From dd08ed9533e587a8158eb3414bb7711b20b4529a Mon Sep 17 00:00:00 2001 From: Mitchell O'Hara-Wild Date: Tue, 18 Feb 2025 17:05:56 +1100 Subject: [PATCH] Convert w1 activities from webr-teachr to quarto-live + qlcheckr --- _extensions/r-wasm/live/_extension.yml | 15 + _extensions/r-wasm/live/_gradethis.qmd | 40 + _extensions/r-wasm/live/_knitr.qmd | 32 + _extensions/r-wasm/live/live.lua | 733 +++++++++++++++ .../r-wasm/live/resources/live-runtime.css | 1 + .../r-wasm/live/resources/live-runtime.js | 130 +++ .../r-wasm/live/resources/pyodide-worker.js | 18 + .../r-wasm/live/resources/tinyyaml.lua | 883 ++++++++++++++++++ .../r-wasm/live/templates/interpolate.ojs | 16 + .../r-wasm/live/templates/pyodide-editor.ojs | 16 + .../live/templates/pyodide-evaluate.ojs | 41 + .../live/templates/pyodide-exercise.ojs | 30 + .../r-wasm/live/templates/pyodide-setup.ojs | 129 +++ .../r-wasm/live/templates/webr-editor.ojs | 11 + .../r-wasm/live/templates/webr-evaluate.ojs | 40 + .../r-wasm/live/templates/webr-exercise.ojs | 29 + .../r-wasm/live/templates/webr-setup.ojs | 123 +++ .../r-wasm/live/templates/webr-widget.ojs | 10 + week1/activities.qmd | 298 ++++-- 19 files changed, 2542 insertions(+), 53 deletions(-) create mode 100644 _extensions/r-wasm/live/_extension.yml create mode 100644 _extensions/r-wasm/live/_gradethis.qmd create mode 100644 _extensions/r-wasm/live/_knitr.qmd create mode 100644 _extensions/r-wasm/live/live.lua create mode 100644 _extensions/r-wasm/live/resources/live-runtime.css create mode 100644 _extensions/r-wasm/live/resources/live-runtime.js create mode 100644 _extensions/r-wasm/live/resources/pyodide-worker.js create mode 100644 _extensions/r-wasm/live/resources/tinyyaml.lua create mode 100644 _extensions/r-wasm/live/templates/interpolate.ojs create mode 100644 _extensions/r-wasm/live/templates/pyodide-editor.ojs create mode 100644 _extensions/r-wasm/live/templates/pyodide-evaluate.ojs create mode 100644 _extensions/r-wasm/live/templates/pyodide-exercise.ojs create mode 100644 _extensions/r-wasm/live/templates/pyodide-setup.ojs create mode 100644 _extensions/r-wasm/live/templates/webr-editor.ojs create mode 100644 _extensions/r-wasm/live/templates/webr-evaluate.ojs create mode 100644 _extensions/r-wasm/live/templates/webr-exercise.ojs create mode 100644 _extensions/r-wasm/live/templates/webr-setup.ojs create mode 100644 _extensions/r-wasm/live/templates/webr-widget.ojs diff --git a/_extensions/r-wasm/live/_extension.yml b/_extensions/r-wasm/live/_extension.yml new file mode 100644 index 0000000..cd325cb --- /dev/null +++ b/_extensions/r-wasm/live/_extension.yml @@ -0,0 +1,15 @@ +title: Quarto Live +author: George Stagg +version: 0.1.2-dev +quarto-required: ">=1.4.0" +contributes: + filters: + - live.lua + formats: + common: + ojs-engine: true + filters: + - live.lua + html: default + revealjs: default + dashboard: default diff --git a/_extensions/r-wasm/live/_gradethis.qmd b/_extensions/r-wasm/live/_gradethis.qmd new file mode 100644 index 0000000..bd0186f --- /dev/null +++ b/_extensions/r-wasm/live/_gradethis.qmd @@ -0,0 +1,40 @@ +```{webr} +#| edit: false +#| output: false +webr::install("gradethis", quiet = TRUE) +library(gradethis) +options(webr.exercise.checker = function( + label, user_code, solution_code, check_code, envir_result, evaluate_result, + envir_prep, last_value, engine, stage, ... +) { + if (is.null(check_code)) { + # No grading code, so just skip grading + invisible(NULL) + } else if (is.null(label)) { + list( + correct = FALSE, + type = "warning", + message = "All exercises must have a label." + ) + } else if (is.null(solution_code)) { + list( + correct = FALSE, + type = "warning", + message = htmltools::tags$div( + htmltools::tags$p("A problem occurred grading this exercise."), + htmltools::tags$p( + "No solution code was found. Note that grading exercises using the ", + htmltools::tags$code("gradethis"), + "package requires a model solution to be included in the document." + ) + ) + ) + } else { + gradethis::gradethis_exercise_checker( + label = label, solution_code = solution_code, user_code = user_code, + check_code = check_code, envir_result = envir_result, + evaluate_result = evaluate_result, envir_prep = envir_prep, + last_value = last_value, stage = stage, engine = engine) + } +}) +``` diff --git a/_extensions/r-wasm/live/_knitr.qmd b/_extensions/r-wasm/live/_knitr.qmd new file mode 100644 index 0000000..5bfca80 --- /dev/null +++ b/_extensions/r-wasm/live/_knitr.qmd @@ -0,0 +1,32 @@ +```{r echo=FALSE} +# Setup knitr for handling {webr} and {pyodide} blocks +# TODO: With quarto-dev/quarto-cli#10169, we can implement this in a filter + +# We'll handle `include: false` in Lua, always include cell in knitr output +knitr::opts_hooks$set(include = function(options) { + if (options$engine == "webr" || options$engine == "pyodide") { + options$include <- TRUE + } + options +}) + +# Passthrough engine for webr +knitr::knit_engines$set(webr = function(options) { + knitr:::one_string(c( + "```{webr}", + options$yaml.code, + options$code, + "```" + )) +}) + +# Passthrough engine for pyodide +knitr::knit_engines$set(pyodide = function(options) { + knitr:::one_string(c( + "```{pyodide}", + options$yaml.code, + options$code, + "```" + )) +}) +``` diff --git a/_extensions/r-wasm/live/live.lua b/_extensions/r-wasm/live/live.lua new file mode 100644 index 0000000..08c29c6 --- /dev/null +++ b/_extensions/r-wasm/live/live.lua @@ -0,0 +1,733 @@ +local tinyyaml = require "resources/tinyyaml" + +local cell_options = { + webr = { eval = true }, + pyodide = { eval = true }, +} + +local live_options = { + ["show-solutions"] = true, + ["show-hints"] = true, + ["grading"] = true, +} + +local ojs_definitions = { + contents = {}, +} +local block_id = 0 + +local include_webr = false +local include_pyodide = false + +local function json_as_b64(obj) + local json_string = quarto.json.encode(obj) + return quarto.base64.encode(json_string) +end + +local function tree(root) + function isdir(path) + -- Is there a better OS agnostic way to do this? + local ok, err, code = os.rename(path .. "/", path .. "/") + if not ok then + if code == 13 then + -- Permission denied, but it exists + return true + end + end + return ok, err + end + + function gather(path, list) + if (isdir(path)) then + -- For each item in this dir, recurse for subdir content + local items = pandoc.system.list_directory(path) + for _, item in pairs(items) do + gather(path .. "/" .. item, list) + end + else + -- This is a file, add it to the table directly + table.insert(list, path) + end + return list + end + + return gather(root, {}) +end + +function ParseBlock(block, engine) + local attr = {} + local param_lines = {} + local code_lines = {} + for line in block.text:gmatch("([^\r\n]*)[\r\n]?") do + local param_line = string.find(line, "^#|") + if (param_line ~= nil) then + table.insert(param_lines, string.sub(line, 4)) + else + table.insert(code_lines, line) + end + end + local code = table.concat(code_lines, "\n") + + -- Include cell-options defaults + for k, v in pairs(cell_options[engine]) do + attr[k] = v + end + + -- Parse quarto-style yaml attributes + local param_yaml = table.concat(param_lines, "\n") + if (param_yaml ~= "") then + param_attr = tinyyaml.parse(param_yaml) + for k, v in pairs(param_attr) do + attr[k] = v + end + end + + -- Parse traditional knitr-style attributes + for k, v in pairs(block.attributes) do + local function toboolean(v) + return string.lower(v) == "true" + end + + local convert = { + autorun = toboolean, + runbutton = toboolean, + echo = toboolean, + edit = toboolean, + error = toboolean, + eval = toboolean, + include = toboolean, + output = toboolean, + startover = toboolean, + solution = toboolean, + warning = toboolean, + timelimit = tonumber, + ["fig-width"] = tonumber, + ["fig-height"] = tonumber, + } + + if (convert[k]) then + attr[k] = convert[k](v) + else + attr[k] = v + end + end + + -- When echo: false: disable the editor + if (attr.echo == false) then + attr.edit = false + end + + -- When `include: false`: disable the editor, source block echo, and output + if (attr.include == false) then + attr.edit = false + attr.echo = false + attr.output = false + end + + -- If we're not executing anything, there's no point showing an editor + if (attr.edit == nil) then + attr.edit = attr.eval + end + + return { + code = code, + attr = attr + } +end + +local exercise_keys = {} +function assertUniqueExercise(key) + if (exercise_keys[key]) then + error("Document contains multiple exercises with key `" .. tostring(key) .. + "`." .. "Exercise keys must be unique.") + end + exercise_keys[key] = true +end + +function assertBlockExercise(type, engine, block) + if (not block.attr.exercise) then + error("Can't create `" .. engine .. "` " .. type .. + " block, `exercise` not defined in cell options.") + end +end + +function ExerciseDataBlocks(btype, block) + local ex = block.attr.exercise + if (type(ex) ~= "table") then + ex = { ex } + end + + local blocks = {} + for idx, ex_id in pairs(ex) do + blocks[idx] = pandoc.RawBlock( + "html", + "" + ) + end + return blocks +end + +function PyodideCodeBlock(code) + block_id = block_id + 1 + + function append_ojs_template(template, template_vars) + local file = io.open(quarto.utils.resolve_path("templates/" .. template), "r") + assert(file) + local content = file:read("*a") + for k, v in pairs(template_vars) do + content = string.gsub(content, "{{" .. k .. "}}", v) + end + + table.insert(ojs_definitions.contents, 1, { + methodName = "interpret", + cellName = "pyodide-" .. block_id, + inline = false, + source = content, + }) + end + + -- Parse codeblock contents for YAML header and Python code body + local block = ParseBlock(code, "pyodide") + + if (block.attr.output == "asis") then + quarto.log.warning( + "For `pyodide` code blocks, using `output: asis` renders Python output as HTML.", + "Markdown rendering is not currently supported." + ) + end + + -- Supplementary execise blocks: setup, check, hint, solution + if (block.attr.setup) then + assertBlockExercise("setup", "pyodide", block) + return ExerciseDataBlocks("setup", block) + end + + if (block.attr.check) then + assertBlockExercise("check", "pyodide", block) + if live_options["grading"] then + return ExerciseDataBlocks("check", block) + else + return {} + end + end + + if (block.attr.hint) then + assertBlockExercise("hint", "pyodide", block) + if live_options["show-hints"] then + return pandoc.Div( + InterpolatedBlock( + pandoc.CodeBlock(block.code, pandoc.Attr('', { 'python', 'cell-code' })), + "python" + ), + pandoc.Attr('', + { 'pyodide-ojs-exercise', 'exercise-hint', 'd-none' }, + { exercise = block.attr.exercise } + ) + ) + end + return {} + end + + if (block.attr.solution) then + assertBlockExercise("solution", "pyodide", block) + if live_options["show-solutions"] then + local plaincode = pandoc.Code(block.code, pandoc.Attr('', { 'solution-code', 'd-none' })) + local codeblock = pandoc.CodeBlock(block.code, pandoc.Attr('', { 'python', 'cell-code' })) + return pandoc.Div( + { + InterpolatedBlock(plaincode, "none"), + InterpolatedBlock(codeblock, "python"), + }, + pandoc.Attr('', + { 'pyodide-ojs-exercise', 'exercise-solution', 'd-none' }, + { exercise = block.attr.exercise } + ) + ) + end + return {} + end + + -- Prepare OJS attributes + local input = "{" .. table.concat(block.attr.input or {}, ", ") .. "}" + local ojs_vars = { + block_id = block_id, + block_input = input, + } + + -- Render appropriate OJS for the type of client-side block we're working with + local ojs_source = nil + if (block.attr.exercise) then + -- Primary interactive exercise block + assertUniqueExercise(block.attr.exercise) + ojs_source = "pyodide-exercise.ojs" + elseif (block.attr.edit) then + -- Editable non-exercise sandbox block + ojs_source = "pyodide-editor.ojs" + else + -- Non-interactive evaluation block + ojs_source = "pyodide-evaluate.ojs" + end + + append_ojs_template(ojs_source, ojs_vars) + + return pandoc.Div({ + pandoc.Div({}, pandoc.Attr("pyodide-" .. block_id, { 'exercise-cell' })), + pandoc.RawBlock( + "html", + "" + ) + }) +end + +function WebRCodeBlock(code) + block_id = block_id + 1 + + function append_ojs_template(template, template_vars) + local file = io.open(quarto.utils.resolve_path("templates/" .. template), "r") + assert(file) + local content = file:read("*a") + for k, v in pairs(template_vars) do + content = string.gsub(content, "{{" .. k .. "}}", v) + end + + table.insert(ojs_definitions.contents, 1, { + methodName = "interpret", + cellName = "webr-" .. block_id, + inline = false, + source = content, + }) + end + + -- Parse codeblock contents for YAML header and R code body + local block = ParseBlock(code, "webr") + + if (block.attr.output == "asis") then + quarto.log.warning( + "For `webr` code blocks, using `output: asis` renders R output as HTML.", + "Markdown rendering is not currently supported." + ) + end + + -- Supplementary execise blocks: setup, check, hint, solution + if (block.attr.setup) then + assertBlockExercise("setup", "webr", block) + return ExerciseDataBlocks("setup", block) + end + + if (block.attr.check) then + assertBlockExercise("check", "webr", block) + if live_options["grading"] then + return ExerciseDataBlocks("check", block) + else + return {} + end + end + + if (block.attr.hint) then + assertBlockExercise("hint", "webr", block) + if live_options["show-hints"] then + return pandoc.Div( + InterpolatedBlock( + pandoc.CodeBlock(block.code, pandoc.Attr('', { 'r', 'cell-code' })), + "r" + ), + pandoc.Attr('', + { 'webr-ojs-exercise', 'exercise-hint', 'd-none' }, + { exercise = block.attr.exercise } + ) + ) + end + return {} + end + + if (block.attr.solution) then + assertBlockExercise("solution", "webr", block) + if live_options["show-solutions"] then + local plaincode = pandoc.Code(block.code, pandoc.Attr('', { 'solution-code', 'd-none' })) + local codeblock = pandoc.CodeBlock(block.code, pandoc.Attr('', { 'r', 'cell-code' })) + return pandoc.Div( + { + InterpolatedBlock(plaincode, "none"), + InterpolatedBlock(codeblock, "r"), + }, + pandoc.Attr('', + { 'webr-ojs-exercise', 'exercise-solution', 'd-none' }, + { exercise = block.attr.exercise } + ) + ) + end + return {} + end + + -- Prepare OJS attributes + local input = "{" .. table.concat(block.attr.input or {}, ", ") .. "}" + local ojs_vars = { + block_id = block_id, + block_input = input, + } + + -- Render appropriate OJS for the type of client-side block we're working with + local ojs_source = nil + if (block.attr.exercise) then + -- Primary interactive exercise block + assertUniqueExercise(block.attr.exercise) + ojs_source = "webr-exercise.ojs" + elseif (block.attr.edit) then + -- Editable non-exercise sandbox block + ojs_source = "webr-editor.ojs" + else + -- Non-interactive evaluation block + ojs_source = "webr-evaluate.ojs" + end + + append_ojs_template(ojs_source, ojs_vars) + + -- Render any HTMLWidgets after HTML output has been added to the DOM + HTMLWidget(block_id) + + return pandoc.Div({ + pandoc.Div({}, pandoc.Attr("webr-" .. block_id, { 'exercise-cell' })), + pandoc.RawBlock( + "html", + "" + ) + }) +end + +function InterpolatedBlock(block, language) + block_id = block_id + 1 + + -- Reactively render OJS variables in codeblocks + file = io.open(quarto.utils.resolve_path("templates/interpolate.ojs"), "r") + assert(file) + content = file:read("*a") + + -- Build map of OJS variable names to JS template literals + local map = "{\n" + for var in block.text:gmatch("${([a-zA-Z_$][%w_$]+)}") do + map = map .. var .. ",\n" + end + map = map .. "}" + + -- We add this OJS block for its side effect of updating the HTML element + content = string.gsub(content, "{{block_id}}", block_id) + content = string.gsub(content, "{{def_map}}", map) + content = string.gsub(content, "{{language}}", language) + table.insert(ojs_definitions.contents, { + methodName = "interpretQuiet", + cellName = "interpolate-" .. block_id, + inline = false, + source = content, + }) + + block.identifier = "interpolate-" .. block_id + return block +end + +function CodeBlock(code) + if ( + code.classes:includes("{webr}") or + code.classes:includes("webr") or + code.classes:includes("{webr-r}") + ) then + -- Client side R code block + include_webr = true + return WebRCodeBlock(code) + end + + if ( + code.classes:includes("{pyodide}") or + code.classes:includes("pyodide") or + code.classes:includes("{pyodide-python}") + ) then + -- Client side Python code block + include_pyodide = true + return PyodideCodeBlock(code) + end + + -- Non-interactive code block containing OJS variables + if (string.match(code.text, "${[a-zA-Z_$][%w_$]+}")) then + if (code.classes:includes("r")) then + include_webr = true + return InterpolatedBlock(code, "r") + elseif (code.classes:includes("python")) then + include_pyodide = true + return InterpolatedBlock(code, "python") + end + end +end + +function HTMLWidget(block_id) + local file = io.open(quarto.utils.resolve_path("templates/webr-widget.ojs"), "r") + assert(file) + content = file:read("*a") + + table.insert(ojs_definitions.contents, 1, { + methodName = "interpretQuiet", + cellName = "webr-widget-" .. block_id, + inline = false, + source = string.gsub(content, "{{block_id}}", block_id), + }) +end + +function Div(block) + -- Render exercise hints with display:none + if (block.classes:includes("hint") and block.attributes["exercise"] ~= nil) then + if live_options["show-hints"] then + block.classes:insert("webr-ojs-exercise") + block.classes:insert("exercise-hint") + block.classes:insert("d-none") + return block + else + return {} + end + end +end + +function Proof(block) + -- Quarto wraps solution blocks in a Proof structure + -- Dig into the expected shape and look for our own exercise solutions + if (block["type"] == "Solution") then + local content = block["__quarto_custom_node"] + local container = content.c[1] + if (container) then + local solution = container.c[1] + if (solution) then + if (solution.attributes["exercise"] ~= nil) then + if live_options["show-solutions"] then + solution.classes:insert("webr-ojs-exercise") + solution.classes:insert("exercise-solution") + solution.classes:insert("d-none") + return solution + else + return {} + end + end + end + end + end +end + +function setupPyodide(doc) + local pyodide = doc.meta.pyodide or {} + local packages = pyodide.packages or {} + + local file = io.open(quarto.utils.resolve_path("templates/pyodide-setup.ojs"), "r") + assert(file) + local content = file:read("*a") + + local pyodide_packages = { + pkgs = { "pyodide_http", "micropip", "ipython" }, + } + for _, pkg in pairs(packages) do + table.insert(pyodide_packages.pkgs, pandoc.utils.stringify(pkg)) + end + + -- Initial Pyodide startup options + local pyodide_options = { + indexURL = "https://cdn.jsdelivr.net/pyodide/v0.26.1/full/", + } + if (pyodide["engine-url"]) then + pyodide_options["indexURL"] = pandoc.utils.stringify(pyodide["engine-url"]) + end + + local data = { + packages = pyodide_packages, + options = pyodide_options, + } + + table.insert(ojs_definitions.contents, { + methodName = "interpretQuiet", + cellName = "pyodide-prelude", + inline = false, + source = content, + }) + + doc.blocks:insert(pandoc.RawBlock( + "html", + "" + )) + + return pyodide +end + +function setupWebR(doc) + local webr = doc.meta.webr or {} + local packages = webr.packages or {} + local repos = webr.repos or {} + + local file = io.open(quarto.utils.resolve_path("templates/webr-setup.ojs"), "r") + assert(file) + local content = file:read("*a") + + -- List of webR R packages and repositories to install + local webr_packages = { + pkgs = { "evaluate", "knitr", "htmltools" }, + repos = {} + } + for _, pkg in pairs(packages) do + table.insert(webr_packages.pkgs, pandoc.utils.stringify(pkg)) + end + for _, repo in pairs(repos) do + table.insert(webr_packages.repos, pandoc.utils.stringify(repo)) + end + + -- Data frame rendering + local webr_render_df = "default" + if (webr["render-df"]) then + webr_render_df = pandoc.utils.stringify(webr["render-df"]) + local pkg = { + ["paged-table"] = "rmarkdown", + ["gt"] = "gt", + ["gt-interactive"] = "gt", + ["dt"] = "DT", + ["reactable"] = "reactable", + } + if (pkg[webr_render_df]) then + table.insert(webr_packages.pkgs, pkg[webr_render_df]) + end + end + + -- Initial webR startup options + local webr_options = { + baseUrl = "https://webr.r-wasm.org/v0.4.1/" + } + if (webr["engine-url"]) then + webr_options["baseUrl"] = pandoc.utils.stringify(webr["engine-url"]) + end + + local data = { + packages = webr_packages, + options = webr_options, + render_df = webr_render_df, + } + + table.insert(ojs_definitions.contents, { + methodName = "interpretQuiet", + cellName = "webr-prelude", + inline = false, + source = content, + }) + + doc.blocks:insert(pandoc.RawBlock( + "html", + "" + )) + + return webr +end + +function Pandoc(doc) + local webr = nil + local pyodide = nil + if (include_webr) then + webr = setupWebR(doc) + end + if (include_pyodide) then + pyodide = setupPyodide(doc) + end + + -- OJS block definitions + doc.blocks:insert(pandoc.RawBlock( + "html", + "" + )) + + -- Loading indicator + doc.blocks:insert( + pandoc.Div({ + pandoc.Div({}, pandoc.Attr("exercise-loading-status", { "d-flex", "gap-2" })), + pandoc.Div({}, pandoc.Attr("", { "spinner-grow", "spinner-grow-sm" })), + }, pandoc.Attr( + "exercise-loading-indicator", + { "exercise-loading-indicator", "d-none", "d-flex", "align-items-center", "gap-2" } + )) + ) + + -- Exercise runtime dependencies + quarto.doc.add_html_dependency({ + name = 'live-runtime', + scripts = { + { path = "resources/live-runtime.js", attribs = { type = "module" } }, + }, + resources = { "resources/pyodide-worker.js" }, + stylesheets = { "resources/live-runtime.css" }, + }) + + -- Copy resources for upload to VFS at runtime + local vfs_files = {} + if (webr and webr.resources) then + resource_list = webr.resources + elseif (pyodide and pyodide.resources) then + resource_list = pyodide.resources + else + resource_list = doc.meta.resources + end + + if (type(resource_list) ~= "table") then + resource_list = { resource_list } + end + + if (resource_list) then + for _, files in pairs(resource_list) do + if (type(files) ~= "table") then + files = { files } + end + for _, file in pairs(files) do + local filetree = tree(pandoc.utils.stringify(file)) + for _, path in pairs(filetree) do + table.insert(vfs_files, path) + end + end + end + end + doc.blocks:insert(pandoc.RawBlock( + "html", + "" + )) + return doc +end + +function Meta(meta) + local webr = meta.webr or {} + + for k, v in pairs(webr["cell-options"] or {}) do + if (type(v) == "table") then + cell_options.webr[k] = pandoc.utils.stringify(v) + else + cell_options.webr[k] = v + end + end + + local pyodide = meta.pyodide or {} + + for k, v in pairs(pyodide["cell-options"] or {}) do + if (type(v) == "table") then + cell_options.pyodide[k] = pandoc.utils.stringify(v) + else + cell_options.pyodide[k] = v + end + end + + local live = meta.live or {} + if (type(live) == "table") then + for k, v in pairs(live) do + live_options[k] = v + end + else + quarto.log.error("Invalid value for document yaml key: `live`.") + end +end + +return { + { Meta = Meta }, + { + Div = Div, + Proof = Proof, + CodeBlock = CodeBlock, + Pandoc = Pandoc, + }, +} diff --git a/_extensions/r-wasm/live/resources/live-runtime.css b/_extensions/r-wasm/live/resources/live-runtime.css new file mode 100644 index 0000000..8086a85 --- /dev/null +++ b/_extensions/r-wasm/live/resources/live-runtime.css @@ -0,0 +1 @@ +.quarto-light{--exercise-main-color: var(--bs-body-color, var(--r-main-color, #212529));--exercise-main-bg: var(--bs-body-bg, var(--r-background-color, #ffffff));--exercise-primary-rgb: var(--bs-primary-rgb, 13, 110, 253);--exercise-gray: var(--bs-gray-300, #dee2e6);--exercise-cap-bg: var(--bs-light-bg-subtle, #f8f8f8);--exercise-line-bg: rgba(var(--exercise-primary-rgb), .05);--exercise-line-gutter-bg: rgba(var(--exercise-primary-rgb), .1)}.quarto-dark{--exercise-main-color: var(--bs-body-color, var(--r-main-color, #ffffff));--exercise-main-bg: var(--bs-body-bg, var(--r-background-color, #222222));--exercise-primary-rgb: var(--bs-primary-rgb, 55, 90, 127);--exercise-gray: var(--bs-gray-700, #434343);--exercise-cap-bg: var(--bs-card-cap-bg, #505050);--exercise-line-bg: rgba(var(--exercise-primary-rgb), .2);--exercise-line-gutter-bg: rgba(var(--exercise-primary-rgb), .4)}.webr-ojs-exercise.exercise-solution,.webr-ojs-exercise.exercise-hint{border:var(--exercise-gray) 1px solid;border-radius:5px;padding:1rem}.exercise-hint .exercise-hint,.exercise-solution .exercise-solution{border:none;padding:0}.webr-ojs-exercise.exercise-solution>.callout,.webr-ojs-exercise.exercise-hint>.callout{margin:-1rem;border:0}#exercise-loading-indicator{position:fixed;bottom:0;right:0;font-size:1.2rem;padding:.2rem .75rem;border:1px solid var(--exercise-gray);background-color:var(--exercise-cap-bg);border-top-left-radius:5px}#exercise-loading-indicator>.spinner-grow{min-width:1rem}.exercise-loading-details+.exercise-loading-details:before{content:"/ "}@media only screen and (max-width: 576px){#exercise-loading-indicator{font-size:.8rem;padding:.1rem .5rem}#exercise-loading-indicator>.spinner-grow{min-width:.66rem}#exercise-loading-indicator .gap-2{gap:.2rem!important}#exercise-loading-indicator .spinner-grow{--bs-spinner-width: .66rem;--bs-spinner-height: .66rem}}.btn.btn-exercise-editor:disabled,.btn.btn-exercise-editor.disabled,.btn-exercise-editor fieldset:disabled .btn{transition:opacity .5s}.card.exercise-editor .card-header a.btn{--bs-btn-padding-x: .5rem;--bs-btn-padding-y: .15rem;--bs-btn-font-size: .75rem}.quarto-dark .card.exercise-editor .card-header .btn.btn-outline-dark{--bs-btn-color: #f8f8f8;--bs-btn-border-color: #f8f8f8;--bs-btn-hover-color: #000;--bs-btn-hover-bg: #f8f8f8;--bs-btn-hover-border-color: #f8f8f8;--bs-btn-focus-shadow-rgb: 248, 248, 248;--bs-btn-active-color: #000;--bs-btn-active-bg: #f8f8f8;--bs-btn-active-border-color: #f8f8f8;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);--bs-btn-disabled-color: #f8f8f8;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #f8f8f8;--bs-btn-bg: transparent;--bs-gradient: none}.card.exercise-editor{--exercise-min-lines: 0;--exercise-max-lines: infinity;--exercise-font-size: var(--bs-body-font-size, 1rem)}.card.exercise-editor .card-header{padding:.5rem 1rem;background-color:var(--exercise-cap-bg);border-bottom:1px solid rgba(0,0,0,.175)}.card.exercise-editor .cm-editor{color:var(--exercise-main-color);background-color:var(--exercise-main-bg);max-height:calc(var(--exercise-max-lines) * 1.4 * var(--exercise-font-size) + 8px)}.card.exercise-editor .cm-content{caret-color:var(--exercise-main-color)}.card.exercise-editor .cm-cursor,.card.exercise-editor .cm-dropCursor{border-left-color:var(--exercise-main-color)}.card.exercise-editor .cm-focused .cm-selectionBackgroundm .cm-selectionBackground,.card.exercise-editor .cm-content ::selection{background-color:rgba(var(--exercise-primary-rgb),.1)}.card.exercise-editor .cm-activeLine{background-color:var(--exercise-line-bg)}.card.exercise-editor .cm-activeLineGutter{background-color:var(--exercise-line-gutter-bg)}.card.exercise-editor .cm-gutters{background-color:var(--exercise-cap-bg);color:var(--exercise-main-color);border-right:1px solid var(--exercise-gray)}.card.exercise-editor .cm-content,.card.exercise-editor .cm-gutter{min-height:calc(var(--exercise-min-lines) * 1.4 * var(--exercise-font-size) + 8px)}.card.exercise-editor .cm-scroller{line-height:1.4;overflow:auto}:root{--exercise-editor-hl-al: var(--quarto-hl-al-color, #AD0000);--exercise-editor-hl-an: var(--quarto-hl-an-color, #5E5E5E);--exercise-editor-hl-at: var(--quarto-hl-at-color, #657422);--exercise-editor-hl-bn: var(--quarto-hl-bn-color, #AD0000);--exercise-editor-hl-ch: var(--quarto-hl-ch-color, #20794D);--exercise-editor-hl-co: var(--quarto-hl-co-color, #5E5E5E);--exercise-editor-hl-cv: var(--quarto-hl-cv-color, #5E5E5E);--exercise-editor-hl-cn: var(--quarto-hl-cn-color, #8f5902);--exercise-editor-hl-cf: var(--quarto-hl-cf-color, #003B4F);--exercise-editor-hl-dt: var(--quarto-hl-dt-color, #AD0000);--exercise-editor-hl-dv: var(--quarto-hl-dv-color, #AD0000);--exercise-editor-hl-do: var(--quarto-hl-do-color, #5E5E5E);--exercise-editor-hl-er: var(--quarto-hl-er-color, #AD0000);--exercise-editor-hl-fl: var(--quarto-hl-fl-color, #AD0000);--exercise-editor-hl-fu: var(--quarto-hl-fu-color, #4758AB);--exercise-editor-hl-im: var(--quarto-hl-im-color, #00769E);--exercise-editor-hl-in: var(--quarto-hl-in-color, #5E5E5E);--exercise-editor-hl-kw: var(--quarto-hl-kw-color, #003B4F);--exercise-editor-hl-op: var(--quarto-hl-op-color, #5E5E5E);--exercise-editor-hl-ot: var(--quarto-hl-ot-color, #003B4F);--exercise-editor-hl-pp: var(--quarto-hl-pp-color, #AD0000);--exercise-editor-hl-sc: var(--quarto-hl-sc-color, #5E5E5E);--exercise-editor-hl-ss: var(--quarto-hl-ss-color, #20794D);--exercise-editor-hl-st: var(--quarto-hl-st-color, #20794D);--exercise-editor-hl-va: var(--quarto-hl-va-color, #111111);--exercise-editor-hl-vs: var(--quarto-hl-vs-color, #20794D);--exercise-editor-hl-wa: var(--quarto-hl-wa-color, #5E5E5E)}*[data-bs-theme=dark]{--exercise-editor-hl-al: var(--quarto-hl-al-color, #f07178);--exercise-editor-hl-an: var(--quarto-hl-an-color, #d4d0ab);--exercise-editor-hl-at: var(--quarto-hl-at-color, #00e0e0);--exercise-editor-hl-bn: var(--quarto-hl-bn-color, #d4d0ab);--exercise-editor-hl-bu: var(--quarto-hl-bu-color, #abe338);--exercise-editor-hl-ch: var(--quarto-hl-ch-color, #abe338);--exercise-editor-hl-co: var(--quarto-hl-co-color, #f8f8f2);--exercise-editor-hl-cv: var(--quarto-hl-cv-color, #ffd700);--exercise-editor-hl-cn: var(--quarto-hl-cn-color, #ffd700);--exercise-editor-hl-cf: var(--quarto-hl-cf-color, #ffa07a);--exercise-editor-hl-dt: var(--quarto-hl-dt-color, #ffa07a);--exercise-editor-hl-dv: var(--quarto-hl-dv-color, #d4d0ab);--exercise-editor-hl-do: var(--quarto-hl-do-color, #f8f8f2);--exercise-editor-hl-er: var(--quarto-hl-er-color, #f07178);--exercise-editor-hl-ex: var(--quarto-hl-ex-color, #00e0e0);--exercise-editor-hl-fl: var(--quarto-hl-fl-color, #d4d0ab);--exercise-editor-hl-fu: var(--quarto-hl-fu-color, #ffa07a);--exercise-editor-hl-im: var(--quarto-hl-im-color, #abe338);--exercise-editor-hl-in: var(--quarto-hl-in-color, #d4d0ab);--exercise-editor-hl-kw: var(--quarto-hl-kw-color, #ffa07a);--exercise-editor-hl-op: var(--quarto-hl-op-color, #ffa07a);--exercise-editor-hl-ot: var(--quarto-hl-ot-color, #00e0e0);--exercise-editor-hl-pp: var(--quarto-hl-pp-color, #dcc6e0);--exercise-editor-hl-re: var(--quarto-hl-re-color, #00e0e0);--exercise-editor-hl-sc: var(--quarto-hl-sc-color, #abe338);--exercise-editor-hl-ss: var(--quarto-hl-ss-color, #abe338);--exercise-editor-hl-st: var(--quarto-hl-st-color, #abe338);--exercise-editor-hl-va: var(--quarto-hl-va-color, #00e0e0);--exercise-editor-hl-vs: var(--quarto-hl-vs-color, #abe338);--exercise-editor-hl-wa: var(--quarto-hl-wa-color, #dcc6e0)}pre>code.sourceCode span.tok-keyword,.exercise-editor-body>.cm-editor span.tok-keyword{color:var(--exercise-editor-hl-kw)}pre>code.sourceCode span.tok-operator,.exercise-editor-body>.cm-editor span.tok-operator{color:var(--exercise-editor-hl-op)}pre>code.sourceCode span.tok-definitionOperator,.exercise-editor-body>.cm-editor span.tok-definitionOperator{color:var(--exercise-editor-hl-ot)}pre>code.sourceCode span.tok-compareOperator,.exercise-editor-body>.cm-editor span.tok-compareOperator{color:var(--exercise-editor-hl-ot)}pre>code.sourceCode span.tok-attributeName,.exercise-editor-body>.cm-editor span.tok-attributeName{color:var(--exercise-editor-hl-at)}pre>code.sourceCode span.tok-controlKeyword,.exercise-editor-body>.cm-editor span.tok-controlKeyword{color:var(--exercise-editor-hl-cf)}pre>code.sourceCode span.tok-comment,.exercise-editor-body>.cm-editor span.tok-comment{color:var(--exercise-editor-hl-co)}pre>code.sourceCode span.tok-string,.exercise-editor-body>.cm-editor span.tok-string{color:var(--exercise-editor-hl-st)}pre>code.sourceCode span.tok-string2,.exercise-editor-body>.cm-editor span.tok-string2{color:var(--exercise-editor-hl-ss)}pre>code.sourceCode span.tok-variableName,.exercise-editor-body>.cm-editor span.tok-variableName{color:var(--exercise-editor-hl-va)}pre>code.sourceCode span.tok-bool,pre>code.sourceCode span.tok-literal,pre>code.sourceCode span.tok-separator,.exercise-editor-body>.cm-editor span.tok-bool,.exercise-editor-body>.cm-editor span.tok-literal,.exercise-editor-body>.cm-editor span.tok-separator{color:var(--exercise-editor-hl-cn)}pre>code.sourceCode span.tok-bool,pre>code.sourceCode span.tok-literal,.exercise-editor-body>.cm-editor span.tok-bool,.exercise-editor-body>.cm-editor span.tok-literal{color:var(--exercise-editor-hl-cn)}pre>code.sourceCode span.tok-number,pre>code.sourceCode span.tok-integer,.exercise-editor-body>.cm-editor span.tok-number,.exercise-editor-body>.cm-editor span.tok-integer{color:var(--exercise-editor-hl-dv)}pre>code.sourceCode span.tok-function-variableName,.exercise-editor-body>.cm-editor span.tok-function-variableName{color:var(--exercise-editor-hl-fu)}pre>code.sourceCode span.tok-function-attributeName,.exercise-editor-body>.cm-editor span.tok-function-attributeName{color:var(--exercise-editor-hl-at)}div.exercise-cell-output.cell-output-stdout pre code,div.exercise-cell-output.cell-output-stderr pre code{white-space:pre-wrap;word-wrap:break-word}div.exercise-cell-output.cell-output-stderr pre code{color:var(--exercise-editor-hl-er, #AD0000)}div.cell-output-pyodide table{border:none;margin:0 auto 1em}div.cell-output-pyodide thead{border-bottom:1px solid var(--exercise-main-color)}div.cell-output-pyodide td,div.cell-output-pyodide th,div.cell-output-pyodide tr{padding:.5em;line-height:normal}div.cell-output-pyodide th{font-weight:700}div.cell-output-display canvas{background-color:#fff}.tab-pane>.exercise-tab-pane-header+div.webr-ojs-exercise{margin-top:1em}.alert .exercise-feedback p:last-child{margin-bottom:0}.alert.exercise-grade{animation-duration:.25s;animation-name:exercise-grade-slidein}@keyframes exercise-grade-slidein{0%{transform:translateY(10px);opacity:0}to{transform:translateY(0);opacity:1}}.alert.exercise-grade p:last-child{margin-bottom:0}.alert.exercise-grade pre{white-space:pre-wrap;color:inherit}.observablehq pre>code.sourceCode{white-space:pre;position:relative}.observablehq div.sourceCode{margin:1em 0!important}.observablehq pre.sourceCode{margin:0!important}@media screen{.observablehq div.sourceCode{overflow:auto}}@media print{.observablehq pre>code.sourceCode{white-space:pre-wrap}.observablehq pre>code.sourceCode>span{text-indent:-5em;padding-left:5em}}.reveal .d-none{display:none!important}.reveal .d-flex{display:flex!important}.reveal .card.exercise-editor .justify-content-between{justify-content:space-between!important}.reveal .card.exercise-editor .align-items-center{align-items:center!important}.reveal .card.exercise-editor .gap-1{gap:.25rem!important}.reveal .card.exercise-editor .gap-2{gap:.5rem!important}.reveal .card.exercise-editor .gap-3{gap:.75rem!important}.reveal .card.exercise-editor{--exercise-font-size: 1.3rem;margin:1rem 0;border:1px solid rgba(0,0,0,.175);border-radius:.375rem;font-size:var(--exercise-font-size);overflow:hidden}.reveal .card.exercise-editor .card-header{padding:.5rem 1rem;background-color:var(--exercise-cap-bg);border-bottom:1px solid rgba(0,0,0,.175)}.reveal .cell-output-webr.cell-output-display,.reveal .cell-output-pyodide.cell-output-display{text-align:center}.quarto-light .reveal .btn.btn-exercise-editor.btn-primary{--exercise-btn-bg: var(--bs-btn-bg, #0d6efd);--exercise-btn-color: var(--bs-btn-color, #ffffff);--exercise-btn-border-color: var(--bs-btn-border-color, #0d6efd);--exercise-btn-hover-border-color: var(--bs-btn-hover-border-color, #0b5ed7);--exercise-btn-hover-bg: var(--bs-btn-hover-bg, #0b5ed7);--exercise-btn-hover-color: var(--bs-btn-hover-color, #ffffff)}.quarto-dark .reveal .btn.btn-exercise-editor.btn-primary{--exercise-btn-bg: var(--bs-btn-bg, #375a7f);--exercise-btn-color: var(--bs-btn-color, #ffffff);--exercise-btn-border-color: var(--bs-btn-border-color, #375a7f);--exercise-btn-hover-border-color: var(--bs-btn-hover-border-color, #2c4866);--exercise-btn-hover-bg: var(--bs-btn-hover-bg, #2c4866);--exercise-btn-hover-color: var(--bs-btn-hover-color, #ffffff)}.quarto-light .reveal .btn.btn-exercise-editor.btn-outline-dark{--exercise-btn-bg: var(--bs-btn-bg, transparent);--exercise-btn-color: var(--bs-btn-color, #333);--exercise-btn-border-color: var(--bs-btn-border-color, #333);--exercise-btn-hover-border-color: var(--bs-btn-hover-border-color, #333);--exercise-btn-hover-bg: var(--bs-btn-hover-bg, #333);--exercise-btn-hover-color: var(--bs-btn-hover-color, #ffffff)}.quarto-dark .reveal .btn.btn-exercise-editor.btn-outline-dark{--exercise-btn-bg: var(--bs-btn-bg, transparent);--exercise-btn-color: var(--bs-btn-color, #f8f8f8);--exercise-btn-border-color: var(--bs-btn-border-color, #f8f8f8);--exercise-btn-hover-border-color: var(--bs-btn-hover-border-color, #f8f8f8);--exercise-btn-hover-bg: var(--bs-btn-hover-bg, #f8f8f8);--exercise-btn-hover-color: var(--bs-btn-hover-color, #000000)}@media only screen and (max-width: 576px){:not(.reveal) .card-header .btn-exercise-editor>.btn-label-exercise-editor{max-width:0px;margin-left:-4px;overflow:hidden;transition:max-width .2s ease-in,margin-left .05s ease-out .2s}:not(.reveal) .card-header .btn-exercise-editor:hover>.btn-label-exercise-editor{position:inherit;max-width:80px;margin-left:0;transition:max-width .2s ease-out .05s,margin-left .05s ease-in}}.reveal .card.exercise-editor .btn-group{border-radius:.375rem;position:relative;display:inline-flex;vertical-align:middle}.reveal .card.exercise-editor .btn-group>.btn{position:relative;flex:1 1 auto}.reveal .card.exercise-editor .btn-group>:not(.btn-check:first-child)+.btn,.reveal .card.exercise-editor .btn-group>.btn-group:not(:first-child){margin-left:-1px}.reveal .card.exercise-editor .btn-group>.btn:not(:last-child):not(.dropdown-toggle),.reveal .card.exercise-editor .btn-group>.btn.dropdown-toggle-split:first-child,.reveal .card.exercise-editor .btn-group>.btn-group:not(:last-child)>.btn{border-top-right-radius:0;border-bottom-right-radius:0}.reveal .card.exercise-editor .btn-group>.btn:nth-child(n+3),.reveal .card.exercise-editor .btn-group>:not(.btn-check)+.btn,.reveal .card.exercise-editor .btn-group>.btn-group:not(:first-child)>.btn{border-top-left-radius:0;border-bottom-left-radius:0}.reveal .btn.btn-exercise-editor{display:inline-block;padding:.25rem .5rem;font-size:1rem;color:var(--exercise-btn-color);background-color:var(--exercise-btn-bg);text-align:center;text-decoration:none;vertical-align:middle;cursor:pointer;user-select:none;border:1px solid var(--exercise-btn-border-color);border-radius:.375rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}.reveal .btn.btn-exercise-editor:hover{color:var(--exercise-btn-hover-color);background-color:var(--exercise-btn-hover-bg);border-color:var(--exercise-btn-hover-border-color)}.reveal .btn.btn-exercise-editor:disabled,.reveal .btn.btn-exercise-editor.disabled,.reveal .btn-exercise-editor fieldset:disabled .btn{pointer-events:none;opacity:.65}.reveal .card.exercise-editor .spinner-grow{background-color:currentcolor;opacity:0;display:inline-block;width:1.5rem;height:1.5rem;vertical-align:-.125em;border-radius:50%;animation:.75s linear infinite spinner-grow}.reveal .cell-output-container pre code{overflow:auto;max-height:initial}.reveal .alert.exercise-grade{font-size:.55em;position:relative;padding:1rem;margin:1rem 0;border-radius:.25rem;color:var(--exercise-alert-color);background-color:var(--exercise-alert-bg);border:1px solid var(--exercise-alert-border-color)}.reveal .alert.exercise-grade .alert-link{font-weight:700;color:var(--exercise-alert-link-color)}.quarto-light .reveal .exercise-grade.alert-info{--exercise-alert-color: #055160;--exercise-alert-bg: #cff4fc;--exercise-alert-border-color: #9eeaf9;--exercise-alert-link-color: #055160}.quarto-light .reveal .exercise-grade.alert-success{--exercise-alert-color: #0a3622;--exercise-alert-bg: #d1e7dd;--exercise-alert-border-color: #a3cfbb;--exercise-alert-link-color: #0a3622}.quarto-light .reveal .exercise-grade.alert-warning{--exercise-alert-color: #664d03;--exercise-alert-bg: #fff3cd;--exercise-alert-border-color: #ffe69c;--exercise-alert-link-color: #664d03}.quarto-light .reveal .exercise-grade.alert-danger{--exercise-alert-color: #58151c;--exercise-alert-bg: #f8d7da;--exercise-alert-border-color: #f1aeb5;--exercise-alert-link-color: #58151c}.quarto-dark .reveal .exercise-grade.alert-info{--exercise-alert-color: #ffffff;--exercise-alert-bg: #3498db;--exercise-alert-border-color: #3498db;--exercise-alert-link-color: #ffffff}.quarto-dark .reveal .exercise-grade.alert-success{--exercise-alert-color: #ffffff;--exercise-alert-bg: #00bc8c;--exercise-alert-border-color: #00bc8c;--exercise-alert-link-color: #ffffff}.quarto-dark .reveal .exercise-grade.alert-warning{--exercise-alert-color: #ffffff;--exercise-alert-bg: #f39c12;--exercise-alert-border-color: #f39c12;--exercise-alert-link-color: #ffffff}.quarto-dark .reveal .exercise-grade.alert-danger{--exercise-alert-color: #ffffff;--exercise-alert-bg: #e74c3c;--exercise-alert-border-color: #e74c3c;--exercise-alert-link-color: #ffffff} diff --git a/_extensions/r-wasm/live/resources/live-runtime.js b/_extensions/r-wasm/live/resources/live-runtime.js new file mode 100644 index 0000000..d76ed7c --- /dev/null +++ b/_extensions/r-wasm/live/resources/live-runtime.js @@ -0,0 +1,130 @@ +var vO=Object.defineProperty;var ci=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var jt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),xO=(i,e)=>{for(var t in e)vO(i,t,{get:e[t],enumerable:!0})};var iO=jt((RP,Uk)=>{Uk.exports=` + + +`});var nO=jt((EP,Fk)=>{Fk.exports=` + + + +`});var rO=jt((AP,Hk)=>{Hk.exports=` + +`});var sO=jt((QP,Gk)=>{Gk.exports=` + +`});var fO=jt((sC,Kk)=>{Kk.exports="CmltcG9ydCBweW9kaWRlICMgdHlwZTogaWdub3JlW2F0dHItZGVmaW5lZF0KaW1wb3J0IHN5cwoKIyBDbGVhbnVwIGFueSBsZWZ0b3ZlciBtYXRwbG90bGliIHBsb3RzCnRyeToKICBpbXBvcnQgbWF0cGxvdGxpYi5weXBsb3QgYXMgcGx0CiAgcGx0LmNsb3NlKCJhbGwiKQogIHBsdC5yY1BhcmFtc1siZmlndXJlLmZpZ3NpemUiXSA9ICh3aWR0aCwgaGVpZ2h0KSAjIHR5cGU6IGlnbm9yZVthdHRyLWRlZmluZWRdCiAgcGx0LnJjUGFyYW1zWyJmaWd1cmUuZHBpIl0gPSBkcGkgIyB0eXBlOiBpZ25vcmVbYXR0ci1kZWZpbmVkXQpleGNlcHQgTW9kdWxlTm90Rm91bmRFcnJvcjoKICBwYXNzCgpmcm9tIElQeXRob24udXRpbHMgaW1wb3J0IGNhcHR1cmUKZnJvbSBJUHl0aG9uLmRpc3BsYXkgaW1wb3J0IGRpc3BsYXkKZnJvbSBJUHl0aG9uLmNvcmUuaW50ZXJhY3RpdmVzaGVsbCBpbXBvcnQgSW50ZXJhY3RpdmVTaGVsbApJbnRlcmFjdGl2ZVNoZWxsKCkuaW5zdGFuY2UoKQoKd2l0aCBjYXB0dXJlLmNhcHR1cmVfb3V0cHV0KCkgYXMgb3V0cHV0OgogIHZhbHVlID0gTm9uZQogIHRyeToKICAgIHZhbHVlID0gYXdhaXQgcHlvZGlkZS5jb2RlLmV2YWxfY29kZV9hc3luYyhjb2RlLCBnbG9iYWxzID0gZW52aXJvbm1lbnQpICMgdHlwZTogaWdub3JlW2F0dHItZGVmaW5lZF0KICBleGNlcHQgRXhjZXB0aW9uIGFzIGVycjoKICAgIHByaW50KGVyciwgZmlsZT1zeXMuc3RkZXJyKQogIGlmICh2YWx1ZSBpcyBub3QgTm9uZSk6CiAgICBkaXNwbGF5KHZhbHVlKQoKewogICJ2YWx1ZSI6IHZhbHVlLAogICJzdGRvdXQiOiBvdXRwdXQuc3Rkb3V0LAogICJzdGRlcnIiOiBvdXRwdXQuc3RkZXJyLAogICJvdXRwdXRzIjogb3V0cHV0Lm91dHB1dHMsCn0K"});var yO=jt((MC,nS)=>{nS.exports="IyBDcmVhdGUgZW52aXJvbm1lbnQgdG8gaG9sZCB2YXJpYWJsZXMgZXhwb3J0ZWQgd2l0aCBvanNfZGVmaW5lCi53ZWJyX29qcyA8LSBuZXcuZW52KCkKb2pzX2RlZmluZSA8LSBmdW5jdGlvbiguLi4pIHsKICBhcmdzIDwtIGxpc3QoLi4uKQogIG5hbWVzKGFyZ3MpIDwtIHF1b3RlKG1hdGNoLmNhbGwoZXhwYW5kLmRvdHM9VFJVRSlbMTpsZW5ndGgoYXJncykgKyAxXSkKICAud2Vicl9vanMgPDwtIGxpc3QyZW52KGFyZ3MsIGVudmlyID0gLndlYnJfb2pzKQp9CgojIHdlYlIgZ3JhcGhpY3MgZGV2aWNlIHNldHRpbmdzCm9wdGlvbnMod2Vici5maWcud2lkdGggPSA3LCB3ZWJyLmZpZy5oZWlnaHQgPSA1KQppZiAod2Vicjo6ZXZhbF9qcygndHlwZW9mIE9mZnNjcmVlbkNhbnZhcyAhPT0gInVuZGVmaW5lZCInKSkgewogIG9wdGlvbnMoZGV2aWNlID0gZnVuY3Rpb24oLi4uKSB7CiAgICBhcmdzIDwtIGxpc3QoYmcgPSAid2hpdGUiLCAuLi4pCiAgICBhcmdzIDwtIGFyZ3NbIWR1cGxpY2F0ZWQobmFtZXMoYXJncykpXQogICAgZG8uY2FsbCh3ZWJyOjpjYW52YXMsIGFyZ3MpCiAgfSkKfQoKIyBDdXN0b20gcGFnZXIgZm9yIGRpc3BsYXlpbmcgZS5nLiBoZWxwIHBhZ2VzCm9wdGlvbnMocGFnZXIgPSBmdW5jdGlvbihmaWxlcywgLi4uKSB7CiAgd3JpdGVMaW5lcyhnc3ViKCIuW1xiXSIsICIiLCByZWFkTGluZXMoZmlsZXMpKSkKfSkKCiMgQ3VzdG9tIHZhbHVlIGhhbmRsZXIgYW5kIHJlbmRlcmluZyBmb3IgZXZhbHVhdGUgYW5kIGtuaXRyCm9wdGlvbnMoIndlYnIuZXZhbHVhdGUuaGFuZGxlciIgPSBldmFsdWF0ZTo6bmV3X291dHB1dF9oYW5kbGVyKAogIHZhbHVlID0gZnVuY3Rpb24oeCwgdmlzaWJsZSkgewogICAga25pdF9vcHRpb25zID0gbGlzdChzY3JlZW5zaG90LmZvcmNlID0gRkFMU0UpCiAgICByZXMgPC0gaWYgKHZpc2libGUpIHsKICAgICAgd2l0aFZpc2libGUoCiAgICAgICAga25pdHI6OmtuaXRfcHJpbnQoCiAgICAgICAgICBpZiAoaW5oZXJpdHMoeCwgImRhdGEuZnJhbWUiKSkgewogICAgICAgICAgICBzd2l0Y2goCiAgICAgICAgICAgICAgZ2V0T3B0aW9uKCJ3ZWJyLnJlbmRlci5kZiIsICJkZWZhdWx0IiksCiAgICAgICAgICAgICAgImthYmxlIiA9IGtuaXRyOjprYWJsZSh4KSwKICAgICAgICAgICAgICAiZHQiID0gRFQ6OmRhdGF0YWJsZSh4KSwKICAgICAgICAgICAgICAicGFnZWQtdGFibGUiID0gcm1hcmtkb3duOjpwYWdlZF90YWJsZSh4KSwKICAgICAgICAgICAgICAiZ3QiID0gZ3Q6Omd0KHgpLAogICAgICAgICAgICAgICJndC1pbnRlcmFjdGl2ZSIgPSBndDo6b3B0X2ludGVyYWN0aXZlKGd0OjpndCh4KSksCiAgICAgICAgICAgICAgInJlYWN0YWJsZSIgPSByZWFjdGFibGU6OnJlYWN0YWJsZSh4KSwKICAgICAgICAgICAgICB4CiAgICAgICAgICAgICkKICAgICAgICAgIH0gZWxzZSB4LAogICAgICAgIG9wdGlvbnMgPSBrbml0X29wdGlvbnMpCiAgICAgICkKICAgIH0gZWxzZSBsaXN0KHZhbHVlID0geCwgdmlzaWJsZSA9IEZBTFNFKQogICAgcmVzJGNsYXNzIDwtIGNsYXNzKHJlcyR2YWx1ZSkKICAgIGNsYXNzKHJlcykgPC0gInJlc3VsdCIKICAgIHJlcwogIH0KKSkKCiMgQWRkaXRpb25hbCBwYWNrYWdlIG9wdGlvbnMKb3B0aW9ucyhrbml0ci50YWJsZS5mb3JtYXQgPSAiaHRtbCIpCm9wdGlvbnMocmdsLnByaW50Umdsd2lkZ2V0ID0gVFJVRSkKCiMgRGVmYXVsdCBleGVyY2lzZSBncmFkZXIKIyBUT0RPOiBoYW5kbGUgZXJyb3JfY2hlY2sgJiBjb2RlX2NoZWNrIHN0YWdlcwpvcHRpb25zKHdlYnIuZXhlcmNpc2UuY2hlY2tlciA9IGZ1bmN0aW9uKAogIGxhYmVsLCB1c2VyX2NvZGUsIHNvbHV0aW9uX2NvZGUsIGNoZWNrX2NvZGUsIGVudmlyX3Jlc3VsdCwgZXZhbHVhdGVfcmVzdWx0LAogIGVudmlyX3ByZXAsIGxhc3RfdmFsdWUsIGVuZ2luZSwgc3RhZ2UsIC4uLgopIHsKICAjIFNldHVwIGVudmlyb25tZW50CiAgLmxhYmVsIDwtIGxhYmVsCiAgLnVzZXJfY29kZSA8LSB1c2VyX2NvZGUKICAuc29sdXRpb25fY29kZSA8LSBzb2x1dGlvbl9jb2RlCiAgLmNoZWNrX2NvZGUgPC0gY2hlY2tfY29kZQogIC5lbnZpcl9yZXN1bHQgPC0gZW52aXJfcmVzdWx0CiAgLmV2YWx1YXRlX3Jlc3VsdCA8LSBldmFsdWF0ZV9yZXN1bHQKICAuZW52aXJfcHJlcCA8LSBlbnZpcl9wcmVwCiAgLmxhc3RfdmFsdWUgPC0gbGFzdF92YWx1ZQogIC5yZXN1bHQgPC0gbGFzdF92YWx1ZQogIC51c2VyIDwtIGxhc3RfdmFsdWUKICAuZW5naW5lIDwtIGVuZ2luZQogIC5zdGFnZSA8LSBzdGFnZQoKICBpZiAoaXMubnVsbCguY2hlY2tfY29kZSkpIHsKICAgICMgTm8gZ3JhZGluZyBjb2RlLCBzbyBqdXN0IHNraXAgZ3JhZGluZwogICAgcmV0dXJuKGludmlzaWJsZShOVUxMKSkKICB9CgogIHRyeUNhdGNoKHsKICAgICMgUGFyc2UgcHJvdmlkZWQgY2hlY2sgY29kZQogICAgcGFyc2VkX2NoZWNrX2NvZGUgPC0gcGFyc2UodGV4dCA9IGNoZWNrX2NvZGUpCgogICAgIyBFdmFsdWF0ZSBwcm92aWRlZCBjaGVjayBjb2RlCiAgICBldmFsKHBhcnNlZF9jaGVja19jb2RlKQogIH0sIGVycm9yID0gZnVuY3Rpb24oZSkgewogICAgbGlzdCgKICAgICAgbWVzc2FnZSA9IHBhc3RlMCgiRXJyb3IgaW4gY2hlY2tpbmcgY29kZSBmb3IgYCIsIGxhYmVsLCAiYDogIiwgZSRtZXNzYWdlKSwKICAgICAgY29ycmVjdCA9IEZBTFNFLAogICAgICBsb2NhdGlvbiA9ICJhcHBlbmQiLAogICAgICB0eXBlID0gIndhcm5pbmciCiAgICApCiAgfSkKfSkK"});var bO=jt((_C,rS)=>{rS.exports="aW1wb3J0IHN5cwppbXBvcnQgb3MKaW1wb3J0IHB5b2RpZGVfaHR0cCAgIyB0eXBlOiBpZ25vcmVbYXR0ci1kZWZpbmVkXQpweW9kaWRlX2h0dHAucGF0Y2hfYWxsKCkKc3lzLnBhdGguaW5zZXJ0KDAsICIvcHlvZGlkZS8iKQpvcy5ta2Rpcihvcy5wYXRoLmV4cGFuZHVzZXIoIn4vLm1hdHBsb3RsaWIiKSkKZiA9IG9wZW4ob3MucGF0aC5leHBhbmR1c2VyKCJ+Ly5tYXRwbG90bGliL21hdHBsb3RsaWJyYyIpLCAiYSIpCmYud3JpdGUoImJhY2tlbmQ6IG1vZHVsZTovL21hdHBsb3RsaWJfZGlzcGxheSIpCmYuY2xvc2UoKQo="});var wO=jt((DC,sS)=>{sS.exports="IyBCYXNlZCBvbiBweW9kaWRlL21hdHBsb3RsaWJfcHlvZGlkZS9odG1sNV9jYW52YXNfYmFja2VuZC5weQojIE1vZGlmaWVkIGZvciBPZmZzY3JlZW5DYW52YXMgcmVuZGVyaW5nIHVuZGVyIFdlYiBXb3JrZXIKIyBMaWNlbnNlOiBNb3ppbGxhIFB1YmxpYyBMaWNlbnNlIFZlcnNpb24gMi4wCgppbXBvcnQgbWF0aAppbXBvcnQgbnVtcHkgYXMgbnAKZnJvbSBtYXRwbG90bGliLmJhY2tlbmRfYmFzZXMgaW1wb3J0ICgKICAgIEZpZ3VyZUNhbnZhc0Jhc2UsCiAgICBGaWd1cmVNYW5hZ2VyQmFzZSwKICAgIFJlbmRlcmVyQmFzZSwKICAgIEdyYXBoaWNzQ29udGV4dEJhc2UsCiAgICBfQmFja2VuZCwKKQpmcm9tIG1hdHBsb3RsaWIuY2Jvb2sgaW1wb3J0IG1heGRpY3QKZnJvbSBtYXRwbG90bGliLmZvbnRfbWFuYWdlciBpbXBvcnQgZmluZGZvbnQKZnJvbSBtYXRwbG90bGliLmZ0MmZvbnQgaW1wb3J0IExPQURfTk9fSElOVElORywgRlQyRm9udApmcm9tIG1hdHBsb3RsaWIubWF0aHRleHQgaW1wb3J0IE1hdGhUZXh0UGFyc2VyCmZyb20gbWF0cGxvdGxpYi5jb2xvcnMgaW1wb3J0IGNvbG9yQ29udmVydGVyLCByZ2IyaGV4CmZyb20gbWF0cGxvdGxpYi5wYXRoIGltcG9ydCBQYXRoCmZyb20gbWF0cGxvdGxpYi50cmFuc2Zvcm1zIGltcG9ydCBBZmZpbmUyRApmcm9tIElQeXRob24uZGlzcGxheSBpbXBvcnQgZGlzcGxheQpmcm9tIGpzIGltcG9ydCBJbWFnZURhdGEsIE9mZnNjcmVlbkNhbnZhcyAjIHR5cGU6IGlnbm9yZVthdHRyLWRlZmluZWRdCmZyb20gcHlvZGlkZS5mZmkgaW1wb3J0IGNyZWF0ZV9wcm94eSAjIHR5cGU6IGlnbm9yZVthdHRyLWRlZmluZWRdCmltcG9ydCBsb2dnaW5nCgpfY2Fwc3R5bGVfZCA9IHsicHJvamVjdGluZyI6ICJzcXVhcmUiLCAiYnV0dCI6ICJidXR0IiwgInJvdW5kIjogInJvdW5kIn0KbG9nZ2luZy5nZXRMb2dnZXIoJ21hdHBsb3RsaWIuZm9udF9tYW5hZ2VyJykuZGlzYWJsZWQgPSBUcnVlCgpjbGFzcyBSaWNoSW1hZ2VCaXRtYXBPdXRwdXQoKToKICAgIGRlZiBfX2luaXRfXyhzZWxmLCBmaWd1cmUpOgogICAgICAgIHNlbGYuaW1hZ2UgPSBmaWd1cmUuX2ltYWdlYml0bWFwCiAgICAgICAgc2VsZi50aXRsZSA9IGZpZ3VyZS5fdGl0bGUKCiAgICBkZWYgX3JlcHJfbWltZWJ1bmRsZV8oc2VsZiwgaW5jbHVkZSwgZXhjbHVkZSk6CiAgICAgICAgcmV0dXJuIHsgImFwcGxpY2F0aW9uL2h0bWwtaW1hZ2ViaXRtYXAiOiBzZWxmLmltYWdlIH0sIHsgInRpdGxlIjogc2VsZi50aXRsZSB9CgpjbGFzcyBGaWd1cmVDYW52YXNXb3JrZXIoRmlndXJlQ2FudmFzQmFzZSk6CiAgICBkZWYgX19pbml0X18oc2VsZiwgKmFyZ3MsICoqa3dhcmdzKToKICAgICAgICBGaWd1cmVDYW52YXNCYXNlLl9faW5pdF9fKHNlbGYsICphcmdzLCAqKmt3YXJncykKICAgICAgICBzZWxmLl9pZGxlX3NjaGVkdWxlZCA9IEZhbHNlCiAgICAgICAgc2VsZi5faWQgPSAibWF0cGxvdGxpYl8iICsgaGV4KGlkKHNlbGYpKVsyOl0KICAgICAgICBzZWxmLl90aXRsZSA9ICIiCiAgICAgICAgc2VsZi5fcmF0aW8gPSAyCgogICAgICAgIHdpZHRoLCBoZWlnaHQgPSBzZWxmLmdldF93aWR0aF9oZWlnaHQoKQogICAgICAgIHdpZHRoICo9IHNlbGYuX3JhdGlvCiAgICAgICAgaGVpZ2h0ICo9IHNlbGYuX3JhdGlvCgogICAgICAgIHNlbGYuX2NhbnZhcyA9IE9mZnNjcmVlbkNhbnZhcy5uZXcod2lkdGgsIGhlaWdodCkKICAgICAgICBzZWxmLl9jb250ZXh0ID0gc2VsZi5fY2FudmFzLmdldENvbnRleHQoIjJkIikKICAgICAgICBzZWxmLl9pbWFnZWJpdG1hcCA9IE5vbmUKCiAgICBkZWYgc2hvdyhzZWxmLCAqYXJncywgKiprd2FyZ3MpOgogICAgICAgIHNlbGYuY2xvc2UoKQogICAgICAgIHNlbGYuZHJhdygpCiAgICAgICAgc2VsZi5faW1hZ2ViaXRtYXAgPSBzZWxmLl9jYW52YXMudHJhbnNmZXJUb0ltYWdlQml0bWFwKCkKICAgICAgICBkaXNwbGF5KFJpY2hJbWFnZUJpdG1hcE91dHB1dChzZWxmKSkKCiAgICBkZWYgZHJhdyhzZWxmKToKICAgICAgICBzZWxmLl9pZGxlX3NjaGVkdWxlZCA9IFRydWUKICAgICAgICBvcmlnX2RwaSA9IHNlbGYuZmlndXJlLmRwaQogICAgICAgIGlmIHNlbGYuX3JhdGlvICE9IDE6CiAgICAgICAgICAgIHNlbGYuZmlndXJlLmRwaSAqPSBzZWxmLl9yYXRpbwogICAgICAgIHRyeToKICAgICAgICAgICAgd2lkdGgsIGhlaWdodCA9IHNlbGYuZ2V0X3dpZHRoX2hlaWdodCgpCiAgICAgICAgICAgIGlmIHNlbGYuX2NhbnZhcyBpcyBOb25lOgogICAgICAgICAgICAgICAgcmV0dXJuCiAgICAgICAgICAgIHJlbmRlcmVyID0gUmVuZGVyZXJIVE1MQ2FudmFzV29ya2VyKHNlbGYuX2NvbnRleHQsIHdpZHRoLCBoZWlnaHQsIHNlbGYuZmlndXJlLmRwaSwgc2VsZikKICAgICAgICAgICAgc2VsZi5maWd1cmUuZHJhdyhyZW5kZXJlcikKICAgICAgICBleGNlcHQgRXhjZXB0aW9uIGFzIGU6CiAgICAgICAgICAgIHJhaXNlIFJ1bnRpbWVFcnJvcigiUmVuZGVyaW5nIGZhaWxlZCIpIGZyb20gZQogICAgICAgIGZpbmFsbHk6CiAgICAgICAgICAgIHNlbGYuZmlndXJlLmRwaSA9IG9yaWdfZHBpCiAgICAgICAgICAgIHNlbGYuX2lkbGVfc2NoZWR1bGVkID0gRmFsc2UKCiAgICBkZWYgc2V0X3dpbmRvd190aXRsZShzZWxmLCB0aXRsZSk6CiAgICAgICAgc2VsZi5fdGl0bGUgPSB0aXRsZQoKICAgIGRlZiBjbG9zZShzZWxmKToKICAgICAgICBpZiAoc2VsZi5faW1hZ2ViaXRtYXApOgogICAgICAgICAgICBzZWxmLl9pbWFnZWJpdG1hcC5jbG9zZSgpCiAgICAgICAgICAgIHNlbGYuX2ltYWdlYml0bWFwID0gTm9uZQoKICAgIGRlZiBkZXN0cm95KHNlbGYsICphcmdzLCAqKmt3YXJncyk6CiAgICAgICAgc2VsZi5jbG9zZSgpCgpjbGFzcyBHcmFwaGljc0NvbnRleHRIVE1MQ2FudmFzKEdyYXBoaWNzQ29udGV4dEJhc2UpOgogICAgZGVmIF9faW5pdF9fKHNlbGYsIHJlbmRlcmVyKToKICAgICAgICBzdXBlcigpLl9faW5pdF9fKCkKICAgICAgICBzZWxmLnN0cm9rZSA9IFRydWUKICAgICAgICBzZWxmLnJlbmRlcmVyID0gcmVuZGVyZXIKCiAgICBkZWYgcmVzdG9yZShzZWxmKToKICAgICAgICBzZWxmLnJlbmRlcmVyLmN0eC5yZXN0b3JlKCkKCiAgICBkZWYgc2V0X2NhcHN0eWxlKHNlbGYsIGNzKToKICAgICAgICBpZiBjcyBpbiBbImJ1dHQiLCAicm91bmQiLCAicHJvamVjdGluZyJdOgogICAgICAgICAgICBzZWxmLl9jYXBzdHlsZSA9IGNzCiAgICAgICAgICAgIHNlbGYucmVuZGVyZXIuY3R4LmxpbmVDYXAgPSBfY2Fwc3R5bGVfZFtjc10KICAgICAgICBlbHNlOgogICAgICAgICAgICByYWlzZSBWYWx1ZUVycm9yKGYiVW5yZWNvZ25pemVkIGNhcCBzdHlsZS4gRm91bmQge2NzfSIpCgogICAgZGVmIHNldF9jbGlwX3JlY3RhbmdsZShzZWxmLCByZWN0YW5nbGUpOgogICAgICAgIHNlbGYucmVuZGVyZXIuY3R4LnNhdmUoKQogICAgICAgIGlmIG5vdCByZWN0YW5nbGU6CiAgICAgICAgICAgIHNlbGYucmVuZGVyZXIuY3R4LnJlc3RvcmUoKQogICAgICAgICAgICByZXR1cm4KICAgICAgICB4LCB5LCB3LCBoID0gbnAucm91bmQocmVjdGFuZ2xlLmJvdW5kcykKICAgICAgICBzZWxmLnJlbmRlcmVyLmN0eC5iZWdpblBhdGgoKQogICAgICAgIHNlbGYucmVuZGVyZXIuY3R4LnJlY3QoeCwgc2VsZi5yZW5kZXJlci5oZWlnaHQgLSB5IC0gaCwgdywgaCkKICAgICAgICBzZWxmLnJlbmRlcmVyLmN0eC5jbGlwKCkKCiAgICBkZWYgc2V0X2NsaXBfcGF0aChzZWxmLCBwYXRoKToKICAgICAgICBzZWxmLnJlbmRlcmVyLmN0eC5zYXZlKCkKICAgICAgICBpZiBub3QgcGF0aDoKICAgICAgICAgICAgc2VsZi5yZW5kZXJlci5jdHgucmVzdG9yZSgpCiAgICAgICAgICAgIHJldHVybgogICAgICAgIHRwYXRoLCBhZmZpbmUgPSBwYXRoLmdldF90cmFuc2Zvcm1lZF9wYXRoX2FuZF9hZmZpbmUoKQogICAgICAgIGFmZmluZSA9IGFmZmluZSArIEFmZmluZTJEKCkuc2NhbGUoMSwgLTEpLnRyYW5zbGF0ZSgwLCBzZWxmLnJlbmRlcmVyLmhlaWdodCkKICAgICAgICBzZWxmLnJlbmRlcmVyLl9wYXRoX2hlbHBlcihzZWxmLnJlbmRlcmVyLmN0eCwgdHBhdGgsIGFmZmluZSkKICAgICAgICBzZWxmLnJlbmRlcmVyLmN0eC5jbGlwKCkKCiAgICBkZWYgc2V0X2Rhc2hlcyhzZWxmLCBkYXNoX29mZnNldCwgZGFzaF9saXN0KToKICAgICAgICBzZWxmLl9kYXNoZXMgPSBkYXNoX29mZnNldCwgZGFzaF9saXN0CiAgICAgICAgaWYgZGFzaF9vZmZzZXQgaXMgbm90IE5vbmU6CiAgICAgICAgICAgIHNlbGYucmVuZGVyZXIuY3R4LmxpbmVEYXNoT2Zmc2V0ID0gZGFzaF9vZmZzZXQKICAgICAgICBpZiBkYXNoX2xpc3QgaXMgTm9uZToKICAgICAgICAgICAgc2VsZi5yZW5kZXJlci5jdHguc2V0TGluZURhc2goW10pCiAgICAgICAgZWxzZToKICAgICAgICAgICAgZGxuID0gbnAuYXNhcnJheShkYXNoX2xpc3QpCiAgICAgICAgICAgIGRsID0gbGlzdChzZWxmLnJlbmRlcmVyLnBvaW50c190b19waXhlbHMoZGxuKSkKICAgICAgICAgICAgc2VsZi5yZW5kZXJlci5jdHguc2V0TGluZURhc2goZGwpCgogICAgZGVmIHNldF9qb2luc3R5bGUoc2VsZiwganMpOgogICAgICAgIGlmIGpzIGluIFsibWl0ZXIiLCAicm91bmQiLCAiYmV2ZWwiXToKICAgICAgICAgICAgc2VsZi5fam9pbnN0eWxlID0ganMKICAgICAgICAgICAgc2VsZi5yZW5kZXJlci5jdHgubGluZUpvaW4gPSBqcwogICAgICAgIGVsc2U6CiAgICAgICAgICAgIHJhaXNlIFZhbHVlRXJyb3IoZiJVbnJlY29nbml6ZWQgam9pbiBzdHlsZS4gRm91bmQge2pzfSIpCgogICAgZGVmIHNldF9saW5ld2lkdGgoc2VsZiwgdyk6CiAgICAgICAgc2VsZi5zdHJva2UgPSB3ICE9IDAKICAgICAgICBzZWxmLl9saW5ld2lkdGggPSBmbG9hdCh3KQogICAgICAgIHNlbGYucmVuZGVyZXIuY3R4LmxpbmVXaWR0aCA9IHNlbGYucmVuZGVyZXIucG9pbnRzX3RvX3BpeGVscyhmbG9hdCh3KSkKCmNsYXNzIFJlbmRlcmVySFRNTENhbnZhc1dvcmtlcihSZW5kZXJlckJhc2UpOgogICAgZGVmIF9faW5pdF9fKHNlbGYsIGN0eCwgd2lkdGgsIGhlaWdodCwgZHBpLCBmaWcpOgogICAgICAgIHN1cGVyKCkuX19pbml0X18oKQogICAgICAgIHNlbGYuZmlnID0gZmlnCiAgICAgICAgc2VsZi5jdHggPSBjdHgKICAgICAgICBzZWxmLndpZHRoID0gd2lkdGgKICAgICAgICBzZWxmLmhlaWdodCA9IGhlaWdodAogICAgICAgIHNlbGYuY3R4LndpZHRoID0gc2VsZi53aWR0aAogICAgICAgIHNlbGYuY3R4LmhlaWdodCA9IHNlbGYuaGVpZ2h0CiAgICAgICAgc2VsZi5kcGkgPSBkcGkKICAgICAgICBzZWxmLmZvbnRkID0gbWF4ZGljdCg1MCkKICAgICAgICBzZWxmLm1hdGh0ZXh0X3BhcnNlciA9IE1hdGhUZXh0UGFyc2VyKCJiaXRtYXAiKQoKICAgICAgICAjIEtlZXAgdGhlIHN0YXRlIG9mIGZvbnRmYWNlcyB0aGF0IGFyZSBsb2FkaW5nCiAgICAgICAgc2VsZi5mb250c19sb2FkaW5nID0ge30KCiAgICBkZWYgbmV3X2djKHNlbGYpOgogICAgICAgIHJldHVybiBHcmFwaGljc0NvbnRleHRIVE1MQ2FudmFzKHJlbmRlcmVyPXNlbGYpCgogICAgZGVmIHBvaW50c190b19waXhlbHMoc2VsZiwgcG9pbnRzKToKICAgICAgICByZXR1cm4gKHBvaW50cyAvIDcyLjApICogc2VsZi5kcGkKCiAgICBkZWYgX21hdHBsb3RsaWJfY29sb3JfdG9fQ1NTKHNlbGYsIGNvbG9yLCBhbHBoYSwgYWxwaGFfb3ZlcnJpZGVzLCBpc19SR0I9VHJ1ZSk6CiAgICAgICAgaWYgbm90IGlzX1JHQjoKICAgICAgICAgICAgUiwgRywgQiwgYWxwaGEgPSBjb2xvckNvbnZlcnRlci50b19yZ2JhKGNvbG9yKQogICAgICAgICAgICBjb2xvciA9IChSLCBHLCBCKQoKICAgICAgICBpZiAobGVuKGNvbG9yKSA9PSA0KSBhbmQgKGFscGhhIGlzIE5vbmUpOgogICAgICAgICAgICBhbHBoYSA9IGNvbG9yWzNdCgogICAgICAgIGlmIGFscGhhIGlzIE5vbmU6CiAgICAgICAgICAgIENTU19jb2xvciA9IHJnYjJoZXgoY29sb3JbOjNdKQoKICAgICAgICBlbHNlOgogICAgICAgICAgICBSID0gaW50KGNvbG9yWzBdICogMjU1KQogICAgICAgICAgICBHID0gaW50KGNvbG9yWzFdICogMjU1KQogICAgICAgICAgICBCID0gaW50KGNvbG9yWzJdICogMjU1KQogICAgICAgICAgICBpZiBsZW4oY29sb3IpID09IDMgb3IgYWxwaGFfb3ZlcnJpZGVzOgogICAgICAgICAgICAgICAgQ1NTX2NvbG9yID0gZiIiInJnYmEoe1I6ZH0sIHtHOmR9LCB7QjpkfSwge2FscGhhOi4zZ30pIiIiCiAgICAgICAgICAgIGVsc2U6CiAgICAgICAgICAgICAgICBDU1NfY29sb3IgPSAiIiJyZ2JhKHs6ZH0sIHs6ZH0sIHs6ZH0sIHs6LjNnfSkiIiIuZm9ybWF0KAogICAgICAgICAgICAgICAgICAgIFIsIEcsIEIsIGNvbG9yWzNdCiAgICAgICAgICAgICAgICApCgogICAgICAgIHJldHVybiBDU1NfY29sb3IKCiAgICBkZWYgX3NldF9zdHlsZShzZWxmLCBnYywgcmdiRmFjZT1Ob25lKToKICAgICAgICBpZiByZ2JGYWNlIGlzIG5vdCBOb25lOgogICAgICAgICAgICBzZWxmLmN0eC5maWxsU3R5bGUgPSBzZWxmLl9tYXRwbG90bGliX2NvbG9yX3RvX0NTUygKICAgICAgICAgICAgICAgIHJnYkZhY2UsIGdjLmdldF9hbHBoYSgpLCBnYy5nZXRfZm9yY2VkX2FscGhhKCkKICAgICAgICAgICAgKQoKICAgICAgICBpZiBnYy5nZXRfY2Fwc3R5bGUoKToKICAgICAgICAgICAgc2VsZi5jdHgubGluZUNhcCA9IF9jYXBzdHlsZV9kW2djLmdldF9jYXBzdHlsZSgpXQoKICAgICAgICBzZWxmLmN0eC5zdHJva2VTdHlsZSA9IHNlbGYuX21hdHBsb3RsaWJfY29sb3JfdG9fQ1NTKAogICAgICAgICAgICBnYy5nZXRfcmdiKCksIGdjLmdldF9hbHBoYSgpLCBnYy5nZXRfZm9yY2VkX2FscGhhKCkKICAgICAgICApCgogICAgICAgIHNlbGYuY3R4LmxpbmVXaWR0aCA9IHNlbGYucG9pbnRzX3RvX3BpeGVscyhnYy5nZXRfbGluZXdpZHRoKCkpCgogICAgZGVmIF9wYXRoX2hlbHBlcihzZWxmLCBjdHgsIHBhdGgsIHRyYW5zZm9ybSwgY2xpcD1Ob25lKToKICAgICAgICBjdHguYmVnaW5QYXRoKCkKICAgICAgICBmb3IgcG9pbnRzLCBjb2RlIGluIHBhdGguaXRlcl9zZWdtZW50cyh0cmFuc2Zvcm0sIHJlbW92ZV9uYW5zPVRydWUsIGNsaXA9Y2xpcCk6CiAgICAgICAgICAgIGlmIGNvZGUgPT0gUGF0aC5NT1ZFVE86CiAgICAgICAgICAgICAgICBjdHgubW92ZVRvKHBvaW50c1swXSwgcG9pbnRzWzFdKQogICAgICAgICAgICBlbGlmIGNvZGUgPT0gUGF0aC5MSU5FVE86CiAgICAgICAgICAgICAgICBjdHgubGluZVRvKHBvaW50c1swXSwgcG9pbnRzWzFdKQogICAgICAgICAgICBlbGlmIGNvZGUgPT0gUGF0aC5DVVJWRTM6CiAgICAgICAgICAgICAgICBjdHgucXVhZHJhdGljQ3VydmVUbygqcG9pbnRzKQogICAgICAgICAgICBlbGlmIGNvZGUgPT0gUGF0aC5DVVJWRTQ6CiAgICAgICAgICAgICAgICBjdHguYmV6aWVyQ3VydmVUbygqcG9pbnRzKQogICAgICAgICAgICBlbGlmIGNvZGUgPT0gUGF0aC5DTE9TRVBPTFk6CiAgICAgICAgICAgICAgICBjdHguY2xvc2VQYXRoKCkKCiAgICBkZWYgZHJhd19wYXRoKHNlbGYsIGdjLCBwYXRoLCB0cmFuc2Zvcm0sIHJnYkZhY2U9Tm9uZSk6CiAgICAgICAgc2VsZi5fc2V0X3N0eWxlKGdjLCByZ2JGYWNlKQogICAgICAgIGlmIHJnYkZhY2UgaXMgTm9uZSBhbmQgZ2MuZ2V0X2hhdGNoKCkgaXMgTm9uZToKICAgICAgICAgICAgZmlndXJlX2NsaXAgPSAoMCwgMCwgc2VsZi53aWR0aCwgc2VsZi5oZWlnaHQpCiAgICAgICAgZWxzZToKICAgICAgICAgICAgZmlndXJlX2NsaXAgPSBOb25lCgogICAgICAgIHRyYW5zZm9ybSArPSBBZmZpbmUyRCgpLnNjYWxlKDEsIC0xKS50cmFuc2xhdGUoMCwgc2VsZi5oZWlnaHQpCiAgICAgICAgc2VsZi5fcGF0aF9oZWxwZXIoc2VsZi5jdHgsIHBhdGgsIHRyYW5zZm9ybSwgZmlndXJlX2NsaXApCgogICAgICAgIGlmIHJnYkZhY2UgaXMgbm90IE5vbmU6CiAgICAgICAgICAgIHNlbGYuY3R4LmZpbGwoKQogICAgICAgICAgICBzZWxmLmN0eC5maWxsU3R5bGUgPSAiIzAwMDAwMCIKCiAgICAgICAgaWYgZ2Muc3Ryb2tlOgogICAgICAgICAgICBzZWxmLmN0eC5zdHJva2UoKQoKICAgIGRlZiBkcmF3X21hcmtlcnMoc2VsZiwgZ2MsIG1hcmtlcl9wYXRoLCBtYXJrZXJfdHJhbnMsIHBhdGgsIHRyYW5zLCByZ2JGYWNlPU5vbmUpOgogICAgICAgIHN1cGVyKCkuZHJhd19tYXJrZXJzKGdjLCBtYXJrZXJfcGF0aCwgbWFya2VyX3RyYW5zLCBwYXRoLCB0cmFucywgcmdiRmFjZSkKCiAgICBkZWYgX2dldF9mb250KHNlbGYsIHByb3ApOgogICAgICAgIGtleSA9IGhhc2gocHJvcCkKICAgICAgICBmb250X3ZhbHVlID0gc2VsZi5mb250ZC5nZXQoa2V5KQogICAgICAgIGlmIGZvbnRfdmFsdWUgaXMgTm9uZToKICAgICAgICAgICAgZm5hbWUgPSBmaW5kZm9udChwcm9wKQogICAgICAgICAgICBmb250X3ZhbHVlID0gc2VsZi5mb250ZC5nZXQoZm5hbWUpCiAgICAgICAgICAgIGlmIGZvbnRfdmFsdWUgaXMgTm9uZToKICAgICAgICAgICAgICAgIGZvbnQgPSBGVDJGb250KHN0cihmbmFtZSkpCiAgICAgICAgICAgICAgICBmb250X2ZpbGVfbmFtZSA9IGZuYW1lW2ZuYW1lLnJmaW5kKCIvIikgKyAxIDpdCiAgICAgICAgICAgICAgICBmb250X3ZhbHVlID0gZm9udCwgZm9udF9maWxlX25hbWUKICAgICAgICAgICAgICAgIHNlbGYuZm9udGRbZm5hbWVdID0gZm9udF92YWx1ZQogICAgICAgICAgICBzZWxmLmZvbnRkW2tleV0gPSBmb250X3ZhbHVlCiAgICAgICAgZm9udCwgZm9udF9maWxlX25hbWUgPSBmb250X3ZhbHVlCiAgICAgICAgZm9udC5jbGVhcigpCiAgICAgICAgZm9udC5zZXRfc2l6ZShwcm9wLmdldF9zaXplX2luX3BvaW50cygpLCBzZWxmLmRwaSkKICAgICAgICByZXR1cm4gZm9udCwgZm9udF9maWxlX25hbWUKCiAgICBkZWYgZ2V0X3RleHRfd2lkdGhfaGVpZ2h0X2Rlc2NlbnQoc2VsZiwgcywgcHJvcCwgaXNtYXRoKToKICAgICAgICB3OiBmbG9hdAogICAgICAgIGg6IGZsb2F0CiAgICAgICAgaWYgaXNtYXRoOgogICAgICAgICAgICBpbWFnZSwgZCA9IHNlbGYubWF0aHRleHRfcGFyc2VyLnBhcnNlKHMsIHNlbGYuZHBpLCBwcm9wKQogICAgICAgICAgICBpbWFnZV9hcnIgPSBucC5hc2FycmF5KGltYWdlKQogICAgICAgICAgICBoLCB3ID0gaW1hZ2VfYXJyLnNoYXBlCiAgICAgICAgZWxzZToKICAgICAgICAgICAgZm9udCwgXyA9IHNlbGYuX2dldF9mb250KHByb3ApCiAgICAgICAgICAgIGZvbnQuc2V0X3RleHQocywgMC4wLCBmbGFncz1MT0FEX05PX0hJTlRJTkcpCiAgICAgICAgICAgIHcsIGggPSBmb250LmdldF93aWR0aF9oZWlnaHQoKQogICAgICAgICAgICB3IC89IDY0LjAKICAgICAgICAgICAgaCAvPSA2NC4wCiAgICAgICAgICAgIGQgPSBmb250LmdldF9kZXNjZW50KCkgLyA2NC4wCiAgICAgICAgcmV0dXJuIHcsIGgsIGQKCiAgICBkZWYgX2RyYXdfbWF0aF90ZXh0KHNlbGYsIGdjLCB4LCB5LCBzLCBwcm9wLCBhbmdsZSk6CiAgICAgICAgcmdiYSwgZGVzY2VudCA9IHNlbGYubWF0aHRleHRfcGFyc2VyLnRvX3JnYmEoCiAgICAgICAgICAgIHMsIGdjLmdldF9yZ2IoKSwgc2VsZi5kcGksIHByb3AuZ2V0X3NpemVfaW5fcG9pbnRzKCkKICAgICAgICApCiAgICAgICAgaGVpZ2h0LCB3aWR0aCwgXyA9IHJnYmEuc2hhcGUKICAgICAgICBhbmdsZSA9IG1hdGgucmFkaWFucyhhbmdsZSkKICAgICAgICBpZiBhbmdsZSAhPSAwOgogICAgICAgICAgICBzZWxmLmN0eC5zYXZlKCkKICAgICAgICAgICAgc2VsZi5jdHgudHJhbnNsYXRlKHgsIHkpCiAgICAgICAgICAgIHNlbGYuY3R4LnJvdGF0ZSgtYW5nbGUpCiAgICAgICAgICAgIHNlbGYuY3R4LnRyYW5zbGF0ZSgteCwgLXkpCiAgICAgICAgc2VsZi5kcmF3X2ltYWdlKGdjLCB4LCAteSAtIGRlc2NlbnQsIG5wLmZsaXB1ZChyZ2JhKSkKICAgICAgICBpZiBhbmdsZSAhPSAwOgogICAgICAgICAgICBzZWxmLmN0eC5yZXN0b3JlKCkKCiAgICBkZWYgZHJhd19pbWFnZShzZWxmLCBnYywgeCwgeSwgaW0sIHRyYW5zZm9ybT1Ob25lKToKICAgICAgICBpbXBvcnQgbnVtcHkgYXMgbnAKICAgICAgICBpbSA9IG5wLmZsaXB1ZChpbSkKICAgICAgICBoLCB3LCBkID0gaW0uc2hhcGUKICAgICAgICB5ID0gc2VsZi5jdHguaGVpZ2h0IC0geSAtIGgKICAgICAgICBpbSA9IG5wLnJhdmVsKG5wLnVpbnQ4KG5wLnJlc2hhcGUoaW0sIChoICogdyAqIGQsIC0xKSkpKS50b2J5dGVzKCkKICAgICAgICBwaXhlbHNfcHJveHkgPSBjcmVhdGVfcHJveHkoaW0pCiAgICAgICAgcGl4ZWxzX2J1ZiA9IHBpeGVsc19wcm94eS5nZXRCdWZmZXIoInU4Y2xhbXBlZCIpCiAgICAgICAgaW1nX2RhdGEgPSBJbWFnZURhdGEubmV3KHBpeGVsc19idWYuZGF0YSwgdywgaCkKICAgICAgICBzZWxmLmN0eC5zYXZlKCkKICAgICAgICBpbl9tZW1vcnlfY2FudmFzID0gT2Zmc2NyZWVuQ2FudmFzLm5ldyh3LCBoKQogICAgICAgIGluX21lbW9yeV9jYW52YXNfY29udGV4dCA9IGluX21lbW9yeV9jYW52YXMuZ2V0Q29udGV4dCgiMmQiKQogICAgICAgIGluX21lbW9yeV9jYW52YXNfY29udGV4dC5wdXRJbWFnZURhdGEoaW1nX2RhdGEsIDAsIDApCiAgICAgICAgc2VsZi5jdHguZHJhd0ltYWdlKGluX21lbW9yeV9jYW52YXMsIHgsIHksIHcsIGgpCiAgICAgICAgc2VsZi5jdHgucmVzdG9yZSgpCiAgICAgICAgcGl4ZWxzX3Byb3h5LmRlc3Ryb3koKQogICAgICAgIHBpeGVsc19idWYucmVsZWFzZSgpCgogICAgZGVmIGRyYXdfdGV4dChzZWxmLCBnYywgeCwgeSwgcywgcHJvcCwgYW5nbGUsIGlzbWF0aD1GYWxzZSwgbXRleHQ9Tm9uZSk6CiAgICAgICAgaWYgaXNtYXRoOgogICAgICAgICAgICBzZWxmLl9kcmF3X21hdGhfdGV4dChnYywgeCwgeSwgcywgcHJvcCwgYW5nbGUpCiAgICAgICAgICAgIHJldHVybgoKICAgICAgICBhbmdsZSA9IG1hdGgucmFkaWFucyhhbmdsZSkKICAgICAgICB3aWR0aCwgaGVpZ2h0LCBkZXNjZW50ID0gc2VsZi5nZXRfdGV4dF93aWR0aF9oZWlnaHRfZGVzY2VudChzLCBwcm9wLCBpc21hdGgpCiAgICAgICAgeCAtPSBtYXRoLnNpbihhbmdsZSkgKiBkZXNjZW50CiAgICAgICAgeSAtPSBtYXRoLmNvcyhhbmdsZSkgKiBkZXNjZW50IC0gc2VsZi5jdHguaGVpZ2h0CiAgICAgICAgZm9udF9zaXplID0gc2VsZi5wb2ludHNfdG9fcGl4ZWxzKHByb3AuZ2V0X3NpemVfaW5fcG9pbnRzKCkpCgogICAgICAgIGZvbnRfcHJvcGVydHlfc3RyaW5nID0gInt9IHt9IHs6LjNnfXB4IHt9LCB7fSIuZm9ybWF0KAogICAgICAgICAgICBwcm9wLmdldF9zdHlsZSgpLAogICAgICAgICAgICBwcm9wLmdldF93ZWlnaHQoKSwKICAgICAgICAgICAgZm9udF9zaXplLAogICAgICAgICAgICBwcm9wLmdldF9uYW1lKCksCiAgICAgICAgICAgIHByb3AuZ2V0X2ZhbWlseSgpWzBdLAogICAgICAgICkKICAgICAgICBpZiBhbmdsZSAhPSAwOgogICAgICAgICAgICBzZWxmLmN0eC5zYXZlKCkKICAgICAgICAgICAgc2VsZi5jdHgudHJhbnNsYXRlKHgsIHkpCiAgICAgICAgICAgIHNlbGYuY3R4LnJvdGF0ZSgtYW5nbGUpCiAgICAgICAgICAgIHNlbGYuY3R4LnRyYW5zbGF0ZSgteCwgLXkpCiAgICAgICAgc2VsZi5jdHguZm9udCA9IGZvbnRfcHJvcGVydHlfc3RyaW5nCiAgICAgICAgc2VsZi5jdHguZmlsbFN0eWxlID0gc2VsZi5fbWF0cGxvdGxpYl9jb2xvcl90b19DU1MoCiAgICAgICAgICAgIGdjLmdldF9yZ2IoKSwgZ2MuZ2V0X2FscGhhKCksIGdjLmdldF9mb3JjZWRfYWxwaGEoKQogICAgICAgICkKICAgICAgICBzZWxmLmN0eC5maWxsVGV4dChzLCB4LCB5KQogICAgICAgIHNlbGYuY3R4LmZpbGxTdHlsZSA9ICIjMDAwMDAwIgogICAgICAgIGlmIGFuZ2xlICE9IDA6CiAgICAgICAgICAgIHNlbGYuY3R4LnJlc3RvcmUoKQoKY2xhc3MgRmlndXJlTWFuYWdlckhUTUxDYW52YXMoRmlndXJlTWFuYWdlckJhc2UpOgogICAgZGVmIF9faW5pdF9fKHNlbGYsIGNhbnZhcywgbnVtKToKICAgICAgICBzdXBlcigpLl9faW5pdF9fKGNhbnZhcywgbnVtKQogICAgICAgIHNlbGYuc2V0X3dpbmRvd190aXRsZSgiRmlndXJlICVkIiAlIG51bSkKCiAgICBkZWYgc2hvdyhzZWxmLCAqYXJncywgKiprd2FyZ3MpOgogICAgICAgIHNlbGYuY2FudmFzLnNob3coKmFyZ3MsICoqa3dhcmdzKQoKICAgIGRlZiBkZXN0cm95KHNlbGYsICphcmdzLCAqKmt3YXJncyk6CiAgICAgICAgc2VsZi5jYW52YXMuZGVzdHJveSgqYXJncywgKiprd2FyZ3MpCgogICAgZGVmIHJlc2l6ZShzZWxmLCB3LCBoKToKICAgICAgICBwYXNzCgogICAgZGVmIHNldF93aW5kb3dfdGl0bGUoc2VsZiwgdGl0bGUpOgogICAgICAgIHNlbGYuY2FudmFzLnNldF93aW5kb3dfdGl0bGUodGl0bGUpCgoKQF9CYWNrZW5kLmV4cG9ydApjbGFzcyBfQmFja2VuZFdhc21Db3JlQWdnKF9CYWNrZW5kKToKICAgIEZpZ3VyZUNhbnZhcyA9IEZpZ3VyZUNhbnZhc1dvcmtlcgogICAgRmlndXJlTWFuYWdlciA9IEZpZ3VyZU1hbmFnZXJIVE1MQ2FudmFzCgogICAgQHN0YXRpY21ldGhvZAogICAgZGVmIHNob3coKmFyZ3MsICoqa3dhcmdzKToKICAgICAgICBmcm9tIG1hdHBsb3RsaWIgaW1wb3J0IHB5cGxvdCBhcyBwbHQKICAgICAgICBwbHQuZ2NmKCkuY2FudmFzLnNob3coKmFyZ3MsICoqa3dhcmdzKQoKICAgIEBzdGF0aWNtZXRob2QKICAgIGRlZiBkZXN0cm95KCphcmdzLCAqKmt3YXJncyk6CiAgICAgICAgZnJvbSBtYXRwbG90bGliIGltcG9ydCBweXBsb3QgYXMgcGx0CiAgICAgICAgcGx0LmdjZigpLmNhbnZhcy5kZXN0cm95KCphcmdzLCAqKmt3YXJncykK"});var Ka={};xO(Ka,{ChannelType:()=>Qt,Console:()=>M0,Shelter:()=>Ba,WebR:()=>Uf,WebRChannelError:()=>pt,WebRError:()=>di,WebRPayloadError:()=>Bn,WebRWorkerError:()=>wf,isRCall:()=>gs,isRCharacter:()=>Ui,isRComplex:()=>R0,isRDouble:()=>C0,isREnvironment:()=>S0,isRFunction:()=>Os,isRInteger:()=>P0,isRList:()=>ot,isRLogical:()=>T0,isRNull:()=>Re,isRObject:()=>ee,isRPairlist:()=>k0,isRRaw:()=>Ja,isRSymbol:()=>x0});var kO=Object.create,pf=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,TO=Object.getOwnPropertyNames,PO=Object.getPrototypeOf,CO=Object.prototype.hasOwnProperty,Bi=(i=>typeof ci<"u"?ci:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof ci<"u"?ci:e)[t]}):i)(function(i){if(typeof ci<"u")return ci.apply(this,arguments);throw new Error('Dynamic require of "'+i+'" is not supported')}),ke=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),RO=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of TO(e))!CO.call(i,r)&&r!==t&&pf(i,r,{get:()=>e[r],enumerable:!(n=SO(e,r))||n.enumerable});return i},Xi=(i,e,t)=>(t=i!=null?kO(PO(i)):{},RO(e||!i||!i.__esModule?pf(t,"default",{value:i,enumerable:!0}):t,i)),Xa=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},k=(i,e,t)=>(Xa(i,e,"read from private field"),t?t.call(i):e.get(i)),L=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},me=(i,e,t,n)=>(Xa(i,e,"write to private field"),n?n.call(i,t):e.set(i,t),t);var Je=(i,e,t)=>(Xa(i,e,"access private method"),t),cs=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getUint64=i.getInt64=i.setInt64=i.setUint64=i.UINT32_MAX=void 0,i.UINT32_MAX=4294967295;function e(s,o,a){let l=a/4294967296,h=a;s.setUint32(o,l),s.setUint32(o+4,h)}i.setUint64=e;function t(s,o,a){let l=Math.floor(a/4294967296),h=a;s.setUint32(o,l),s.setUint32(o+4,h)}i.setInt64=t;function n(s,o){let a=s.getInt32(o),l=s.getUint32(o+4);return a*4294967296+l}i.getInt64=n;function r(s,o){let a=s.getUint32(o),l=s.getUint32(o+4);return a*4294967296+l}i.getUint64=r}),Wa=ke(i=>{"use strict";var e,t,n;Object.defineProperty(i,"__esModule",{value:!0}),i.utf8DecodeTD=i.TEXT_DECODER_THRESHOLD=i.utf8DecodeJs=i.utf8EncodeTE=i.TEXT_ENCODER_THRESHOLD=i.utf8EncodeJs=i.utf8Count=void 0;var r=cs(),s=(typeof process>"u"||((e=process==null?void 0:process.env)===null||e===void 0?void 0:e.TEXT_ENCODING)!=="never")&&typeof TextEncoder<"u"&&typeof TextDecoder<"u";function o(p){let g=p.length,O=0,y=0;for(;y=55296&&v<=56319&&y>6&31|192;else{if(w>=55296&&w<=56319&&x>18&7|240,g[v++]=w>>12&63|128,g[v++]=w>>6&63|128):(g[v++]=w>>12&15|224,g[v++]=w>>6&63|128)}else{g[v++]=w;continue}g[v++]=w&63|128}}i.utf8EncodeJs=a;var l=s?new TextEncoder:void 0;i.TEXT_ENCODER_THRESHOLD=s?typeof process<"u"&&((t=process==null?void 0:process.env)===null||t===void 0?void 0:t.TEXT_ENCODING)!=="force"?200:0:r.UINT32_MAX;function h(p,g,O){g.set(l.encode(p),O)}function c(p,g,O){l.encodeInto(p,g.subarray(O))}i.utf8EncodeTE=l!=null&&l.encodeInto?c:h;var f=4096;function u(p,g,O){let y=g,v=y+O,x=[],w="";for(;y65535&&(V-=65536,x.push(V>>>10&1023|55296),V=56320|V&1023),x.push(V)}else x.push(P);x.length>=f&&(w+=String.fromCharCode(...x),x.length=0)}return x.length>0&&(w+=String.fromCharCode(...x)),w}i.utf8DecodeJs=u;var d=s?new TextDecoder:null;i.TEXT_DECODER_THRESHOLD=s?typeof process<"u"&&((n=process==null?void 0:process.env)===null||n===void 0?void 0:n.TEXT_DECODER)!=="force"?200:0:r.UINT32_MAX;function m(p,g,O){let y=p.subarray(g,g+O);return d.decode(y)}i.utf8DecodeTD=m}),mf=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ExtData=void 0;var e=class{constructor(t,n){this.type=t,this.data=n}};i.ExtData=e}),Ia=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DecodeError=void 0;var e=class extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};i.DecodeError=e}),gf=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.timestampExtension=i.decodeTimestampExtension=i.decodeTimestampToTimeSpec=i.encodeTimestampExtension=i.encodeDateToTimeSpec=i.encodeTimeSpecToTimestamp=i.EXT_TIMESTAMP=void 0;var e=Ia(),t=cs();i.EXT_TIMESTAMP=-1;var n=4294967296-1,r=17179869184-1;function s({sec:c,nsec:f}){if(c>=0&&f>=0&&c<=r)if(f===0&&c<=n){let u=new Uint8Array(4);return new DataView(u.buffer).setUint32(0,c),u}else{let u=c/4294967296,d=c&4294967295,m=new Uint8Array(8),p=new DataView(m.buffer);return p.setUint32(0,f<<2|u&3),p.setUint32(4,d),m}else{let u=new Uint8Array(12),d=new DataView(u.buffer);return d.setUint32(0,f),(0,t.setInt64)(d,4,c),u}}i.encodeTimeSpecToTimestamp=s;function o(c){let f=c.getTime(),u=Math.floor(f/1e3),d=(f-u*1e3)*1e6,m=Math.floor(d/1e9);return{sec:u+m,nsec:d-m*1e9}}i.encodeDateToTimeSpec=o;function a(c){if(c instanceof Date){let f=o(c);return s(f)}else return null}i.encodeTimestampExtension=a;function l(c){let f=new DataView(c.buffer,c.byteOffset,c.byteLength);switch(c.byteLength){case 4:return{sec:f.getUint32(0),nsec:0};case 8:{let u=f.getUint32(0),d=f.getUint32(4),m=(u&3)*4294967296+d,p=u>>>2;return{sec:m,nsec:p}}case 12:{let u=(0,t.getInt64)(f,4),d=f.getUint32(0);return{sec:u,nsec:d}}default:throw new e.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${c.length}`)}}i.decodeTimestampToTimeSpec=l;function h(c){let f=l(c);return new Date(f.sec*1e3+f.nsec/1e6)}i.decodeTimestampExtension=h,i.timestampExtension={type:i.EXT_TIMESTAMP,encode:a,decode:h}}),Na=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ExtensionCodec=void 0;var e=mf(),t=gf(),n=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(t.timestampExtension)}register({type:r,encode:s,decode:o}){if(r>=0)this.encoders[r]=s,this.decoders[r]=o;else{let a=1+r;this.builtInEncoders[a]=s,this.builtInDecoders[a]=o}}tryToEncode(r,s){for(let o=0;o{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createDataView=i.ensureUint8Array=void 0;function e(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):n instanceof ArrayBuffer?new Uint8Array(n):Uint8Array.from(n)}i.ensureUint8Array=e;function t(n){if(n instanceof ArrayBuffer)return new DataView(n);let r=e(n);return new DataView(r.buffer,r.byteOffset,r.byteLength)}i.createDataView=t}),yf=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Encoder=i.DEFAULT_INITIAL_BUFFER_SIZE=i.DEFAULT_MAX_DEPTH=void 0;var e=Wa(),t=Na(),n=cs(),r=Of();i.DEFAULT_MAX_DEPTH=100,i.DEFAULT_INITIAL_BUFFER_SIZE=2048;var s=class{constructor(o=t.ExtensionCodec.defaultCodec,a=void 0,l=i.DEFAULT_MAX_DEPTH,h=i.DEFAULT_INITIAL_BUFFER_SIZE,c=!1,f=!1,u=!1,d=!1){this.extensionCodec=o,this.context=a,this.maxDepth=l,this.initialBufferSize=h,this.sortKeys=c,this.forceFloat32=f,this.ignoreUndefined=u,this.forceIntegerToFloat=d,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}reinitializeState(){this.pos=0}encodeSharedRef(o){return this.reinitializeState(),this.doEncode(o,1),this.bytes.subarray(0,this.pos)}encode(o){return this.reinitializeState(),this.doEncode(o,1),this.bytes.slice(0,this.pos)}doEncode(o,a){if(a>this.maxDepth)throw new Error(`Too deep objects in depth ${a}`);o==null?this.encodeNil():typeof o=="boolean"?this.encodeBoolean(o):typeof o=="number"?this.encodeNumber(o):typeof o=="string"?this.encodeString(o):this.encodeObject(o,a)}ensureBufferSizeToWrite(o){let a=this.pos+o;this.view.byteLength=0?o<128?this.writeU8(o):o<256?(this.writeU8(204),this.writeU8(o)):o<65536?(this.writeU8(205),this.writeU16(o)):o<4294967296?(this.writeU8(206),this.writeU32(o)):(this.writeU8(207),this.writeU64(o)):o>=-32?this.writeU8(224|o+32):o>=-128?(this.writeU8(208),this.writeI8(o)):o>=-32768?(this.writeU8(209),this.writeI16(o)):o>=-2147483648?(this.writeU8(210),this.writeI32(o)):(this.writeU8(211),this.writeI64(o)):this.forceFloat32?(this.writeU8(202),this.writeF32(o)):(this.writeU8(203),this.writeF64(o))}writeStringHeader(o){if(o<32)this.writeU8(160+o);else if(o<256)this.writeU8(217),this.writeU8(o);else if(o<65536)this.writeU8(218),this.writeU16(o);else if(o<4294967296)this.writeU8(219),this.writeU32(o);else throw new Error(`Too long string: ${o} bytes in UTF-8`)}encodeString(o){if(o.length>e.TEXT_ENCODER_THRESHOLD){let a=(0,e.utf8Count)(o);this.ensureBufferSizeToWrite(5+a),this.writeStringHeader(a),(0,e.utf8EncodeTE)(o,this.bytes,this.pos),this.pos+=a}else{let a=(0,e.utf8Count)(o);this.ensureBufferSizeToWrite(5+a),this.writeStringHeader(a),(0,e.utf8EncodeJs)(o,this.bytes,this.pos),this.pos+=a}}encodeObject(o,a){let l=this.extensionCodec.tryToEncode(o,this.context);if(l!=null)this.encodeExtension(l);else if(Array.isArray(o))this.encodeArray(o,a);else if(ArrayBuffer.isView(o))this.encodeBinary(o);else if(typeof o=="object")this.encodeMap(o,a);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(o)}`)}encodeBinary(o){let a=o.byteLength;if(a<256)this.writeU8(196),this.writeU8(a);else if(a<65536)this.writeU8(197),this.writeU16(a);else if(a<4294967296)this.writeU8(198),this.writeU32(a);else throw new Error(`Too large binary: ${a}`);let l=(0,r.ensureUint8Array)(o);this.writeU8a(l)}encodeArray(o,a){let l=o.length;if(l<16)this.writeU8(144+l);else if(l<65536)this.writeU8(220),this.writeU16(l);else if(l<4294967296)this.writeU8(221),this.writeU32(l);else throw new Error(`Too large array: ${l}`);for(let h of o)this.doEncode(h,a+1)}countWithoutUndefined(o,a){let l=0;for(let h of a)o[h]!==void 0&&l++;return l}encodeMap(o,a){let l=Object.keys(o);this.sortKeys&&l.sort();let h=this.ignoreUndefined?this.countWithoutUndefined(o,l):l.length;if(h<16)this.writeU8(128+h);else if(h<65536)this.writeU8(222),this.writeU16(h);else if(h<4294967296)this.writeU8(223),this.writeU32(h);else throw new Error(`Too large map object: ${h}`);for(let c of l){let f=o[c];this.ignoreUndefined&&f===void 0||(this.encodeString(c),this.doEncode(f,a+1))}}encodeExtension(o){let a=o.data.length;if(a===1)this.writeU8(212);else if(a===2)this.writeU8(213);else if(a===4)this.writeU8(214);else if(a===8)this.writeU8(215);else if(a===16)this.writeU8(216);else if(a<256)this.writeU8(199),this.writeU8(a);else if(a<65536)this.writeU8(200),this.writeU16(a);else if(a<4294967296)this.writeU8(201),this.writeU32(a);else throw new Error(`Too large extension object: ${a}`);this.writeI8(o.type),this.writeU8a(o.data)}writeU8(o){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,o),this.pos++}writeU8a(o){let a=o.length;this.ensureBufferSizeToWrite(a),this.bytes.set(o,this.pos),this.pos+=a}writeI8(o){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,o),this.pos++}writeU16(o){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,o),this.pos+=2}writeI16(o){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,o),this.pos+=2}writeU32(o){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,o),this.pos+=4}writeI32(o){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,o),this.pos+=4}writeF32(o){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,o),this.pos+=4}writeF64(o){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,o),this.pos+=8}writeU64(o){this.ensureBufferSizeToWrite(8),(0,n.setUint64)(this.view,this.pos,o),this.pos+=8}writeI64(o){this.ensureBufferSizeToWrite(8),(0,n.setInt64)(this.view,this.pos,o),this.pos+=8}};i.Encoder=s}),EO=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.encode=void 0;var e=yf(),t={};function n(r,s=t){return new e.Encoder(s.extensionCodec,s.context,s.maxDepth,s.initialBufferSize,s.sortKeys,s.forceFloat32,s.ignoreUndefined,s.forceIntegerToFloat).encodeSharedRef(r)}i.encode=n}),AO=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.prettyByte=void 0;function e(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}i.prettyByte=e}),QO=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CachedKeyDecoder=void 0;var e=Wa(),t=16,n=16,r=class{constructor(s=t,o=n){this.maxKeyLength=s,this.maxLengthPerKey=o,this.hit=0,this.miss=0,this.caches=[];for(let a=0;a0&&s<=this.maxKeyLength}find(s,o,a){let l=this.caches[a-1];e:for(let h of l){let c=h.bytes;for(let f=0;f=this.maxLengthPerKey?a[Math.random()*a.length|0]=l:a.push(l)}decode(s,o,a){let l=this.find(s,o,a);if(l!=null)return this.hit++,l;this.miss++;let h=(0,e.utf8DecodeJs)(s,o,a),c=Uint8Array.prototype.slice.call(s,o,o+a);return this.store(c,h),h}};i.CachedKeyDecoder=r}),ja=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Decoder=i.DataViewIndexOutOfBoundsError=void 0;var e=AO(),t=Na(),n=cs(),r=Wa(),s=Of(),o=QO(),a=Ia(),l=p=>{let g=typeof p;return g==="string"||g==="number"},h=-1,c=new DataView(new ArrayBuffer(0)),f=new Uint8Array(c.buffer);i.DataViewIndexOutOfBoundsError=(()=>{try{c.getInt8(0)}catch(p){return p.constructor}throw new Error("never reached")})();var u=new i.DataViewIndexOutOfBoundsError("Insufficient data"),d=new o.CachedKeyDecoder,m=class{constructor(p=t.ExtensionCodec.defaultCodec,g=void 0,O=n.UINT32_MAX,y=n.UINT32_MAX,v=n.UINT32_MAX,x=n.UINT32_MAX,w=n.UINT32_MAX,P=d){this.extensionCodec=p,this.context=g,this.maxStrLength=O,this.maxBinLength=y,this.maxArrayLength=v,this.maxMapLength=x,this.maxExtLength=w,this.keyDecoder=P,this.totalPos=0,this.pos=0,this.view=c,this.bytes=f,this.headByte=h,this.stack=[]}reinitializeState(){this.totalPos=0,this.headByte=h,this.stack.length=0}setBuffer(p){this.bytes=(0,s.ensureUint8Array)(p),this.view=(0,s.createDataView)(this.bytes),this.pos=0}appendBuffer(p){if(this.headByte===h&&!this.hasRemaining(1))this.setBuffer(p);else{let g=this.bytes.subarray(this.pos),O=(0,s.ensureUint8Array)(p),y=new Uint8Array(g.length+O.length);y.set(g),y.set(O,g.length),this.setBuffer(y)}}hasRemaining(p){return this.view.byteLength-this.pos>=p}createExtraByteError(p){let{view:g,pos:O}=this;return new RangeError(`Extra ${g.byteLength-O} of ${g.byteLength} byte(s) found at buffer[${p}]`)}decode(p){this.reinitializeState(),this.setBuffer(p);let g=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return g}*decodeMulti(p){for(this.reinitializeState(),this.setBuffer(p);this.hasRemaining(1);)yield this.doDecodeSync()}async decodeAsync(p){let g=!1,O;for await(let w of p){if(g)throw this.createExtraByteError(this.totalPos);this.appendBuffer(w);try{O=this.doDecodeSync(),g=!0}catch(P){if(!(P instanceof i.DataViewIndexOutOfBoundsError))throw P}this.totalPos+=this.pos}if(g){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return O}let{headByte:y,pos:v,totalPos:x}=this;throw new RangeError(`Insufficient data in parsing ${(0,e.prettyByte)(y)} at ${x} (${v} in the current buffer)`)}decodeArrayStream(p){return this.decodeMultiAsync(p,!0)}decodeStream(p){return this.decodeMultiAsync(p,!1)}async*decodeMultiAsync(p,g){let O=g,y=-1;for await(let v of p){if(g&&y===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(v),O&&(y=this.readArraySize(),O=!1,this.complete());try{for(;yield this.doDecodeSync(),--y!==0;);}catch(x){if(!(x instanceof i.DataViewIndexOutOfBoundsError))throw x}this.totalPos+=this.pos}}doDecodeSync(){e:for(;;){let p=this.readHeadByte(),g;if(p>=224)g=p-256;else if(p<192)if(p<128)g=p;else if(p<144){let y=p-128;if(y!==0){this.pushMapState(y),this.complete();continue e}else g={}}else if(p<160){let y=p-144;if(y!==0){this.pushArrayState(y),this.complete();continue e}else g=[]}else{let y=p-160;g=this.decodeUtf8String(y,0)}else if(p===192)g=null;else if(p===194)g=!1;else if(p===195)g=!0;else if(p===202)g=this.readF32();else if(p===203)g=this.readF64();else if(p===204)g=this.readU8();else if(p===205)g=this.readU16();else if(p===206)g=this.readU32();else if(p===207)g=this.readU64();else if(p===208)g=this.readI8();else if(p===209)g=this.readI16();else if(p===210)g=this.readI32();else if(p===211)g=this.readI64();else if(p===217){let y=this.lookU8();g=this.decodeUtf8String(y,1)}else if(p===218){let y=this.lookU16();g=this.decodeUtf8String(y,2)}else if(p===219){let y=this.lookU32();g=this.decodeUtf8String(y,4)}else if(p===220){let y=this.readU16();if(y!==0){this.pushArrayState(y),this.complete();continue e}else g=[]}else if(p===221){let y=this.readU32();if(y!==0){this.pushArrayState(y),this.complete();continue e}else g=[]}else if(p===222){let y=this.readU16();if(y!==0){this.pushMapState(y),this.complete();continue e}else g={}}else if(p===223){let y=this.readU32();if(y!==0){this.pushMapState(y),this.complete();continue e}else g={}}else if(p===196){let y=this.lookU8();g=this.decodeBinary(y,1)}else if(p===197){let y=this.lookU16();g=this.decodeBinary(y,2)}else if(p===198){let y=this.lookU32();g=this.decodeBinary(y,4)}else if(p===212)g=this.decodeExtension(1,0);else if(p===213)g=this.decodeExtension(2,0);else if(p===214)g=this.decodeExtension(4,0);else if(p===215)g=this.decodeExtension(8,0);else if(p===216)g=this.decodeExtension(16,0);else if(p===199){let y=this.lookU8();g=this.decodeExtension(y,1)}else if(p===200){let y=this.lookU16();g=this.decodeExtension(y,2)}else if(p===201){let y=this.lookU32();g=this.decodeExtension(y,4)}else throw new a.DecodeError(`Unrecognized type byte: ${(0,e.prettyByte)(p)}`);this.complete();let O=this.stack;for(;O.length>0;){let y=O[O.length-1];if(y.type===0)if(y.array[y.position]=g,y.position++,y.position===y.size)O.pop(),g=y.array;else continue e;else if(y.type===1){if(!l(g))throw new a.DecodeError("The type of key must be string or number but "+typeof g);if(g==="__proto__")throw new a.DecodeError("The key __proto__ is not allowed");y.key=g,y.type=2;continue e}else if(y.map[y.key]=g,y.readCount++,y.readCount===y.size)O.pop(),g=y.map;else{y.key=null,y.type=1;continue e}}return g}}readHeadByte(){return this.headByte===h&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=h}readArraySize(){let p=this.readHeadByte();switch(p){case 220:return this.readU16();case 221:return this.readU32();default:{if(p<160)return p-144;throw new a.DecodeError(`Unrecognized array type byte: ${(0,e.prettyByte)(p)}`)}}}pushMapState(p){if(p>this.maxMapLength)throw new a.DecodeError(`Max length exceeded: map length (${p}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.push({type:1,size:p,key:null,readCount:0,map:{}})}pushArrayState(p){if(p>this.maxArrayLength)throw new a.DecodeError(`Max length exceeded: array length (${p}) > maxArrayLength (${this.maxArrayLength})`);this.stack.push({type:0,size:p,array:new Array(p),position:0})}decodeUtf8String(p,g){var O;if(p>this.maxStrLength)throw new a.DecodeError(`Max length exceeded: UTF-8 byte length (${p}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLengthr.TEXT_DECODER_THRESHOLD?v=(0,r.utf8DecodeTD)(this.bytes,y,p):v=(0,r.utf8DecodeJs)(this.bytes,y,p),this.pos+=g+p,v}stateIsMapKey(){return this.stack.length>0?this.stack[this.stack.length-1].type===1:!1}decodeBinary(p,g){if(p>this.maxBinLength)throw new a.DecodeError(`Max length exceeded: bin length (${p}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(p+g))throw u;let O=this.pos+g,y=this.bytes.subarray(O,O+p);return this.pos+=g+p,y}decodeExtension(p,g){if(p>this.maxExtLength)throw new a.DecodeError(`Max length exceeded: ext length (${p}) > maxExtLength (${this.maxExtLength})`);let O=this.view.getInt8(this.pos+g),y=this.decodeBinary(p,g+1);return this.extensionCodec.decode(y,O,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let p=this.view.getUint8(this.pos);return this.pos++,p}readI8(){let p=this.view.getInt8(this.pos);return this.pos++,p}readU16(){let p=this.view.getUint16(this.pos);return this.pos+=2,p}readI16(){let p=this.view.getInt16(this.pos);return this.pos+=2,p}readU32(){let p=this.view.getUint32(this.pos);return this.pos+=4,p}readI32(){let p=this.view.getInt32(this.pos);return this.pos+=4,p}readU64(){let p=(0,n.getUint64)(this.view,this.pos);return this.pos+=8,p}readI64(){let p=(0,n.getInt64)(this.view,this.pos);return this.pos+=8,p}readF32(){let p=this.view.getFloat32(this.pos);return this.pos+=4,p}readF64(){let p=this.view.getFloat64(this.pos);return this.pos+=8,p}};i.Decoder=m}),bf=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decodeMulti=i.decode=i.defaultDecodeOptions=void 0;var e=ja();i.defaultDecodeOptions={};function t(r,s=i.defaultDecodeOptions){return new e.Decoder(s.extensionCodec,s.context,s.maxStrLength,s.maxBinLength,s.maxArrayLength,s.maxMapLength,s.maxExtLength).decode(r)}i.decode=t;function n(r,s=i.defaultDecodeOptions){return new e.Decoder(s.extensionCodec,s.context,s.maxStrLength,s.maxBinLength,s.maxArrayLength,s.maxMapLength,s.maxExtLength).decodeMulti(r)}i.decodeMulti=n}),MO=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ensureAsyncIterable=i.asyncIterableFromStream=i.isAsyncIterable=void 0;function e(s){return s[Symbol.asyncIterator]!=null}i.isAsyncIterable=e;function t(s){if(s==null)throw new Error("Assertion Failure: value must not be null nor undefined")}async function*n(s){let o=s.getReader();try{for(;;){let{done:a,value:l}=await o.read();if(a)return;t(l),yield l}}finally{o.releaseLock()}}i.asyncIterableFromStream=n;function r(s){return e(s)?s:n(s)}i.ensureAsyncIterable=r}),_O=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decodeStream=i.decodeMultiStream=i.decodeArrayStream=i.decodeAsync=void 0;var e=ja(),t=MO(),n=bf();async function r(l,h=n.defaultDecodeOptions){let c=(0,t.ensureAsyncIterable)(l);return new e.Decoder(h.extensionCodec,h.context,h.maxStrLength,h.maxBinLength,h.maxArrayLength,h.maxMapLength,h.maxExtLength).decodeAsync(c)}i.decodeAsync=r;function s(l,h=n.defaultDecodeOptions){let c=(0,t.ensureAsyncIterable)(l);return new e.Decoder(h.extensionCodec,h.context,h.maxStrLength,h.maxBinLength,h.maxArrayLength,h.maxMapLength,h.maxExtLength).decodeArrayStream(c)}i.decodeArrayStream=s;function o(l,h=n.defaultDecodeOptions){let c=(0,t.ensureAsyncIterable)(l);return new e.Decoder(h.extensionCodec,h.context,h.maxStrLength,h.maxBinLength,h.maxArrayLength,h.maxMapLength,h.maxExtLength).decodeStream(c)}i.decodeMultiStream=o;function a(l,h=n.defaultDecodeOptions){return o(l,h)}i.decodeStream=a}),za=ke(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decodeTimestampExtension=i.encodeTimestampExtension=i.decodeTimestampToTimeSpec=i.encodeTimeSpecToTimestamp=i.encodeDateToTimeSpec=i.EXT_TIMESTAMP=i.ExtData=i.ExtensionCodec=i.Encoder=i.DataViewIndexOutOfBoundsError=i.DecodeError=i.Decoder=i.decodeStream=i.decodeMultiStream=i.decodeArrayStream=i.decodeAsync=i.decodeMulti=i.decode=i.encode=void 0;var e=EO();Object.defineProperty(i,"encode",{enumerable:!0,get:function(){return e.encode}});var t=bf();Object.defineProperty(i,"decode",{enumerable:!0,get:function(){return t.decode}}),Object.defineProperty(i,"decodeMulti",{enumerable:!0,get:function(){return t.decodeMulti}});var n=_O();Object.defineProperty(i,"decodeAsync",{enumerable:!0,get:function(){return n.decodeAsync}}),Object.defineProperty(i,"decodeArrayStream",{enumerable:!0,get:function(){return n.decodeArrayStream}}),Object.defineProperty(i,"decodeMultiStream",{enumerable:!0,get:function(){return n.decodeMultiStream}}),Object.defineProperty(i,"decodeStream",{enumerable:!0,get:function(){return n.decodeStream}});var r=ja();Object.defineProperty(i,"Decoder",{enumerable:!0,get:function(){return r.Decoder}}),Object.defineProperty(i,"DataViewIndexOutOfBoundsError",{enumerable:!0,get:function(){return r.DataViewIndexOutOfBoundsError}});var s=Ia();Object.defineProperty(i,"DecodeError",{enumerable:!0,get:function(){return s.DecodeError}});var o=yf();Object.defineProperty(i,"Encoder",{enumerable:!0,get:function(){return o.Encoder}});var a=Na();Object.defineProperty(i,"ExtensionCodec",{enumerable:!0,get:function(){return a.ExtensionCodec}});var l=mf();Object.defineProperty(i,"ExtData",{enumerable:!0,get:function(){return l.ExtData}});var h=gf();Object.defineProperty(i,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return h.EXT_TIMESTAMP}}),Object.defineProperty(i,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return h.encodeDateToTimeSpec}}),Object.defineProperty(i,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return h.encodeTimeSpecToTimestamp}}),Object.defineProperty(i,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return h.decodeTimestampToTimeSpec}}),Object.defineProperty(i,"encodeTimestampExtension",{enumerable:!0,get:function(){return h.encodeTimestampExtension}}),Object.defineProperty(i,"decodeTimestampExtension",{enumerable:!0,get:function(){return h.decodeTimestampExtension}})}),di=class extends Error{constructor(i){super(i),this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},wf=class extends di{},pt=class extends di{},Bn=class extends di{},Ie=typeof process<"u"&&process.release&&process.release.name==="node",ga;if(globalThis.document)ga=i=>new Promise((e,t)=>{let n=document.createElement("script");n.src=i,n.onload=()=>e(),n.onerror=t,document.head.appendChild(n)});else if(globalThis.importScripts)ga=async i=>{try{globalThis.importScripts(i)}catch(e){if(e instanceof TypeError)await Promise.resolve().then(()=>Xi(Bi(i)));else throw e}};else if(Ie)ga=async i=>{let e=(await Promise.resolve().then(()=>Xi(Bi("path")))).default;await Promise.resolve().then(()=>Xi(Bi(e.resolve(i))))};else throw new di("Cannot determine runtime environment");var T={};function DO(i){Object.keys(i).forEach(e=>T._free(i[e]))}var mt={null:0,symbol:1,pairlist:2,closure:3,environment:4,promise:5,call:6,special:7,builtin:8,string:9,logical:10,integer:13,double:14,complex:15,character:16,dots:17,any:18,list:19,expression:20,bytecode:21,pointer:22,weakref:23,raw:24,s4:25,new:30,free:31,function:99};function vf(i){return!!i&&typeof i=="object"&&Object.keys(mt).includes(i.type)}function fs(i){return!!i&&typeof i=="object"&&"re"in i&&"im"in i}function Yr(i){return T._Rf_protect(Mt(i)),i}function ae(i,e){return T._Rf_protect(Mt(i)),++e.n,i}function $O(i){let e=T._malloc(4);return T._R_ProtectWithIndex(Mt(i),e),{loc:T.getValue(e,"i32"),ptr:e}}function VO(i){T._Rf_unprotect(1),T._free(i.ptr)}function LO(i,e){return T._R_Reprotect(Mt(i),e.loc),i}function Oe(i){T._Rf_unprotect(i)}function af(i,e,t){T._Rf_defineVar(Mt(e),Mt(t),Mt(i))}function lf(i,e){let t={},n={n:0};try{let r=new Tf(e);ae(r,n),t.code=T.allocateUTF8(i);let s=T._R_ParseEvalString(t.code,r.ptr);return z.wrap(s)}finally{DO(t),Oe(n.n)}}function us(i,e){return T.getWasmTableEntry(T.GOT.ffi_safe_eval.value)(Mt(i),Mt(e))}var qO=new WeakMap;function BO(i,e){return qO.set(i,e),i}var XO=63;function xf(){let i=Array.from({length:4},WO).join("-");if(i.length!==XO)throw new Error("comlink internal error: UUID has the wrong length");return i}function WO(){let i=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16),e=15-i.length;return e>0&&(i=Array.from({length:e},()=>0).join("")+i),i}function Mt(i){return rs(i)?i.ptr:i}function pi(i,e){if(T._TYPEOF(i.ptr)!==mt[e])throw new Error(`Unexpected object type "${i.type()}" when expecting type "${e}"`)}function kf(i){if(vf(i))return new(_f(i.type))(i);if(i&&typeof i=="object"&&"type"in i&&i.type==="null")return new Sf;if(i===null)return new Ni({type:"logical",names:null,values:[null]});if(typeof i=="boolean")return new Ni(i);if(typeof i=="number")return new ps(i);if(typeof i=="string")return new zt(i);if(fs(i))return new Fa(i);if(ArrayBuffer.isView(i)||i instanceof ArrayBuffer)return new Ha(i);if(Array.isArray(i))return IO(i);if(typeof i=="object")return Xn.fromObject(i);throw new Error("Robj construction for this JS object is not yet supported")}function IO(i){let e={n:0};if(i.every(t=>t&&typeof t=="object"&&!rs(t)&&!fs(t))){let t=i,n=t.every(s=>Object.keys(s).filter(o=>!Object.keys(t[0]).includes(o)).length===0&&Object.keys(t[0]).filter(o=>!Object.keys(s).includes(o)).length===0),r=t.every(s=>Object.values(s).every(o=>$f(o)||Df(o)));if(n&&r)return Xn.fromD3(t)}if(i.every(t=>typeof t=="boolean"||t===null))return new Ni(i);if(i.every(t=>typeof t=="number"||t===null))return new ps(i);if(i.every(t=>typeof t=="string"||t===null))return new zt(i);try{let t=new ui([new gt("c"),...i]);return ae(t,e),t.eval()}finally{Oe(e.n)}}var ye=class{constructor(i){this.ptr=i}type(){let i=T._TYPEOF(this.ptr);return Object.keys(mt).find(e=>mt[e]===i)}},_n,Zr,Wi=class extends ye{constructor(i){if(!(i instanceof ye))return kf(i);super(i.ptr),L(this,_n)}static wrap(i){let e=T._TYPEOF(i),t=Object.keys(mt)[Object.values(mt).indexOf(e)];return new(_f(t))(new ye(i))}get[Symbol.toStringTag](){return`RObject:${this.type()}`}static getPersistentObject(i){return xe[i]}getPropertyValue(i){return this[i]}inspect(){lf(".Internal(inspect(x))",{x:this})}isNull(){return T._TYPEOF(this.ptr)===mt.null}isNa(){try{let i=lf("is.na(x)",{x:this});return Yr(i),i.toBoolean()}finally{Oe(1)}}isUnbound(){return this.ptr===xe.unboundValue.ptr}attrs(){return ds.wrap(T._ATTRIB(this.ptr))}class(){let i={n:0},e=new ui([new gt("class"),this]);ae(e,i);try{return e.eval()}finally{Oe(i.n)}}setNames(i){let e;if(i===null)e=xe.null;else if(Array.isArray(i)&&i.every(t=>typeof t=="string"||t===null))e=new zt(i);else throw new Error("Argument to setNames must be null or an Array of strings or null");return T._Rf_setAttrib(this.ptr,xe.namesSymbol.ptr,e.ptr),this}names(){let i=zt.wrap(T._Rf_getAttrib(this.ptr,xe.namesSymbol.ptr));return i.isNull()?null:i.toArray()}includes(i){let e=this.names();return e&&e.includes(i)}toJs(i={depth:0},e=1){throw new Error("This R object cannot be converted to JS")}subset(i){return Je(this,_n,Zr).call(this,i,xe.bracketSymbol.ptr)}get(i){return Je(this,_n,Zr).call(this,i,xe.bracket2Symbol.ptr)}getDollar(i){return Je(this,_n,Zr).call(this,i,xe.dollarSymbol.ptr)}pluck(...i){let e=$O(xe.null);try{let t=(r,s)=>{let o=r.get(s);return LO(o,e)},n=i.reduce(t,this);return n.isNull()?void 0:n}finally{VO(e)}}set(i,e){let t={n:0};try{let n=new Wi(i);ae(n,t);let r=new Wi(e);ae(r,t);let s=new gt("[[<-"),o=T._Rf_lang4(s.ptr,this.ptr,n.ptr,r.ptr);return ae(o,t),Wi.wrap(us(o,xe.baseEnv))}finally{Oe(t.n)}}static getMethods(i){let e=new Set,t=i;do Object.getOwnPropertyNames(t).map(n=>e.add(n));while(t=Object.getPrototypeOf(t));return[...e.keys()].filter(n=>typeof i[n]=="function")}},z=Wi;_n=new WeakSet,Zr=function(i,e){let t={n:0};try{let n=new Wi(i);ae(n,t);let r=T._Rf_lang3(e,this.ptr,n.ptr);return ae(r,t),Wi.wrap(us(r,xe.baseEnv))}finally{Oe(t.n)}};var Sf=class extends z{constructor(){return super(new ye(T.getValue(T._R_NilValue,"*"))),this}toJs(){return{type:"null"}}},gt=class extends z{constructor(i){if(i instanceof ye){pi(i,"symbol"),super(i);return}let e=T.allocateUTF8(i);try{super(new ye(T._Rf_install(e)))}finally{T._free(e)}}toJs(){let i=this.toObject();return{type:"symbol",printname:i.printname,symvalue:i.symvalue,internal:i.internal}}toObject(){return{printname:this.printname().isUnbound()?null:this.printname().toString(),symvalue:this.symvalue().isUnbound()?null:this.symvalue().ptr,internal:this.internal().isNull()?null:this.internal().ptr}}toString(){return this.printname().toString()}printname(){return Ua.wrap(T._PRINTNAME(this.ptr))}symvalue(){return z.wrap(T._SYMVALUE(this.ptr))}internal(){return z.wrap(T._INTERNAL(this.ptr))}},ds=class extends z{constructor(i){if(i instanceof ye)return pi(i,"pairlist"),super(i),this;let e={n:0};try{let{names:t,values:n}=zi(i),r=ds.wrap(T._Rf_allocList(n.length));ae(r,e);for(let[s,o]=[0,r];!o.isNull();[s,o]=[s+1,o.cdr()])o.setcar(new z(n[s]));r.setNames(t),super(r)}finally{Oe(e.n)}}get length(){return this.toArray().length}toArray(i={depth:1}){return this.toJs(i).values}toObject({allowDuplicateKey:i=!0,allowEmptyKey:e=!1,depth:t=-1}={}){let n=this.entries({depth:t}),r=n.map(([s])=>s);if(!i&&new Set(r).size!==r.length)throw new Error("Duplicate key when converting pairlist without allowDuplicateKey enabled");if(!e&&r.some(s=>!s))throw new Error("Empty or null key when converting pairlist without allowEmptyKey enabled");return Object.fromEntries(n.filter((s,o)=>n.findIndex(a=>a[0]===s[0])===o))}entries(i={depth:1}){let e=this.toJs(i);return e.values.map((t,n)=>[e.names?e.names[n]:null,t])}toJs(i={depth:0},e=1){let t=[],n=!1,r=[];for(let s=this;!s.isNull();s=s.cdr()){let o=s.tag();o.isNull()?t.push(""):(n=!0,t.push(o.toString())),i.depth&&e>=i.depth?r.push(s.car()):r.push(s.car().toJs(i,e+1))}return{type:"pairlist",names:n?t:null,values:r}}includes(i){return i in this.toObject()}setcar(i){T._SETCAR(this.ptr,i.ptr)}car(){return z.wrap(T._CAR(this.ptr))}cdr(){return z.wrap(T._CDR(this.ptr))}tag(){return z.wrap(T._TAG(this.ptr))}},ui=class extends z{constructor(i){if(i instanceof ye)return pi(i,"call"),super(i),this;let e={n:0};try{let{values:t}=zi(i),n=t.map(s=>ae(new z(s),e)),r=ui.wrap(T._Rf_allocVector(mt.call,t.length));ae(r,e);for(let[s,o]=[0,r];!o.isNull();[s,o]=[s+1,o.cdr()])o.setcar(n[s]);super(r)}finally{Oe(e.n)}}setcar(i){T._SETCAR(this.ptr,i.ptr)}car(){return z.wrap(T._CAR(this.ptr))}cdr(){return z.wrap(T._CDR(this.ptr))}eval(){return T.webr.evalR(this,{env:xe.baseEnv})}capture(i={}){return T.webr.captureR(this,i)}deparse(){let i={n:0};try{let e=T._Rf_lang2(new gt("deparse1").ptr,T._Rf_lang2(new gt("quote").ptr,this.ptr));ae(e,i);let t=zt.wrap(us(e,xe.baseEnv));return ae(t,i),t.toString()}finally{Oe(i.n)}}},ya=class extends z{constructor(i,e=null){if(i instanceof ye){if(pi(i,"list"),super(i),e){if(e.length!==this.length)throw new Error("Can't construct named `RList`. Supplied `names` must be the same length as the list.");this.setNames(e)}return this}let t={n:0};try{let n=zi(i),r=T._Rf_allocVector(mt.list,n.values.length);ae(r,t),n.values.forEach((o,a)=>{T._SET_VECTOR_ELT(r,a,new z(o).ptr)});let s=e||n.names;if(s&&s.length!==n.values.length)throw new Error("Can't construct named `RList`. Supplied `names` must be the same length as the list.");z.wrap(r).setNames(s),super(new ye(r))}finally{Oe(t.n)}}get length(){return T._LENGTH(this.ptr)}isDataFrame(){let i=ds.wrap(T._ATTRIB(this.ptr)).get("class");return!i.isNull()&&i.toArray().includes("data.frame")}toArray(i={depth:1}){return this.toJs(i).values}toObject({allowDuplicateKey:i=!0,allowEmptyKey:e=!1,depth:t=-1}={}){let n=this.entries({depth:t}),r=n.map(([s])=>s);if(!i&&new Set(r).size!==r.length)throw new Error("Duplicate key when converting list without allowDuplicateKey enabled");if(!e&&r.some(s=>!s))throw new Error("Empty or null key when converting list without allowEmptyKey enabled");return Object.fromEntries(n.filter((s,o)=>n.findIndex(a=>a[0]===s[0])===o))}toD3(){if(!this.isDataFrame())throw new Error("Can't convert R list object to D3 format. Object must be of class 'data.frame'.");return this.entries().reduce((i,e)=>(e[1].forEach((t,n)=>i[n]=Object.assign(i[n]||{},{[e[0]]:t})),i),[])}entries(i={depth:-1}){let e=this.toJs(i);return this.isDataFrame()&&i.depth<0&&(e.values=e.values.map(t=>t.toArray())),e.values.map((t,n)=>[e.names?e.names[n]:null,t])}toJs(i={depth:0},e=1){return{type:"list",names:this.names(),values:[...Array(this.length).keys()].map(t=>i.depth&&e>=i.depth?this.get(t+1):this.get(t+1).toJs(i,e+1))}}},Xn=class extends ya{constructor(i){if(i instanceof ye){if(super(i),!this.isDataFrame())throw new Error("Can't construct `RDataFrame`. Supplied R object is not a `data.frame`.");return this}return Xn.fromObject(i)}static fromObject(i){let{names:e,values:t}=zi(i),n={n:0};try{let r=!!e&&e.length>0&&e.every(o=>o),s=t.length>0&&t.every(o=>Array.isArray(o)||ArrayBuffer.isView(o)||o instanceof ArrayBuffer);if(r&&s){let o=t,a=o.every(h=>h.length===o[0].length),l=o.every(h=>$f(h[0])||Df(h[0]));if(a&&l){let h=new ya({type:"list",names:e,values:o.map(f=>kf(f))});ae(h,n);let c=new ui([new gt("as.data.frame"),h]);return ae(c,n),new Xn(c.eval())}}}finally{Oe(n.n)}throw new Error("Can't construct `data.frame`. Source object is not eligible.")}static fromD3(i){return this.fromObject(Object.fromEntries(Object.keys(i[0]).map(e=>[e,i.map(t=>t[e])])))}},Gr=class extends z{exec(...i){let e={n:0};try{let t=new ui([this,...i]);return ae(t,e),t.eval()}finally{Oe(e.n)}}capture(i={},...e){let t={n:0};try{let n=new ui([this,...e]);return ae(n,t),n.capture(i)}finally{Oe(t.n)}}},Ua=class extends z{constructor(i){if(i instanceof ye){pi(i,"string"),super(i);return}let e=T.allocateUTF8(i);try{super(new ye(T._Rf_mkChar(e)))}finally{T._free(e)}}toString(){return T.UTF8ToString(T._R_CHAR(this.ptr))}toJs(){return{type:"string",value:this.toString()}}},Tf=class extends z{constructor(i={}){if(i instanceof ye)return pi(i,"environment"),super(i),this;let e=0;try{let{names:t,values:n}=zi(i),r=Yr(T._R_NewEnv(xe.globalEnv.ptr,0,0));++e,n.forEach((s,o)=>{let a=t?t[o]:null;if(!a)throw new Error("Can't create object in new environment with empty symbol name");let l=new gt(a),h=Yr(new z(s));try{af(r,l,h)}finally{Oe(1)}}),super(new ye(r))}finally{Oe(e)}}ls(i=!1,e=!0){return zt.wrap(T._R_lsInternal3(this.ptr,Number(i),Number(e))).toArray()}bind(i,e){let t=new gt(i),n=Yr(new z(e));try{af(this,t,n)}finally{Oe(1)}}names(){return this.ls(!0,!0)}frame(){return z.wrap(T._FRAME(this.ptr))}subset(i){if(typeof i=="number")throw new Error("Object of type environment is not subsettable");return this.getDollar(i)}toObject({depth:i=-1}={}){let e=this.names();return Object.fromEntries([...Array(e.length).keys()].map(t=>{let n=this.getDollar(e[t]);return[e[t],i<0?n:n.toJs({depth:i})]}))}toJs(i={depth:0},e=1){let t=this.names(),n=[...Array(t.length).keys()].map(r=>i.depth&&e>=i.depth?this.getDollar(t[r]):this.getDollar(t[r]).toJs(i,e+1));return{type:"environment",names:t,values:n}}},ji=class extends z{constructor(i,e,t){if(i instanceof ye)return pi(i,e),super(i),this;let n={n:0};try{let{names:r,values:s}=zi(i),o=T._Rf_allocVector(mt[e],s.length);ae(o,n),s.forEach(t(o)),z.wrap(o).setNames(r),super(new ye(o))}finally{Oe(n.n)}}get length(){return T._LENGTH(this.ptr)}get(i){return super.get(i)}subset(i){return super.subset(i)}getDollar(){throw new Error("$ operator is invalid for atomic vectors")}detectMissing(){let i={n:0};try{let e=T._Rf_lang2(new gt("is.na").ptr,this.ptr);ae(e,i);let t=Ni.wrap(us(e,xe.baseEnv));ae(t,i);let n=t.toTypedArray();return Array.from(n).map(r=>!!r)}finally{Oe(i.n)}}toArray(){let i=this.toTypedArray();return this.detectMissing().map((e,t)=>e?null:i[t])}toObject({allowDuplicateKey:i=!0,allowEmptyKey:e=!1}={}){let t=this.entries(),n=t.map(([r])=>r);if(!i&&new Set(n).size!==n.length)throw new Error("Duplicate key when converting atomic vector without allowDuplicateKey enabled");if(!e&&n.some(r=>!r))throw new Error("Empty or null key when converting atomic vector without allowEmptyKey enabled");return Object.fromEntries(t.filter((r,s)=>t.findIndex(o=>o[0]===r[0])===s))}entries(){let i=this.toArray(),e=this.names();return i.map((t,n)=>[e?e[n]:null,t])}toJs(){return{type:this.type(),names:this.names(),values:this.toArray()}}},ba,Pf=class extends ji{constructor(i){super(i,"logical",k(Pf,ba))}getBoolean(i){return this.get(i).toArray()[0]}toBoolean(){if(this.length!==1)throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");let i=this.getBoolean(1);if(i===null)throw new Error("Can't convert missing value `NA` to a JS boolean");return i}toTypedArray(){return new Int32Array(T.HEAP32.subarray(T._LOGICAL(this.ptr)/4,T._LOGICAL(this.ptr)/4+this.length))}toArray(){let i=this.toTypedArray();return this.detectMissing().map((e,t)=>e?null:!!i[t])}},Ni=Pf;ba=new WeakMap,L(Ni,ba,i=>{let e=T._LOGICAL(i),t=T.getValue(T._R_NaInt,"i32");return(n,r)=>{T.setValue(e+4*r,n===null?t:!!n,"i32")}});var wa,Cf=class extends ji{constructor(i){super(i,"integer",k(Cf,wa))}getNumber(i){return this.get(i).toArray()[0]}toNumber(){if(this.length!==1)throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");let i=this.getNumber(1);if(i===null)throw new Error("Can't convert missing value `NA` to a JS number");return i}toTypedArray(){return new Int32Array(T.HEAP32.subarray(T._INTEGER(this.ptr)/4,T._INTEGER(this.ptr)/4+this.length))}},Rf=Cf;wa=new WeakMap,L(Rf,wa,i=>{let e=T._INTEGER(i),t=T.getValue(T._R_NaInt,"i32");return(n,r)=>{T.setValue(e+4*r,n===null?t:Math.round(Number(n)),"i32")}});var va,Ef=class extends ji{constructor(i){super(i,"double",k(Ef,va))}getNumber(i){return this.get(i).toArray()[0]}toNumber(){if(this.length!==1)throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");let i=this.getNumber(1);if(i===null)throw new Error("Can't convert missing value `NA` to a JS number");return i}toTypedArray(){return new Float64Array(T.HEAPF64.subarray(T._REAL(this.ptr)/8,T._REAL(this.ptr)/8+this.length))}},ps=Ef;va=new WeakMap,L(ps,va,i=>{let e=T._REAL(i),t=T.getValue(T._R_NaReal,"double");return(n,r)=>{T.setValue(e+8*r,n===null?t:n,"double")}});var xa,Af=class extends ji{constructor(i){super(i,"complex",k(Af,xa))}getComplex(i){return this.get(i).toArray()[0]}toComplex(){if(this.length!==1)throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");let i=this.getComplex(1);if(i===null)throw new Error("Can't convert missing value `NA` to a JS object");return i}toTypedArray(){return new Float64Array(T.HEAPF64.subarray(T._COMPLEX(this.ptr)/8,T._COMPLEX(this.ptr)/8+2*this.length))}toArray(){let i=this.toTypedArray();return this.detectMissing().map((e,t)=>e?null:{re:i[2*t],im:i[2*t+1]})}},Fa=Af;xa=new WeakMap,L(Fa,xa,i=>{let e=T._COMPLEX(i),t=T.getValue(T._R_NaReal,"double");return(n,r)=>{T.setValue(e+8*(2*r),n===null?t:n.re,"double"),T.setValue(e+8*(2*r+1),n===null?t:n.im,"double")}});var ka,Qf=class extends ji{constructor(i){super(i,"character",k(Qf,ka))}getString(i){return this.get(i).toArray()[0]}toString(){if(this.length!==1)throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");let i=this.getString(1);if(i===null)throw new Error("Can't convert missing value `NA` to a JS string");return i}toTypedArray(){return new Uint32Array(T.HEAPU32.subarray(T._STRING_PTR(this.ptr)/4,T._STRING_PTR(this.ptr)/4+this.length))}toArray(){return this.detectMissing().map((i,e)=>i?null:T.UTF8ToString(T._R_CHAR(T._STRING_ELT(this.ptr,e))))}},zt=Qf;ka=new WeakMap,L(zt,ka,i=>(e,t)=>{e===null?T._SET_STRING_ELT(i,t,xe.naString.ptr):T._SET_STRING_ELT(i,t,new Ua(e).ptr)});var Sa,Mf=class extends ji{constructor(i){i instanceof ArrayBuffer&&(i=new Uint8Array(i)),super(i,"raw",k(Mf,Sa))}getNumber(i){return this.get(i).toArray()[0]}toNumber(){if(this.length!==1)throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");let i=this.getNumber(1);if(i===null)throw new Error("Can't convert missing value `NA` to a JS number");return i}toTypedArray(){return new Uint8Array(T.HEAPU8.subarray(T._RAW(this.ptr),T._RAW(this.ptr)+this.length))}},Ha=Mf;Sa=new WeakMap,L(Ha,Sa,i=>{let e=T._RAW(i);return(t,n)=>{T.setValue(e+n,Number(t),"i8")}});function zi(i){return vf(i)?i:Array.isArray(i)||ArrayBuffer.isView(i)?{names:null,values:i}:i&&typeof i=="object"&&!fs(i)?{names:Object.keys(i),values:Object.values(i)}:{names:null,values:[i]}}function _f(i){let e={object:z,null:Sf,symbol:gt,pairlist:ds,closure:Gr,environment:Tf,call:ui,special:Gr,builtin:Gr,string:Ua,logical:Ni,integer:Rf,double:ps,complex:Fa,character:zt,list:ya,raw:Ha,function:Gr,dataframe:Xn};return i in e?e[i]:z}function rs(i){return i instanceof z}function Df(i){let e=["logical","integer","double","complex","character"];return rs(i)&&e.includes(i.type())||rs(i)&&i.isNa()}function $f(i){return i===null||typeof i=="number"||typeof i=="boolean"||typeof i=="string"||fs(i)}var xe;function ms(){let i={resolve:()=>{},reject:()=>{},promise:Promise.resolve()},e=new Promise((t,n)=>{i.resolve=t,i.reject=n});return i.promise=e,i}function NO(i){return new Promise(e=>setTimeout(e,i))}function Ut(i,e,t,...n){return i==null||jO(i)?i:i instanceof ArrayBuffer?new Uint8Array(i):e(i)?t(i,...n):Array.isArray(i)||ArrayBuffer.isView(i)?i.map(r=>Ut(r,e,t,...n)):i instanceof ye?i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([r,s])=>[r,Ut(s,e,t,...n)])):i}function Ga(i,e){let t=new XMLHttpRequest;t.open("get",i,!0),t.onload=()=>{let n=new Worker(URL.createObjectURL(new Blob([t.responseText])));e(n)},t.send()}function Ya(i){if(Ie)return!1;let e=new URL(location.href),t=new URL(i,location.origin);return!(e.host===t.host&&e.port===t.port&&e.protocol===t.protocol)}function jO(i){return typeof ImageBitmap<"u"&&i instanceof ImageBitmap}var zO=Xi(za()),UO=new TextEncoder;async function FO(i,e,t){try{let{taskId:n,sizeBuffer:r,dataBuffer:s,signalBuffer:o}=e,a=(0,zO.encode)(t),l=a.length<=s.length;if(Atomics.store(r,0,a.length),Atomics.store(r,1,+l),!l){let[h,c]=HO(i);s.set(UO.encode(h)),await hf(o,n),s=(await c).dataBuffer}s.set(a),Atomics.store(r,1,1),await hf(o,n)}catch(n){console.warn(n)}}function HO(i){let e=xf();return[e,new Promise(t=>{Ie?i.once("message",n=>{!n.id||n.id!==e||t(n)}):i.addEventListener("message",function n(r){!r.data||!r.data.id||r.data.id!==e||(i.removeEventListener("message",n),t(r.data))}),i.start&&i.start()})]}async function hf(i,e){let t=(e>>1)%32,n=1;for(;Atomics.compareExchange(i,t+1,0,e)!==0;)await NO(n),n<32&&(n*=2);Atomics.or(i,0,1<{k(this,At).push(i)}))};function GO(i,e){return Vf({type:"request",data:{uuid:xf(),msg:i}},e)}function Pa(i,e,t){return Vf({type:"response",data:{uuid:i,resp:e}},t)}function Vf(i,e){return e&&BO(i,e),i}function YO(i){let e=new wf(i.obj.message);return i.obj.name!=="Error"&&(e.name=i.obj.name),e.stack=i.obj.stack,e}function ZO(i){return!!i&&typeof i=="object"&&"payloadType"in i&&"obj"in i}function Lf(i){return ZO(i)&&i.payloadType==="ptr"}var Dn,Za=class{constructor(){this.inputQueue=new Oa,this.outputQueue=new Oa,this.systemQueue=new Oa,L(this,Dn,new Map)}async read(){return await this.outputQueue.get()}async flush(){let i=[];for(;!this.outputQueue.isEmpty();)i.push(await this.read());return i}async readSystem(){return await this.systemQueue.get()}write(i){this.inputQueue.put(i)}async request(i,e){let t=GO(i,e),{resolve:n,reject:r,promise:s}=ms();return k(this,Dn).set(t.data.uuid,{resolve:n,reject:r}),this.write(t),s}putClosedMessage(){this.outputQueue.put({type:"closed"})}resolveResponse(i){let e=i.data.uuid,t=k(this,Dn).get(e);if(t){let n=i.data.resp;k(this,Dn).delete(e),n.payloadType==="err"?t.reject(YO(n)):t.resolve(n)}else console.warn("Can't find request.")}};Dn=new WeakMap;var cS=Xi(za()),fS=new TextDecoder("utf-8"),JO,KO,e0,t0,i0;JO=new WeakMap,KO=new WeakMap,e0=new WeakMap,t0=new WeakMap,i0=new WeakMap;var uS=new Int32Array(new ArrayBuffer(4));Ie&&(globalThis.Worker=Bi("worker_threads").Worker);var $n,Ca,qf,Kr,cf=class extends Za{constructor(i){super(),L(this,Ca),L(this,$n,void 0),this.close=()=>{},L(this,Kr,async(t,n)=>{if(!(!n||!n.type))switch(n.type){case"resolve":me(this,$n,new Int32Array(n.data)),this.resolve();return;case"response":this.resolveResponse(n);return;case"system":this.systemQueue.put(n.data);return;default:this.outputQueue.put(n);return;case"sync-request":{let r=n,s=r.data.msg,o=r.data.reqData;switch(s.type){case"read":{let a=await this.inputQueue.get();await FO(t,o,a);break}default:throw new pt(`Unsupported request type '${s.type}'.`)}return}case"request":throw new pt("Can't send messages of type 'request' from a worker. Please Use 'sync-request' instead.")}});let e=t=>{Je(this,Ca,qf).call(this,t),this.close=()=>{t.terminate(),this.putClosedMessage()};let n={type:"init",data:{config:i,channelType:Qt.SharedArrayBuffer}};t.postMessage(n)};if(Ya(i.baseUrl))Ga(`${i.baseUrl}webr-worker.js`,t=>e(t));else{let t=new Worker(`${i.baseUrl}webr-worker.js`);e(t)}({resolve:this.resolve,promise:this.initialised}=ms())}interrupt(){if(!k(this,$n))throw new pt("Failed attempt to interrupt before initialising interruptBuffer");this.inputQueue.reset(),k(this,$n)[0]=1}};$n=new WeakMap,Ca=new WeakSet,qf=function(i){Ie?i.on("message",e=>{k(this,Kr).call(this,i,e)}):i.onmessage=e=>k(this,Kr).call(this,i,e.data)},Kr=new WeakMap;var n0,r0,s0,o0;n0=new WeakMap,r0=new WeakMap,s0=new WeakMap,o0=new WeakMap;var dS=Xi(za());Ie&&(globalThis.Worker=Bi("worker_threads").Worker);var Ln,Ii,qn,Ra,Bf,Ea,ff,Aa,Xf,es,a0=class extends Za{constructor(i){super(),L(this,Ra),L(this,Ea),L(this,Aa),this.close=()=>{},L(this,Ln,new Map),L(this,Ii,void 0),L(this,qn,!1),L(this,es,(t,n)=>{if(!(!n||!n.type))switch(n.type){case"resolve":this.resolve();return;case"response":this.resolveResponse(n);return;case"system":this.systemQueue.put(n.data);return;default:this.outputQueue.put(n);return;case"sync-request":{let r=n.data;k(this,Ln).set(r.data.uuid,r.data.msg);return}case"request":throw new pt("Can't send messages of type 'request' from a worker.Use service worker fetch request instead.")}}),console.warn("The ServiceWorker communication channel is deprecated and will be removed in a future version of webR. Consider using the PostMessage channel instead. If blocking input is required (for example, `browser()`) the SharedArrayBuffer channel should be used. See https://docs.r-wasm.org/webr/latest/serving.html for further information.");let e=t=>{Je(this,Aa,Xf).call(this,t),this.close=()=>{t.terminate(),this.putClosedMessage()},Je(this,Ra,Bf).call(this,`${i.serviceWorkerUrl}webr-serviceworker.js`).then(n=>{let r={type:"init",data:{config:i,channelType:Qt.ServiceWorker,clientId:n,location:window.location.href}};t.postMessage(r)})};if(Ya(i.serviceWorkerUrl))Ga(`${i.serviceWorkerUrl}webr-worker.js`,t=>e(t));else{let t=new Worker(`${i.serviceWorkerUrl}webr-worker.js`);e(t)}({resolve:this.resolve,promise:this.initialised}=ms())}activeRegistration(){var i;if(!((i=k(this,Ii))!=null&&i.active))throw new pt("Attempted to obtain a non-existent active registration.");return k(this,Ii).active}interrupt(){me(this,qn,!0)}};Ln=new WeakMap,Ii=new WeakMap,qn=new WeakMap,Ra=new WeakSet,Bf=async function(i){me(this,Ii,await navigator.serviceWorker.register(i)),await navigator.serviceWorker.ready,window.addEventListener("beforeunload",()=>{var t;(t=k(this,Ii))==null||t.unregister()});let e=await new Promise(t=>{navigator.serviceWorker.addEventListener("message",function n(r){r.data.type==="registration-successful"&&(navigator.serviceWorker.removeEventListener("message",n),t(r.data.clientId))}),this.activeRegistration().postMessage({type:"register-client-main"})});return navigator.serviceWorker.addEventListener("message",t=>{Je(this,Ea,ff).call(this,t)}),e},Ea=new WeakSet,ff=async function(i){if(i.data.type==="request"){let e=i.data.data,t=k(this,Ln).get(e);if(!t)throw new pt("Request not found during service worker XHR request");switch(k(this,Ln).delete(e),t.type){case"read":{let n=await this.inputQueue.get();this.activeRegistration().postMessage({type:"wasm-webr-fetch-response",uuid:e,response:Pa(e,n)});break}case"interrupt":{let n=k(this,qn);this.activeRegistration().postMessage({type:"wasm-webr-fetch-response",uuid:e,response:Pa(e,n)}),this.inputQueue.reset(),me(this,qn,!1);break}default:throw new pt(`Unsupported request type '${t.type}'.`)}return}},Aa=new WeakSet,Xf=function(i){Ie?i.on("message",e=>{k(this,es).call(this,i,e)}):i.onmessage=e=>k(this,es).call(this,i,e.data)},es=new WeakMap;var l0,h0,c0,f0,u0,d0;l0=new WeakMap,h0=new WeakMap,c0=new WeakMap,f0=new WeakMap,u0=new WeakMap,d0=new WeakMap;Ie&&(globalThis.Worker=Bi("worker_threads").Worker);var Vn,Qa,Wf,ts,uf=class extends Za{constructor(i){super(),L(this,Qa),this.close=()=>{},L(this,Vn,void 0),L(this,ts,async(t,n)=>{if(!(!n||!n.type))switch(n.type){case"resolve":this.resolve();return;case"response":this.resolveResponse(n);return;case"system":this.systemQueue.put(n.data);return;default:this.outputQueue.put(n);return;case"request":{let r=n,s=r.data.msg;switch(s.type){case"read":{let o=await this.inputQueue.get();if(k(this,Vn)){let a=Pa(r.data.uuid,o);k(this,Vn).postMessage(a)}break}default:throw new pt(`Unsupported request type '${s.type}'.`)}return}case"sync-request":throw new pt("Can't send messages of type 'sync-request' in PostMessage mode. Use 'request' instead.")}});let e=t=>{me(this,Vn,t),Je(this,Qa,Wf).call(this,t),this.close=()=>t.terminate();let n={type:"init",data:{config:i,channelType:Qt.PostMessage}};t.postMessage(n)};if(Ya(i.baseUrl))Ga(`${i.baseUrl}webr-worker.js`,t=>e(t));else{let t=new Worker(`${i.baseUrl}webr-worker.js`);e(t)}({resolve:this.resolve,promise:this.initialised}=ms())}interrupt(){console.error("Interrupting R execution is not available when using the PostMessage channel")}};Vn=new WeakMap,Qa=new WeakSet,Wf=function(i){Ie?i.on("message",e=>{k(this,ts).call(this,i,e)}):i.onmessage=e=>k(this,ts).call(this,i,e.data)},ts=new WeakMap;var p0,m0,g0,O0,y0;p0=new WeakMap,m0=new WeakMap,g0=new WeakMap,O0=new WeakMap,y0=new WeakMap;var Qt={Automatic:0,SharedArrayBuffer:1,ServiceWorker:2,PostMessage:3};function b0(i){switch(i.channelType){case Qt.SharedArrayBuffer:return new cf(i);case Qt.ServiceWorker:return new a0(i);case Qt.PostMessage:return new uf(i);case Qt.Automatic:default:return typeof SharedArrayBuffer<"u"?new cf(i):new uf(i)}}var w0=Ie?__dirname+"/":"https://webr.r-wasm.org/v0.4.0/",v0="https://repo.r-wasm.org",If="0.4.0";function ee(i){return!!i&&(typeof i=="object"||typeof i=="function")&&"payloadType"in i&&Lf(i._payload)}function Re(i){return ee(i)&&i._payload.obj.type==="null"}function x0(i){return ee(i)&&i._payload.obj.type==="symbol"}function k0(i){return ee(i)&&i._payload.obj.type==="pairlist"}function S0(i){return ee(i)&&i._payload.obj.type==="environment"}function T0(i){return ee(i)&&i._payload.obj.type==="logical"}function P0(i){return ee(i)&&i._payload.obj.type==="integer"}function C0(i){return ee(i)&&i._payload.obj.type==="double"}function R0(i){return ee(i)&&i._payload.obj.type==="complex"}function Ui(i){return ee(i)&&i._payload.obj.type==="character"}function ot(i){return ee(i)&&i._payload.obj.type==="list"}function Ja(i){return ee(i)&&i._payload.obj.type==="raw"}function gs(i){return ee(i)&&i._payload.obj.type==="call"}function Os(i){var e;return!!(ee(i)&&(e=i._payload.obj.methods)!=null&&e.includes("exec"))}function E0(){}function A0(i,e){return async function*(){let t={type:"callRObjectMethod",data:{payload:e._payload,prop:"getPropertyValue",args:[{payloadType:"raw",obj:"length"}],shelter:void 0}},n=await i.request(t);if(typeof n.obj!="number")throw new di("Cannot iterate over object, unexpected type for length property.");for(let r=1;r<=n.obj;r++)yield e.get(r)}}function Nf(i,e,t){return async(...n)=>{let r=n.map(a=>ee(a)?a._payload:{obj:Ut(a,ee,l=>l._payload),payloadType:"raw"}),s={type:"callRObjectMethod",data:{payload:t,prop:e,args:r}},o=await i.request(s);switch(o.payloadType){case"ptr":return fi(i,o);case"raw":return Ut(o,Lf,(a,l)=>fi(l,a),i).obj}}}async function Q0(i,e,t,...n){let r={type:"newRObject",data:{objType:e,args:Ut(n,ee,o=>o._payload),shelter:t}},s=await i.request(r);switch(s.payloadType){case"raw":throw new Bn("Unexpected raw payload type returned from newRObject");case"ptr":return fi(i,s)}}function fi(i,e){var t;let n=new Proxy((t=e.obj.methods)!=null&&t.includes("exec")?Object.assign(E0,{...e}):e,{get:(r,s)=>{var o;if(s==="_payload")return e;if(s===Symbol.asyncIterator)return A0(i,n);if((o=e.obj.methods)!=null&&o.includes(s.toString()))return Nf(i,s.toString(),e)},apply:async(r,s,o)=>{let a=await fi(i,e).exec(...o);return Os(a)?a:a.toJs()}});return n}function Ve(i,e,t){return new Proxy(z,{construct:(n,r)=>Q0(i,t,e,...r),get:(n,r)=>Nf(i,r.toString())})}var ss,os,as,ls,hs,Ma,_a,Da,$a,Va,La,jf,M0=class{constructor(i={},e={REnv:{R_HOME:"/usr/lib/R",FONTCONFIG_PATH:"/etc/fonts",R_ENABLE_JIT:"0"}}){L(this,La),L(this,ss,void 0),L(this,os,void 0),L(this,as,void 0),L(this,ls,void 0),L(this,hs,void 0),L(this,Ma,t=>{console.log(t)}),L(this,_a,t=>{console.error(t)}),L(this,Da,t=>{let n=prompt(t);n&&this.stdin(`${n} +`)}),L(this,$a,t=>{if(Ie)throw new Error("Plotting with HTML canvas is not yet supported under Node");this.canvas.getContext("2d").drawImage(t,0,0)}),L(this,Va,()=>{if(Ie)throw new Error("Plotting with HTML canvas is not yet supported under Node");this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}),this.webR=new Uf(e),Ie||(this.canvas=document.createElement("canvas"),this.canvas.setAttribute("width","1008"),this.canvas.setAttribute("height","1008")),me(this,ss,i.stdout||k(this,Ma)),me(this,os,i.stderr||k(this,_a)),me(this,as,i.prompt||k(this,Da)),me(this,ls,i.canvasImage||k(this,$a)),me(this,hs,i.canvasNewPage||k(this,Va)),this.webR.evalRVoid("options(device=webr::canvas)")}stdin(i){this.webR.writeConsole(i)}interrupt(){this.webR.interrupt()}run(){Je(this,La,jf).call(this)}};ss=new WeakMap,os=new WeakMap,as=new WeakMap,ls=new WeakMap,hs=new WeakMap,Ma=new WeakMap,_a=new WeakMap,Da=new WeakMap,$a=new WeakMap,Va=new WeakMap,La=new WeakSet,jf=async function(){for(;;){let i=await this.webR.read();switch(i.type){case"stdout":k(this,ss).call(this,i.data);break;case"stderr":k(this,os).call(this,i.data);break;case"prompt":k(this,as).call(this,i.data);break;case"canvas":i.data.event==="canvasImage"?k(this,ls).call(this,i.data.image):i.data.event==="canvasNewPage"&&k(this,hs).call(this);break;case"closed":return;default:console.warn(`Unhandled output type for webR Console: ${i.type}.`)}}};var _0={FONTCONFIG_PATH:"/etc/fonts",R_HOME:"/usr/lib/R",R_ENABLE_JIT:"0",WEBR:"1",WEBR_VERSION:If},df={RArgs:[],REnv:_0,baseUrl:w0,serviceWorkerUrl:"",repoUrl:v0,homedir:"/home/web_user",interactive:!0,channelType:Qt.Automatic,createLazyFilesystem:!0},ne,is,qa,zf,Uf=class{constructor(i={}){L(this,qa),L(this,ne,void 0),L(this,is,void 0),this.version=If,this.FS={lookupPath:async t=>{let n={type:"lookupPath",data:{path:t}};return(await k(this,ne).request(n)).obj},mkdir:async t=>{let n={type:"mkdir",data:{path:t}};return(await k(this,ne).request(n)).obj},mount:async(t,n,r)=>{let s={type:"mount",data:{type:t,options:n,mountpoint:r}};await k(this,ne).request(s)},syncfs:async t=>{let n={type:"syncfs",data:{populate:t}};await k(this,ne).request(n)},readFile:async(t,n)=>{let r={type:"readFile",data:{path:t,flags:n}};return(await k(this,ne).request(r)).obj},rmdir:async t=>{let n={type:"rmdir",data:{path:t}};await k(this,ne).request(n)},writeFile:async(t,n,r)=>{let s={type:"writeFile",data:{path:t,data:n,flags:r}};await k(this,ne).request(s)},unlink:async t=>{let n={type:"unlink",data:{path:t}};await k(this,ne).request(n)},unmount:async t=>{let n={type:"unmount",data:{path:t}};await k(this,ne).request(n)}};let e={...df,...i,REnv:{...df.REnv,...i.REnv}};me(this,ne,b0(e)),this.objs={},this.Shelter=D0(k(this,ne)),me(this,is,k(this,ne).initialised.then(async()=>{this.globalShelter=await new this.Shelter,this.RObject=this.globalShelter.RObject,this.RLogical=this.globalShelter.RLogical,this.RInteger=this.globalShelter.RInteger,this.RDouble=this.globalShelter.RDouble,this.RComplex=this.globalShelter.RComplex,this.RCharacter=this.globalShelter.RCharacter,this.RRaw=this.globalShelter.RRaw,this.RList=this.globalShelter.RList,this.RDataFrame=this.globalShelter.RDataFrame,this.RPairlist=this.globalShelter.RPairlist,this.REnvironment=this.globalShelter.REnvironment,this.RSymbol=this.globalShelter.RSymbol,this.RString=this.globalShelter.RString,this.RCall=this.globalShelter.RCall,this.objs={baseEnv:await this.RObject.getPersistentObject("baseEnv"),globalEnv:await this.RObject.getPersistentObject("globalEnv"),null:await this.RObject.getPersistentObject("null"),true:await this.RObject.getPersistentObject("true"),false:await this.RObject.getPersistentObject("false"),na:await this.RObject.getPersistentObject("na")},Je(this,qa,zf).call(this)}))}async init(){return k(this,is)}close(){k(this,ne).close()}async read(){return await k(this,ne).read()}async flush(){return await k(this,ne).flush()}write(i){k(this,ne).write(i)}writeConsole(i){this.write({type:"stdin",data:i+` +`})}interrupt(){k(this,ne).interrupt()}async installPackages(i,e){let t=Object.assign({quiet:!1,mount:!0},e),n={type:"installPackages",data:{name:i,options:t}};await k(this,ne).request(n)}async destroy(i){await this.globalShelter.destroy(i)}async evalR(i,e){return this.globalShelter.evalR(i,e)}async evalRVoid(i,e){return this.evalRRaw(i,"void",e)}async evalRBoolean(i,e){return this.evalRRaw(i,"boolean",e)}async evalRNumber(i,e){return this.evalRRaw(i,"number",e)}async evalRString(i,e){return this.evalRRaw(i,"string",e)}async evalRRaw(i,e,t={}){let n=Ut(t,ee,o=>o._payload),r={type:"evalRRaw",data:{code:i,options:n,outputType:e}},s=await k(this,ne).request(r);switch(s.payloadType){case"raw":return s.obj;case"ptr":throw new Bn("Unexpected ptr payload type returned from evalRVoid")}}async invokeWasmFunction(i,...e){let t={type:"invokeWasmFunction",data:{ptr:i,args:e}};return(await k(this,ne).request(t)).obj}};ne=new WeakMap,is=new WeakMap,qa=new WeakSet,zf=async function(){for(;;){let i=await k(this,ne).readSystem();switch(i.type){case"setTimeoutWasm":setTimeout((e,t)=>{this.invokeWasmFunction(e,...t)},i.data.delay,i.data.ptr,i.data.args);break;case"console.log":console.log(i.data);break;case"console.warn":console.warn(i.data);break;case"console.error":console.error(i.data);break;default:throw new di("Unknown system message type `"+i.type+"`")}}};var se,Z,ns,Ba=class{constructor(i){L(this,se,""),L(this,Z,void 0),L(this,ns,!1),me(this,Z,i)}async init(){if(k(this,ns))return;let i={type:"newShelter"},e=await k(this,Z).request(i);me(this,se,e.obj),this.RObject=Ve(k(this,Z),k(this,se),"object"),this.RLogical=Ve(k(this,Z),k(this,se),"logical"),this.RInteger=Ve(k(this,Z),k(this,se),"integer"),this.RDouble=Ve(k(this,Z),k(this,se),"double"),this.RComplex=Ve(k(this,Z),k(this,se),"complex"),this.RCharacter=Ve(k(this,Z),k(this,se),"character"),this.RRaw=Ve(k(this,Z),k(this,se),"raw"),this.RList=Ve(k(this,Z),k(this,se),"list"),this.RDataFrame=Ve(k(this,Z),k(this,se),"dataframe"),this.RPairlist=Ve(k(this,Z),k(this,se),"pairlist"),this.REnvironment=Ve(k(this,Z),k(this,se),"environment"),this.RSymbol=Ve(k(this,Z),k(this,se),"symbol"),this.RString=Ve(k(this,Z),k(this,se),"string"),this.RCall=Ve(k(this,Z),k(this,se),"call"),me(this,ns,!0)}async purge(){let i={type:"shelterPurge",data:k(this,se)};await k(this,Z).request(i)}async destroy(i){let e={type:"shelterDestroy",data:{id:k(this,se),obj:i._payload}};await k(this,Z).request(e)}async size(){let i={type:"shelterSize",data:k(this,se)};return(await k(this,Z).request(i)).obj}async evalR(i,e={}){let t=Ut(e,ee,s=>s._payload),n={type:"evalR",data:{code:i,options:t,shelter:k(this,se)}},r=await k(this,Z).request(n);switch(r.payloadType){case"raw":throw new Bn("Unexpected payload type returned from evalR");default:return fi(k(this,Z),r)}}async captureR(i,e={}){let t=Ut(e,ee,s=>s._payload),n={type:"captureR",data:{code:i,options:t,shelter:k(this,se)}},r=await k(this,Z).request(n);switch(r.payloadType){case"ptr":throw new Bn("Unexpected payload type returned from evalR");case"raw":{let s=r.obj,o=fi(k(this,Z),s.result),a=s.output,l=s.images;for(let h=0;h{let e=new Ba(i);return await e.init(),e}})}var Hf=Symbol("Comlink.proxy"),il=Symbol("Comlink.endpoint"),$0=Symbol("Comlink.releaseProxy"),el=Symbol("Comlink.finalizer"),bs=Symbol("Comlink.thrown"),Gf=i=>typeof i=="object"&&i!==null||typeof i=="function",V0={canHandle:i=>Gf(i)&&i[Hf],serialize(i){let{port1:e,port2:t}=new MessageChannel;return ks(i,e),[t,[t]]},deserialize(i){return i.start(),Wn(i)}},L0={canHandle:i=>Gf(i)&&bs in i,serialize({value:i}){let e;return i instanceof Error?e={isError:!0,value:{message:i.message,name:i.name,stack:i.stack}}:e={isError:!1,value:i},[e,[]]},deserialize(i){throw i.isError?Object.assign(new Error(i.value.message),i.value):i.value}},gi=new Map([["proxy",V0],["throw",L0]]);function q0(i,e){for(let t of i)if(e===t||t==="*"||t instanceof RegExp&&t.test(e))return!0;return!1}function ks(i,e=globalThis,t=["*"]){e.addEventListener("message",function n(r){if(!r||!r.data)return;if(!q0(t,r.origin)){console.warn(`Invalid origin '${r.origin}' for comlink proxy`);return}let{id:s,type:o,path:a}=Object.assign({path:[]},r.data),l=(r.data.argumentList||[]).map(mi),h;try{let c=a.slice(0,-1).reduce((u,d)=>u[d],i),f=a.reduce((u,d)=>u[d],i);switch(o){case"GET":h=f;break;case"SET":c[a.slice(-1)[0]]=mi(r.data.value),h=!0;break;case"APPLY":h=f.apply(c,l);break;case"CONSTRUCT":{let u=new f(...l);h=j0(u)}break;case"ENDPOINT":{let{port1:u,port2:d}=new MessageChannel;ks(i,d),h=N0(u,[u])}break;case"RELEASE":h=void 0;break;default:return}}catch(c){h={value:c,[bs]:0}}Promise.resolve(h).catch(c=>({value:c,[bs]:0})).then(c=>{let[f,u]=xs(c);e.postMessage(Object.assign(Object.assign({},f),{id:s}),u),o==="RELEASE"&&(e.removeEventListener("message",n),Yf(e),el in i&&typeof i[el]=="function"&&i[el]())}).catch(c=>{let[f,u]=xs({value:new TypeError("Unserializable return value"),[bs]:0});e.postMessage(Object.assign(Object.assign({},f),{id:s}),u)})}),e.start&&e.start()}function B0(i){return i.constructor.name==="MessagePort"}function Yf(i){B0(i)&&i.close()}function Wn(i,e){return tl(i,[],e)}function ys(i){if(i)throw new Error("Proxy has been released and is not useable")}function Zf(i){return Fi(i,{type:"RELEASE"}).then(()=>{Yf(i)})}var ws=new WeakMap,vs="FinalizationRegistry"in globalThis&&new FinalizationRegistry(i=>{let e=(ws.get(i)||0)-1;ws.set(i,e),e===0&&Zf(i)});function X0(i,e){let t=(ws.get(e)||0)+1;ws.set(e,t),vs&&vs.register(i,e,i)}function W0(i){vs&&vs.unregister(i)}function tl(i,e=[],t=function(){}){let n=!1,r=new Proxy(t,{get(s,o){if(ys(n),o===$0)return()=>{W0(r),Zf(i),n=!0};if(o==="then"){if(e.length===0)return{then:()=>r};let a=Fi(i,{type:"GET",path:e.map(l=>l.toString())}).then(mi);return a.then.bind(a)}return tl(i,[...e,o])},set(s,o,a){ys(n);let[l,h]=xs(a);return Fi(i,{type:"SET",path:[...e,o].map(c=>c.toString()),value:l},h).then(mi)},apply(s,o,a){ys(n);let l=e[e.length-1];if(l===il)return Fi(i,{type:"ENDPOINT"}).then(mi);if(l==="bind")return tl(i,e.slice(0,-1));let[h,c]=Ff(a);return Fi(i,{type:"APPLY",path:e.map(f=>f.toString()),argumentList:h},c).then(mi)},construct(s,o){ys(n);let[a,l]=Ff(o);return Fi(i,{type:"CONSTRUCT",path:e.map(h=>h.toString()),argumentList:a},l).then(mi)}});return X0(r,i),r}function I0(i){return Array.prototype.concat.apply([],i)}function Ff(i){let e=i.map(xs);return[e.map(t=>t[0]),I0(e.map(t=>t[1]))]}var Jf=new WeakMap;function N0(i,e){return Jf.set(i,e),i}function j0(i){return Object.assign(i,{[Hf]:!0})}function xs(i){for(let[e,t]of gi)if(t.canHandle(i)){let[n,r]=t.serialize(i);return[{type:"HANDLER",name:e,value:n},r]}return[{type:"RAW",value:i},Jf.get(i)||[]]}function mi(i){switch(i.type){case"HANDLER":return gi.get(i.name).deserialize(i.value);case"RAW":return i.value}}function Fi(i,e,t){return new Promise(n=>{let r=z0();i.addEventListener("message",function s(o){!o.data||!o.data.id||o.data.id!==r||(i.removeEventListener("message",s),n(o.data))}),i.start&&i.start(),i.postMessage(Object.assign({id:r},e),t)})}function z0(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Hi=[],Ke=class{constructor(e){this.isRunning=!1;this.isDestroyed=!1;Hi.push(this),e?this.callbacks=e:this.callbacks={busyCallback:()=>{},idleCallback:()=>{},runningCallback:()=>{},finishedCallback:()=>{}}}running(){this.isRunning=!0,Hi.forEach(e=>e.callbacks.busyCallback()),this.callbacks.runningCallback()}finished(){this.isRunning=!1,this.callbacks.finishedCallback(),this.status().busy||Hi.forEach(e=>e.callbacks.idleCallback())}status(){let e=this.isRunning,t=this.isDestroyed,n=Hi.some(r=>r.isRunning);return{running:e,busy:n,destroyed:t}}destroy(){this.isDestroyed=!0;let e=Hi.indexOf(this);Hi.splice(e,1)}};var W=class i{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=en(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),Yi.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=en(this,e,t);let n=[];return this.decompose(e,t,n,0),Yi.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new bi(this),s=new bi(e);for(let o=t,a=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new bi(this,e)}iterRange(e,t=this.length){return new Cs(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Rs(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?i.empty:e.length<=32?new Ne(e):Yi.from(Ne.split(e,[]))}},Ne=class i extends W{constructor(e,t=U0(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let s=0;;s++){let o=this.text[s],a=r+o.length;if((t?n:a)>=e)return new rl(r,a,n,o);r=a+1,n++}}decompose(e,t,n,r){let s=e<=0&&t>=this.length?this:new i(eu(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=n.pop(),a=Ps(s.text,o.text.slice(),0,s.length);if(a.length<=32)n.push(new i(a,o.length+s.length));else{let l=a.length>>1;n.push(new i(a.slice(0,l)),new i(a.slice(l)))}}else n.push(s)}replace(e,t,n){if(!(n instanceof i))return super.replace(e,t,n);[e,t]=en(this,e,t);let r=Ps(this.text,Ps(n.text,eu(this.text,0,e)),t),s=this.length+n.length-(t-e);return r.length<=32?new i(r,s):Yi.from(i.split(r,[]),s)}sliceString(e,t=this.length,n=` +`){[e,t]=en(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=n),es&&(r+=a.slice(Math.max(0,e-s),t-s)),s=l+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let n=[],r=-1;for(let s of e)n.push(s),r+=s.length+1,n.length==32&&(t.push(new i(n,r)),n=[],r=-1);return r>-1&&t.push(new i(n,r)),t}},Yi=class i extends W{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let n of e)this.lines+=n.lines}lineInner(e,t,n,r){for(let s=0;;s++){let o=this.children[s],a=r+o.length,l=n+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,n,r);r=a+1,n=l+1}}decompose(e,t,n,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!h?n.push(a):a.decompose(e-o,t-o,n,h)}o=l+1}}replace(e,t,n){if([e,t]=en(this,e,t),n.lines=s&&t<=a){let l=o.replace(e-s,t-s,n),h=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>h>>6){let c=this.children.slice();return c[r]=l,new i(c,this.length-(t-e)+n.length)}return super.replace(s,a,l)}s=a+1}return super.replace(e,t,n)}sliceString(e,t=this.length,n=` +`){[e,t]=en(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=n),eo&&(r+=a.sliceString(e-o,t-o,n)),o=l+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof i))return 0;let n=0,[r,s,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==a)return n;let l=this.children[r],h=e.children[s];if(l!=h)return n+l.scanIdentical(h,t);n+=l.length+1}}static from(e,t=e.reduce((n,r)=>n+r.length+1,-1)){let n=0;for(let d of e)n+=d.lines;if(n<32){let d=[];for(let m of e)m.flatten(d);return new Ne(d,t)}let r=Math.max(32,n>>5),s=r<<1,o=r>>1,a=[],l=0,h=-1,c=[];function f(d){let m;if(d.lines>s&&d instanceof i)for(let p of d.children)f(p);else d.lines>o&&(l>o||!l)?(u(),a.push(d)):d instanceof Ne&&l&&(m=c[c.length-1])instanceof Ne&&d.lines+m.lines<=32?(l+=d.lines,h+=d.length+1,c[c.length-1]=new Ne(m.text.concat(d.text),m.length+1+d.length)):(l+d.lines>r&&u(),l+=d.lines,h+=d.length+1,c.push(d))}function u(){l!=0&&(a.push(c.length==1?c[0]:i.from(c,h)),h=-1,l=c.length=0)}for(let d of e)f(d);return u(),a.length==1?a[0]:new i(a,t)}};W.empty=new Ne([""],0);function U0(i){let e=-1;for(let t of i)e+=t.length+1;return e}function Ps(i,e,t=0,n=1e9){for(let r=0,s=0,o=!0;s=t&&(l>n&&(a=a.slice(0,n-r)),r0?1:(e instanceof Ne?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,r=this.nodes[n],s=this.offsets[n],o=s>>1,a=r instanceof Ne?r.text.length:r.children.length;if(o==(t>0?a:0)){if(n==0)return this.done=!0,this.value="",this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(r instanceof Ne){let l=r.text[o+(t<0?-1:0)];if(this.offsets[n]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=r.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof Ne?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Cs=class{constructor(e,t,n){this.value="",this.done=!1,this.cursor=new bi(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=n?r:t<0?r.slice(r.length-n):r.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},Rs=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:n,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):n?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(W.prototype[Symbol.iterator]=function(){return this.iter()},bi.prototype[Symbol.iterator]=Cs.prototype[Symbol.iterator]=Rs.prototype[Symbol.iterator]=function(){return this});var rl=class{constructor(e,t,n,r){this.from=e,this.to=t,this.number=n,this.text=r}get length(){return this.to-this.from}};function en(i,e,t){return e=Math.max(0,Math.min(i.length,e)),[e,Math.max(e,Math.min(i.length,t))]}var Zi="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(i=>i?parseInt(i,36):1);for(let i=1;ii)return Zi[e-1]<=i;return!1}function tu(i){return i>=127462&&i<=127487}var iu=8205;function ue(i,e,t=!0,n=!0){return(t?lu:H0)(i,e,n)}function lu(i,e,t){if(e==i.length)return e;e&&hu(i.charCodeAt(e))&&cu(i.charCodeAt(e-1))&&e--;let n=ce(i,e);for(e+=Ee(n);e=0&&tu(ce(i,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function H0(i,e,t){for(;e>0;){let n=lu(i,e-2,t);if(n=56320&&i<57344}function cu(i){return i>=55296&&i<56320}function ce(i,e){let t=i.charCodeAt(e);if(!cu(t)||e+1==i.length)return t;let n=i.charCodeAt(e+1);return hu(n)?(t-55296<<10)+(n-56320)+65536:t}function Fn(i){return i<=65535?String.fromCharCode(i):(i-=65536,String.fromCharCode((i>>10)+55296,(i&1023)+56320))}function Ee(i){return i<65536?1:2}var sl=/\r\n?|\n/,ge=function(i){return i[i.Simple=0]="Simple",i[i.TrackDel=1]="TrackDel",i[i.TrackBefore=2]="TrackBefore",i[i.TrackAfter=3]="TrackAfter",i}(ge||(ge={})),_t=class i{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=a}else{if(n!=ge.Simple&&h>=e&&(n==ge.TrackDel&&re||n==ge.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!a)return e==r||t<0?s:s+l;s+=l}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let n=0,r=0;n=0&&r<=t&&a>=e)return rt?"cover":!0;r=a}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new i(e)}static create(e){return new i(e)}},Ae=class i extends _t{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return ol(this,(t,n,r,s,o)=>e=e.replace(r,r+(n-t),o),!1),e}mapDesc(e,t=!1){return al(this,e,t,!0)}invert(e){let t=this.sections.slice(),n=[];for(let r=0,s=0;r=0){t[r]=a,t[r+1]=o;let l=r>>1;for(;n.length0&&Ft(n,t,s.text),s.forward(c),a+=c}let h=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,n){let r=[],s=[],o=0,a=null;function l(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let m=d?typeof d=="string"?W.of(d.split(n||sl)):d:W.empty,p=m.length;if(f==u&&p==0)return;fo&&Se(r,f-o,-1),Se(r,u-f,p),Ft(s,r,m),o=u}}return h(e),l(!a),a}static empty(e){return new i(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],n=[];for(let r=0;ra&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;n.length=0&&t<=0&&t==i[r+1]?i[r]+=e:e==0&&i[r]==0?i[r+1]+=t:n?(i[r]+=e,i[r+1]+=t):i.push(e,t)}function Ft(i,e,t){if(t.length==0)return;let n=e.length-2>>1;if(n>1])),!(t||o==i.sections.length||i.sections[o+1]<0);)a=i.sections[o++],l=i.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function al(i,e,t,n=!1){let r=[],s=n?[]:null,o=new wi(i),a=new wi(e);for(let l=-1;;)if(o.ins==-1&&a.ins==-1){let h=Math.min(o.len,a.len);Se(r,h,-1),o.forward(h),a.forward(h)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let h=0,c=o.len;for(;c;)if(a.ins==-1){let f=Math.min(c,a.len);h+=f,c-=f,a.forward(f)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||n.length>h),s.forward2(l),o.forward(l)}}}}var wi=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?W.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?W.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},Gi=class i{constructor(e,t,n){this.from=e,this.to=t,this.flags=n}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let n,r;return this.empty?n=r=e.mapPos(this.from,t):(n=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),n==this.from&&r==this.to?this:new i(n,r,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return S.range(e,t);let n=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return S.range(this.anchor,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return S.range(e.anchor,e.head)}static create(e,t,n){return new i(e,t,n)}},S=class i{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:i.create(this.ranges.map(n=>n.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;ne.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new i(e.ranges.map(t=>Gi.fromJSON(t)),e.main)}static single(e,t=e){return new i([i.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let n=0,r=0;re?8:0)|s)}static normalized(e,t=0){let n=e[t];e.sort((r,s)=>r.from-s.from),t=e.indexOf(n);for(let r=1;rs.head?i.range(l,a):i.range(a,l))}}return new i(e,t)}};function uu(i,e){for(let t of i.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var Ol=0,A=class i{constructor(e,t,n,r,s){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=r,this.id=Ol++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new i(e.combine||(t=>t),e.compareInput||((t,n)=>t===n),e.compare||(e.combine?(t,n)=>t===n:yl),!!e.static,e.enables)}of(e){return new Ji([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ji(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ji(e,this,2,t)}from(e,t){return t||(t=n=>n),this.compute([e],n=>t(n.field(e)))}};function yl(i,e){return i==e||i.length==e.length&&i.every((t,n)=>t===e[n])}var Ji=class{constructor(e,t,n,r){this.dependencies=e,this.facet=t,this.type=n,this.value=r,this.id=Ol++}dynamicSlot(e){var t;let n=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,a=this.type==2,l=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?l=!0:f=="selection"?h=!0:((t=e[f.id])!==null&&t!==void 0?t:1)&1||c.push(e[f.id]);return{create(f){return f.values[o]=n(f),1},update(f,u){if(l&&u.docChanged||h&&(u.docChanged||u.selection)||ll(f,c)){let d=n(f);if(a?!nu(d,f.values[o],r):!r(d,f.values[o]))return f.values[o]=d,1}return 0},reconfigure:(f,u)=>{let d,m=u.config.address[s];if(m!=null){let p=Qs(u,m);if(this.dependencies.every(g=>g instanceof A?u.facet(g)===f.facet(g):g instanceof te?u.field(g,!1)==f.field(g,!1):!0)||(a?nu(d=n(f),p,r):r(d=n(f),p)))return f.values[o]=p,0}else d=n(f);return f.values[o]=d,1}}}};function nu(i,e,t){if(i.length!=e.length)return!1;for(let n=0;ni[l.id]),r=t.map(l=>l.type),s=n.filter(l=>!(l&1)),o=i[e.id]>>1;function a(l){let h=[];for(let c=0;cn===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(ru).find(n=>n.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:n=>(n.values[t]=this.create(n),1),update:(n,r)=>{let s=n.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(n.values[t]=o,1)},reconfigure:(n,r)=>r.config.address[this.id]!=null?(n.values[t]=r.field(this),0):(n.values[t]=this.create(n),1)}}init(e){return[this,ru.of({field:this,create:e})]}get extension(){return this}},Oi={lowest:4,low:3,default:2,high:1,highest:0};function In(i){return e=>new Es(e,i)}var Qe={highest:In(Oi.highest),high:In(Oi.high),default:In(Oi.default),low:In(Oi.low),lowest:In(Oi.lowest)},Es=class{constructor(e,t){this.inner=e,this.prec=t}},Dt=class i{of(e){return new jn(this,e)}reconfigure(e){return i.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},jn=class{constructor(e,t){this.compartment=e,this.inner=t}},As=class i{constructor(e,t,n,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,n){let r=[],s=Object.create(null),o=new Map;for(let u of Y0(e,t,o))u instanceof te?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let a=Object.create(null),l=[],h=[];for(let u of r)a[u.id]=h.length<<1,h.push(d=>u.slot(d));let c=n?.config.facets;for(let u in s){let d=s[u],m=d[0].facet,p=c&&c[u]||[];if(d.every(g=>g.type==0))if(a[m.id]=l.length<<1|1,yl(p,d))l.push(n.facet(m));else{let g=m.combine(d.map(O=>O.value));l.push(n&&m.compare(g,n.facet(m))?n.facet(m):g)}else{for(let g of d)g.type==0?(a[g.id]=l.length<<1|1,l.push(g.value)):(a[g.id]=h.length<<1,h.push(O=>g.dynamicSlot(O)));a[m.id]=h.length<<1,h.push(g=>G0(g,m,d))}}let f=h.map(u=>u(a));return new i(e,o,f,a,l,s)}};function Y0(i,e,t){let n=[[],[],[],[],[]],r=new Map;function s(o,a){let l=r.get(o);if(l!=null){if(l<=a)return;let h=n[l].indexOf(o);h>-1&&n[l].splice(h,1),o instanceof jn&&t.delete(o.compartment)}if(r.set(o,a),Array.isArray(o))for(let h of o)s(h,a);else if(o instanceof jn){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,a)}else if(o instanceof Es)s(o.inner,o.prec);else if(o instanceof te)n[a].push(o),o.provides&&s(o.provides,a);else if(o instanceof Ji)n[a].push(o),o.facet.extensions&&s(o.facet.extensions,Oi.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,a)}}return s(i,Oi.default),n.reduce((o,a)=>o.concat(a))}function Nn(i,e){if(e&1)return 2;let t=e>>1,n=i.status[t];if(n==4)throw new Error("Cyclic dependency between fields and/or facets");if(n&2)return n;i.status[t]=4;let r=i.computeSlot(i,i.config.dynamicSlots[t]);return i.status[t]=2|r}function Qs(i,e){return e&1?i.config.staticValues[e>>1]:i.values[e>>1]}var du=A.define(),hl=A.define({combine:i=>i.some(e=>e),static:!0}),pu=A.define({combine:i=>i.length?i[0]:void 0,static:!0}),mu=A.define(),gu=A.define(),Ou=A.define(),yu=A.define({combine:i=>i.length?i[0]:!1}),Le=class{constructor(e,t){this.type=e,this.value=t}static define(){return new cl}},cl=class{of(e){return new Le(this,e)}},fl=class{constructor(e){this.map=e}of(e){return new _(this,e)}},_=class i{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new i(this.type,t)}is(e){return this.type==e}static define(e={}){return new fl(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let r of e){let s=r.map(t);s&&n.push(s)}return n}};_.reconfigure=_.define();_.appendConfig=_.define();var fe=class i{constructor(e,t,n,r,s,o){this.startState=e,this.changes=t,this.selection=n,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,n&&uu(n,t.newLength),s.some(a=>a.type==i.time)||(this.annotations=s.concat(i.time.of(Date.now())))}static create(e,t,n,r,s,o){return new i(e,t,n,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(i.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};fe.time=Le.define();fe.userEvent=Le.define();fe.addToHistory=Le.define();fe.remote=Le.define();function Z0(i,e){let t=[];for(let n=0,r=0;;){let s,o;if(n=i[n]))s=i[n++],o=i[n++];else if(r=0;r--){let s=n[r](i);s instanceof fe?i=s:Array.isArray(s)&&s.length==1&&s[0]instanceof fe?i=s[0]:i=wu(e,Ki(s),!1)}return i}function K0(i){let e=i.startState,t=e.facet(Ou),n=i;for(let r=t.length-1;r>=0;r--){let s=t[r](i);s&&Object.keys(s).length&&(n=bu(n,ul(e,s,i.changes.newLength),!0))}return n==i?i:fe.create(e,i.changes,i.selection,n.effects,n.annotations,n.scrollIntoView)}var ey=[];function Ki(i){return i==null?ey:Array.isArray(i)?i:[i]}var F=function(i){return i[i.Word=0]="Word",i[i.Space=1]="Space",i[i.Other=2]="Other",i}(F||(F={})),ty=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,dl;try{dl=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function iy(i){if(dl)return dl.test(i);for(let e=0;e"\x80"&&(t.toUpperCase()!=t.toLowerCase()||ty.test(t)))return!0}return!1}function ny(i){return e=>{if(!/\S/.test(e))return F.Space;if(iy(e))return F.Word;for(let t=0;t-1)return F.Word;return F.Other}}var N=class i{constructor(e,t,n,r,s,o){this.config=e,this.doc=t,this.selection=n,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let a=0;ar.set(h,l)),t=null),r.set(a.value.compartment,a.value.extension)):a.is(_.reconfigure)?(t=null,n=a.value):a.is(_.appendConfig)&&(t=null,n=Ki(n).concat(a.value));let s;t?s=e.startState.values.slice():(t=As.resolve(n,r,this),s=new i(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,h)=>h.reconfigure(l,this),null).values);let o=e.startState.facet(hl)?e.newSelection:e.newSelection.asSingle();new i(t,e.newDoc,o,s,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:S.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),r=this.changes(n.changes),s=[n.range],o=Ki(n.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return i.create({doc:e.doc,selection:S.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=As.resolve(e.extensions||[],new Map),n=e.doc instanceof W?e.doc:W.of((e.doc||"").split(t.staticFacet(i.lineSeparator)||sl)),r=e.selection?e.selection instanceof S?e.selection:S.single(e.selection.anchor,e.selection.head):S.single(0);return uu(r,n.length),t.staticFacet(hl)||(r=r.asSingle()),new i(t,n,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(i.tabSize)}get lineBreak(){return this.facet(i.lineSeparator)||` +`}get readOnly(){return this.facet(yu)}phrase(e,...t){for(let n of this.facet(i.phrases))if(Object.prototype.hasOwnProperty.call(n,e)){e=n[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(n,r)=>{if(r=="$")return"$";let s=+(r||1);return!s||s>t.length?n:t[s-1]})),e}languageDataAt(e,t,n=-1){let r=[];for(let s of this.facet(du))for(let o of s(this,t,n))Object.prototype.hasOwnProperty.call(o,e)&&r.push(o[e]);return r}charCategorizer(e){return ny(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:n,length:r}=this.doc.lineAt(e),s=this.charCategorizer(e),o=e-n,a=e-n;for(;o>0;){let l=ue(t,o,!1);if(s(t.slice(l,o))!=F.Word)break;o=l}for(;ai.length?i[0]:4});N.lineSeparator=pu;N.readOnly=yu;N.phrases=A.define({compare(i,e){let t=Object.keys(i),n=Object.keys(e);return t.length==n.length&&t.every(r=>i[r]==e[r])}});N.languageData=du;N.changeFilter=mu;N.transactionFilter=gu;N.transactionExtender=Ou;Dt.reconfigure=_.define();function Te(i,e,t={}){let n={};for(let r of i)for(let s of Object.keys(r)){let o=r[s],a=n[s];if(a===void 0)n[s]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,s))n[s]=t[s](a,o);else throw new Error("Config merge conflict for field "+s)}for(let r in e)n[r]===void 0&&(n[r]=e[r]);return n}var at=class{eq(e){return this==e}range(e,t=e){return zn.create(e,t,this)}};at.prototype.startSide=at.prototype.endSide=0;at.prototype.point=!1;at.prototype.mapMode=ge.TrackDel;var zn=class i{constructor(e,t,n){this.from=e,this.to=t,this.value=n}static create(e,t,n){return new i(e,t,n)}};function pl(i,e){return i.from-e.from||i.value.startSide-e.value.startSide}var ml=class i{constructor(e,t,n,r){this.from=e,this.to=t,this.value=n,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,n,r=0){let s=n?this.to:this.from;for(let o=r,a=s.length;;){if(o==a)return o;let l=o+a>>1,h=s[l]-e||(n?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return h>=0?o:a;h>=0?a=l:o=l+1}}between(e,t,n,r){for(let s=this.findIndex(t,-1e9,!0),o=this.findIndex(n,1e9,!1,s);sd||u==d&&h.startSide>0&&h.endSide<=0)continue;(d-u||h.endSide-h.startSide)<0||(o<0&&(o=u),h.point&&(a=Math.max(a,d-u)),n.push(h),r.push(u-o),s.push(d-o))}return{mapped:n.length?new i(r,s,n,a):null,pos:o}}},j=class i{constructor(e,t,n,r){this.chunkPos=e,this.chunk=t,this.nextLayer=n,this.maxPoint=r}static create(e,t,n,r){return new i(e,t,n,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:n=!1,filterFrom:r=0,filterTo:s=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(n&&(t=t.slice().sort(pl)),this.isEmpty)return t.length?i.of(t):this;let a=new Ms(this,null,-1).goto(0),l=0,h=[],c=new lt;for(;a.value||l=0){let f=t[l++];c.addInner(f.from,f.to,f.value)||h.push(f)}else a.rangeIndex==1&&a.chunkIndexthis.chunkEnd(a.chunkIndex)||sa.to||s=s&&e<=s+o.length&&o.between(s,e-s,t-s,n)===!1)return}this.nextLayer.between(e,t,n)}}iter(e=0){return Un.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Un.from(e).goto(t)}static compare(e,t,n,r,s=-1){let o=e.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=s),a=t.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=s),l=su(o,a,n),h=new yi(o,l,s),c=new yi(a,l,s);n.iterGaps((f,u,d)=>ou(h,f,c,u,d,r)),n.empty&&n.length==0&&ou(h,0,c,0,0,r)}static eq(e,t,n=0,r){r==null&&(r=999999999);let s=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(s.length!=o.length)return!1;if(!s.length)return!0;let a=su(s,o),l=new yi(s,a,0).goto(n),h=new yi(o,a,0).goto(n);for(;;){if(l.to!=h.to||!gl(l.active,h.active)||l.point&&(!h.point||!l.point.eq(h.point)))return!1;if(l.to>r)return!0;l.next(),h.next()}}static spans(e,t,n,r,s=-1){let o=new yi(e,null,s).goto(t),a=t,l=o.openStart;for(;;){let h=Math.min(o.to,n);if(o.point){let c=o.activeForPoint(o.to),f=o.pointFroma&&(r.span(a,h,o.active,l),l=o.openEnd(h));if(o.to>n)return l+(o.point&&o.to>n?1:0);a=o.to,o.next()}}static of(e,t=!1){let n=new lt;for(let r of e instanceof zn?[e]:t?ry(e):e)n.add(r.from,r.to,r.value);return n.finish()}static join(e){if(!e.length)return i.empty;let t=e[e.length-1];for(let n=e.length-2;n>=0;n--)for(let r=e[n];r!=i.empty;r=r.nextLayer)t=new i(r.chunkPos,r.chunk,t,Math.max(r.maxPoint,t.maxPoint));return t}};j.empty=new j([],[],null,-1);function ry(i){if(i.length>1)for(let e=i[0],t=1;t0)return i.slice().sort(pl);e=n}return i}j.empty.nextLayer=j.empty;var lt=class i{finishChunk(e){this.chunks.push(new ml(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,n){this.addInner(e,t,n)||(this.nextLayer||(this.nextLayer=new i)).add(e,t,n)}addInner(e,t,n){let r=e-this.lastTo||n.startSide-this.last.endSide;if(r<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return r<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=t,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let n=t.value.length-1;return this.last=t.value[n],this.lastFrom=t.from[n]+e,this.lastTo=t.to[n]+e,!0}finish(){return this.finishInner(j.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=j.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function su(i,e,t){let n=new Map;for(let s of i)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=n&&r.push(new Ms(o,t,n,s));return r.length==1?r[0]:new i(r)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let n of this.heap)n.goto(e,t);for(let n=this.heap.length>>1;n>=0;n--)nl(this.heap,n);return this.next(),this}forward(e,t){for(let n of this.heap)n.forward(e,t);for(let n=this.heap.length>>1;n>=0;n--)nl(this.heap,n);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),nl(this.heap,0)}}};function nl(i,e){for(let t=i[e];;){let n=(e<<1)+1;if(n>=i.length)break;let r=i[n];if(n+1=0&&(r=i[n+1],n++),t.compare(r)<0)break;i[n]=t,i[e]=r,e=n}}var yi=class{constructor(e,t,n){this.minPoint=n,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Un.from(e,t,n)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Ss(this.active,e),Ss(this.activeTo,e),Ss(this.activeRank,e),this.minActive=au(this.active,this.activeTo)}addActive(e){let t=0,{value:n,to:r,rank:s}=this.cursor;for(;t0;)t++;Ts(this.active,t,n),Ts(this.activeTo,t,r),Ts(this.activeRank,t,s),e&&Ts(e,t,this.cursor.from),this.minActive=au(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let n=this.openStart<0?[]:null;for(;;){let r=this.minActive;if(r>-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),n&&Ss(n,r)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let s=this.cursor.value;if(!s.point)this.addActive(n),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&n[r]=0&&!(this.activeRank[n]e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&t.push(this.active[n]);return t.reverse()}openEnd(e){let t=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)t++;return t}};function ou(i,e,t,n,r,s){i.goto(e),t.goto(n);let o=n+r,a=n,l=n-e;for(;;){let h=i.to+l-t.to||i.endSide-t.endSide,c=h<0?i.to+l:t.to,f=Math.min(c,o);if(i.point||t.point?i.point&&t.point&&(i.point==t.point||i.point.eq(t.point))&&gl(i.activeForPoint(i.to),t.activeForPoint(t.to))||s.comparePoint(a,f,i.point,t.point):f>a&&!gl(i.active,t.active)&&s.compareRange(a,f,i.active,t.active),c>o)break;a=c,h<=0&&i.next(),h>=0&&t.next()}}function gl(i,e){if(i.length!=e.length)return!1;for(let t=0;t=e;n--)i[n+1]=i[n];i[e]=t}function au(i,e){let t=-1,n=1e9;for(let r=0;r=e)return r;if(r==i.length)break;s+=i.charCodeAt(r)==9?t-s%t:1,r=ue(i,r)}return n===!0?-1:i.length}var bl="\u037C",vu=typeof Symbol>"u"?"__"+bl:Symbol.for(bl),wl=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),xu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},et=class{constructor(e,t){this.rules=[];let{finish:n}=t||{};function r(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,a,l,h){let c=[],f=/^@(\w+)\b/.exec(o[0]),u=f&&f[1]=="keyframes";if(f&&a==null)return l.push(o[0]+";");for(let d in a){let m=a[d];if(/&/.test(d))s(d.split(/,\s*/).map(p=>o.map(g=>p.replace(/&/,g))).reduce((p,g)=>p.concat(g)),m,l);else if(m&&typeof m=="object"){if(!f)throw new RangeError("The value of a property ("+d+") should be a primitive value.");s(r(d),m,c,u)}else m!=null&&c.push(d.replace(/_.*/,"").replace(/[A-Z]/g,p=>"-"+p.toLowerCase())+": "+m+";")}(c.length||u)&&l.push((n&&!f&&!h?o.map(n):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)s(r(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=xu[vu]||1;return xu[vu]=e+1,bl+e.toString(36)}static mount(e,t,n){let r=e[wl],s=n&&n.nonce;r?s&&r.setNonce(s):r=new vl(e,s),r.mount(Array.isArray(t)?t:[t],e)}},ku=new Map,vl=class{constructor(e,t){let n=e.ownerDocument||e,r=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let s=ku.get(n);if(s)return e[wl]=s;this.sheet=new r.CSSStyleSheet,ku.set(n,this)}else this.styleTag=n.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[wl]=this}mount(e,t){let n=this.sheet,r=0,s=0;for(let o=0;o-1&&(this.modules.splice(l,1),s--,l=-1),l==-1){if(this.modules.splice(s++,0,a),n)for(let h=0;h",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},sy=typeof navigator<"u"&&/Mac/.test(navigator.platform),oy=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(de=0;de<10;de++)Vt[48+de]=Vt[96+de]=String(de);var de;for(de=1;de<=24;de++)Vt[de+111]="F"+de;var de;for(de=65;de<=90;de++)Vt[de]=String.fromCharCode(de+32),tn[de]=String.fromCharCode(de);var de;for(Ds in Vt)tn.hasOwnProperty(Ds)||(tn[Ds]=Vt[Ds]);var Ds;function Su(i){var e=sy&&i.metaKey&&i.shiftKey&&!i.ctrlKey&&!i.altKey||oy&&i.shiftKey&&i.key&&i.key.length==1||i.key=="Unidentified",t=!e&&i.key||(i.shiftKey?tn:Vt)[i.keyCode]||i.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function ar(i){let e;return i.nodeType==11?e=i.getSelection?i:i.ownerDocument:e=i,e.getSelection()}function El(i,e){return e?i==e||i.contains(e.nodeType!=1?e.parentNode:e):!1}function ay(i){let e=i.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function js(i,e){if(!e.anchorNode)return!1;try{return El(i,e.anchorNode)}catch{return!1}}function lr(i){return i.nodeType==3?ki(i,0,i.nodeValue.length).getClientRects():i.nodeType==1?i.getClientRects():[]}function er(i,e,t,n){return t?Tu(i,e,t,n,-1)||Tu(i,e,t,n,1):!1}function xi(i){for(var e=0;;e++)if(i=i.previousSibling,!i)return e}function Ys(i){return i.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(i.nodeName)}function Tu(i,e,t,n,r){for(;;){if(i==t&&e==n)return!0;if(e==(r<0?0:Lt(i))){if(i.nodeName=="DIV")return!1;let s=i.parentNode;if(!s||s.nodeType!=1)return!1;e=xi(i)+(r<0?0:1),i=s}else if(i.nodeType==1){if(i=i.childNodes[e+(r<0?-1:0)],i.nodeType==1&&i.contentEditable=="false")return!1;e=r<0?Lt(i):0}else return!1}}function Lt(i){return i.nodeType==3?i.nodeValue.length:i.childNodes.length}function yh(i,e){let t=e?i.left:i.right;return{left:t,right:t,top:i.top,bottom:i.bottom}}function ly(i){let e=i.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:i.innerWidth,top:0,bottom:i.innerHeight}}function fd(i,e){let t=e.width/i.offsetWidth,n=e.height/i.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-i.offsetWidth)<1)&&(t=1),(n>.995&&n<1.005||!isFinite(n)||Math.abs(e.height-i.offsetHeight)<1)&&(n=1),{scaleX:t,scaleY:n}}function hy(i,e,t,n,r,s,o,a){let l=i.ownerDocument,h=l.defaultView||window;for(let c=i,f=!1;c&&!f;)if(c.nodeType==1){let u,d=c==l.body,m=1,p=1;if(d)u=ly(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(f=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let y=c.getBoundingClientRect();({scaleX:m,scaleY:p}=fd(c,y)),u={left:y.left,right:y.left+c.clientWidth*m,top:y.top,bottom:y.top+c.clientHeight*p}}let g=0,O=0;if(r=="nearest")e.top0&&e.bottom>u.bottom+O&&(O=e.bottom-u.bottom+O+o)):e.bottom>u.bottom&&(O=e.bottom-u.bottom+o,t<0&&e.top-O0&&e.right>u.right+g&&(g=e.right-u.right+g+s)):e.right>u.right&&(g=e.right-u.right+s,t<0&&e.leftt.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.assignedSlot||t.parentNode}else if(t.nodeType==11)t=t.host;else break;return null}var Al=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:n}=e;this.set(t,Math.min(e.anchorOffset,t?Lt(t):0),n,Math.min(e.focusOffset,n?Lt(n):0))}set(e,t,n,r){this.anchorNode=e,this.anchorOffset=t,this.focusNode=n,this.focusOffset=r}},nn=null;function ud(i){if(i.setActive)return i.setActive();if(nn)return i.focus(nn);let e=[];for(let t=i;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(i.focus(nn==null?{get preventScroll(){return nn={preventScroll:!0},!0}}:void 0),!nn){nn=!1;for(let t=0;tMath.max(1,i.scrollHeight-i.clientHeight-4)}function md(i,e){for(let t=i,n=e;;){if(t.nodeType==3&&n>0)return{node:t,offset:n};if(t.nodeType==1&&n>0){if(t.contentEditable=="false")return null;t=t.childNodes[n-1],n=Lt(t)}else if(t.parentNode&&!Ys(t))n=xi(t),t=t.parentNode;else return null}}function gd(i,e){for(let t=i,n=e;;){if(t.nodeType==3&&nt)return f.domBoundsAround(e,t,h);if(u>=e&&r==-1&&(r=l,s=h),h>t&&f.dom.parentNode==this.dom){o=l,a=c;break}c=u,h=u+f.breakAfter}return{from:s,to:a<0?n+this.length:a,startDOM:(r?this.children[r-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:o=0?this.children[o].dom:null}}markDirty(e=!1){this.flags|=2,this.markParentsDirty(e)}markParentsDirty(e){for(let t=this.parent;t;t=t.parent){if(e&&(t.flags|=2),t.flags&1)return;t.flags|=1,e=!1}}setParent(e){this.parent!=e&&(this.parent=e,this.flags&7&&this.markParentsDirty(!0))}setDOM(e){this.dom!=e&&(this.dom&&(this.dom.cmView=null),this.dom=e,e.cmView=this)}get rootView(){for(let e=this;;){let t=e.parent;if(!t)return e;e=t}}replaceChildren(e,t,n=bh){this.markDirty();for(let r=e;rthis.pos||e==this.pos&&(t>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=e-this.pos,this;let n=this.children[--this.i];this.pos-=n.length+n.breakAfter}}};function Od(i,e,t,n,r,s,o,a,l){let{children:h}=i,c=h.length?h[e]:null,f=s.length?s[s.length-1]:null,u=f?f.breakAfter:o;if(!(e==n&&c&&!o&&!u&&s.length<2&&c.merge(t,r,s.length?f:null,t==0,a,l))){if(n0&&(!o&&s.length&&c.merge(t,c.length,s[0],!1,a,0)?c.breakAfter=s.shift().breakAfter:(t2),Q={mac:Au||/Mac/.test(qe.platform),windows:/Win/.test(qe.platform),linux:/Linux|X11/.test(qe.platform),ie:fo,ie_version:bd?Ql.documentMode||6:_l?+_l[1]:Ml?+Ml[1]:0,gecko:Ru,gecko_version:Ru?+(/Firefox\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,chrome:!!xl,chrome_version:xl?+xl[1]:0,ios:Au,android:/Android\b/.test(qe.userAgent),webkit:Eu,safari:wd,webkit_version:Eu?+(/\bAppleWebKit\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,tabSize:Ql.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"},dy=256,vt=class i extends J{constructor(e){super(),this.text=e}get length(){return this.text.length}createDOM(e){this.setDOM(e||document.createTextNode(this.text))}sync(e,t){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(t&&t.node==this.dom&&(t.written=!0),this.dom.nodeValue=this.text)}reuseDOM(e){e.nodeType==3&&this.createDOM(e)}merge(e,t,n){return this.flags&8||n&&(!(n instanceof i)||this.length-(t-e)+n.length>dy||n.flags&8)?!1:(this.text=this.text.slice(0,e)+(n?n.text:"")+this.text.slice(t),this.markDirty(),!0)}split(e){let t=new i(this.text.slice(e));return this.text=this.text.slice(0,e),this.markDirty(),t.flags|=this.flags&8,t}localPosFromDOM(e,t){return e==this.dom?t:t?this.text.length:0}domAtPos(e){return new Me(this.dom,e)}domBoundsAround(e,t,n){return{from:n,to:n+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(e,t){return py(this.dom,e,t)}},Zt=class i extends J{constructor(e,t=[],n=0){super(),this.mark=e,this.children=t,this.length=n;for(let r of t)r.setParent(this)}setAttrs(e){if(dd(e),this.mark.class&&(e.className=this.mark.class),this.mark.attrs)for(let t in this.mark.attrs)e.setAttribute(t,this.mark.attrs[t]);return e}canReuseDOM(e){return super.canReuseDOM(e)&&!((this.flags|e.flags)&8)}reuseDOM(e){e.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(e),this.flags|=6)}sync(e,t){this.dom?this.flags&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(e,t)}merge(e,t,n,r,s,o){return n&&(!(n instanceof i&&n.mark.eq(this.mark))||e&&s<=0||te&&t.push(n=e&&(r=s),n=l,s++}let o=this.length-e;return this.length=e,r>-1&&(this.children.length=r,this.markDirty()),new i(this.mark,t,o)}domAtPos(e){return vd(this,e)}coordsAt(e,t){return kd(this,e,t)}};function py(i,e,t){let n=i.nodeValue.length;e>n&&(e=n);let r=e,s=e,o=0;e==0&&t<0||e==n&&t>=0?Q.chrome||Q.gecko||(e?(r--,o=1):s=0)?0:a.length-1];return Q.safari&&!o&&l.width==0&&(l=Array.prototype.find.call(a,h=>h.width)||l),o?yh(l,o<0):l||null}var hr=class i extends J{static create(e,t,n){return new i(e,t,n)}constructor(e,t,n){super(),this.widget=e,this.length=t,this.side=n,this.prevWidget=null}split(e){let t=i.create(this.widget,this.length-e,this.side);return this.length-=e,t}sync(e){(!this.dom||!this.widget.updateDOM(this.dom,e))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(e)),this.widget.editable||(this.dom.contentEditable="false"))}getSide(){return this.side}merge(e,t,n,r,s,o){return n&&(!(n instanceof i)||!this.widget.compare(n.widget)||e>0&&s<=0||t0)?Me.before(this.dom):Me.after(this.dom,e==this.length)}domBoundsAround(){return null}coordsAt(e,t){let n=this.widget.coordsAt(this.dom,e,t);if(n)return n;let r=this.dom.getClientRects(),s=null;if(!r.length)return null;let o=this.side?this.side<0:e>0;for(let a=o?r.length-1:0;s=r[a],!(e>0?a==0:a==r.length-1||s.top0?Me.before(this.dom):Me.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(e){return this.dom.getBoundingClientRect()}get overrideDOMText(){return W.empty}get isHidden(){return!0}};vt.prototype.children=hr.prototype.children=cr.prototype.children=bh;function vd(i,e){let t=i.dom,{children:n}=i,r=0;for(let s=0;rs&&e0;s--){let o=n[s-1];if(o.dom.parentNode==t)return o.domAtPos(o.length)}for(let s=r;s0&&e instanceof Zt&&r.length&&(n=r[r.length-1])instanceof Zt&&n.mark.eq(e.mark)?xd(n,e.children[0],t-1):(r.push(e),e.setParent(i)),i.length+=e.length}function kd(i,e,t){let n=null,r=-1,s=null,o=-1;function a(h,c){for(let f=0,u=0;f=c&&(d.children.length?a(d,c-u):(!s||s.isHidden&&t>0)&&(m>c||u==m&&d.getSide()>0)?(s=d,o=c-u):(u-1?1:0)!=r.length-(t&&r.indexOf(t)>-1?1:0))return!1;for(let s of n)if(s!=t&&(r.indexOf(s)==-1||i[s]!==e[s]))return!1;return!0}function $l(i,e,t){let n=!1;if(e)for(let r in e)t&&r in t||(n=!0,r=="style"?i.style.cssText="":i.removeAttribute(r));if(t)for(let r in t)e&&e[r]==t[r]||(n=!0,r=="style"?i.style.cssText=t[r]:i.setAttribute(r,t[r]));return n}function gy(i){let e=Object.create(null);for(let t=0;t0&&this.children[n-1].length==0;)this.children[--n].destroy();return this.children.length=n,this.markDirty(),this.length=e,t}transferDOM(e){this.dom&&(this.markDirty(),e.setDOM(this.dom),e.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(e){Js(this.attrs,e)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=e)}append(e,t){xd(this,e,t)}addLineDeco(e){let t=e.spec.attributes,n=e.spec.class;t&&(this.attrs=Dl(t,this.attrs||{})),n&&(this.attrs=Dl({class:n},this.attrs||{}))}domAtPos(e){return vd(this,e)}reuseDOM(e){e.nodeName=="DIV"&&(this.setDOM(e),this.flags|=6)}sync(e,t){var n;this.dom?this.flags&4&&(dd(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&($l(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(e,t);let r=this.dom.lastChild;for(;r&&J.get(r)instanceof Zt;)r=r.lastChild;if(!r||!this.length||r.nodeName!="BR"&&((n=J.get(r))===null||n===void 0?void 0:n.isEditable)==!1&&(!Q.ios||!this.children.some(s=>s instanceof vt))){let s=document.createElement("BR");s.cmIgnore=!0,this.dom.appendChild(s)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let e=0,t;for(let n of this.children){if(!(n instanceof vt)||/[^ -~]/.test(n.text))return null;let r=lr(n.dom);if(r.length!=1)return null;e+=r[0].width,t=r[0].height}return e?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:e/this.length,textHeight:t}:null}coordsAt(e,t){let n=kd(this,e,t);if(!this.children.length&&n&&this.parent){let{heightOracle:r}=this.parent.view.viewState,s=n.bottom-n.top;if(Math.abs(s-r.lineHeight)<2&&r.textHeight=t){if(s instanceof i)return s;if(o>t)break}r=o+s.breakAfter}return null}},vi=class i extends J{constructor(e,t,n){super(),this.widget=e,this.length=t,this.deco=n,this.breakAfter=0,this.prevWidget=null}merge(e,t,n,r,s,o){return n&&(!(n instanceof i)||!this.widget.compare(n.widget)||e>0&&s<=0||t0}},Be=class{eq(e){return!1}updateDOM(e,t){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,n){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}},_e=function(i){return i[i.Text=0]="Text",i[i.WidgetBefore=1]="WidgetBefore",i[i.WidgetAfter=2]="WidgetAfter",i[i.WidgetRange=3]="WidgetRange",i}(_e||(_e={})),M=class extends at{constructor(e,t,n,r){super(),this.startSide=e,this.endSide=t,this.widget=n,this.spec=r}get heightRelevant(){return!1}static mark(e){return new fr(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),n=!!e.block;return t+=n&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new Jt(e,t,t,n,e.widget||null,!1)}static replace(e){let t=!!e.block,n,r;if(e.isBlockGap)n=-5e8,r=4e8;else{let{start:s,end:o}=Sd(e,t);n=(s?t?-3e8:-1:5e8)-1,r=(o?t?2e8:1:-6e8)+1}return new Jt(e,n,r,t,e.widget||null,!0)}static line(e){return new ur(e)}static set(e,t=!1){return j.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};M.none=j.empty;var fr=class i extends M{constructor(e){let{start:t,end:n}=Sd(e);super(t?-1:5e8,n?1:-6e8,null,e),this.tagName=e.tagName||"span",this.class=e.class||"",this.attrs=e.attributes||null}eq(e){var t,n;return this==e||e instanceof i&&this.tagName==e.tagName&&(this.class||((t=this.attrs)===null||t===void 0?void 0:t.class))==(e.class||((n=e.attrs)===null||n===void 0?void 0:n.class))&&Js(this.attrs,e.attrs,"class")}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};fr.prototype.point=!1;var ur=class i extends M{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof i&&this.spec.class==e.spec.class&&Js(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}};ur.prototype.mapMode=ge.TrackBefore;ur.prototype.point=!0;var Jt=class i extends M{constructor(e,t,n,r,s,o){super(t,n,s,e),this.block=r,this.isReplace=o,this.mapMode=r?t<=0?ge.TrackBefore:ge.TrackAfter:ge.TrackDel}get type(){return this.startSide!=this.endSide?_e.WidgetRange:this.startSide<=0?_e.WidgetBefore:_e.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof i&&Oy(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}};Jt.prototype.point=!0;function Sd(i,e=!1){let{inclusiveStart:t,inclusiveEnd:n}=i;return t==null&&(t=i.inclusive),n==null&&(n=i.inclusive),{start:t??e,end:n??e}}function Oy(i,e){return i==e||!!(i&&e&&i.compare(e))}function Vl(i,e,t,n=0){let r=t.length-1;r>=0&&t[r]+n>=i?t[r]=Math.max(t[r],e):t.push(i,e)}var tr=class i{constructor(e,t,n,r){this.doc=e,this.pos=t,this.end=n,this.disallowBlockEffectsFor=r,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=e.iter(),this.skip=t}posCovered(){if(this.content.length==0)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let e=this.content[this.content.length-1];return!(e.breakAfter||e instanceof vi&&e.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new be),this.atCursorPos=!0),this.curLine}flushBuffer(e=this.bufferMarks){this.pendingBuffer&&(this.curLine.append($s(new cr(-1),e),e.length),this.pendingBuffer=0)}addBlockWidget(e){this.flushBuffer(),this.curLine=null,this.content.push(e)}finish(e){this.pendingBuffer&&e<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,!this.posCovered()&&!(e&&this.content.length&&this.content[this.content.length-1]instanceof vi)&&this.getLine()}buildText(e,t,n){for(;e>0;){if(this.textOff==this.text.length){let{value:s,lineBreak:o,done:a}=this.cursor.next(this.skip);if(this.skip=0,a)throw new Error("Ran out of text content when drawing inline views");if(o){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,e--;continue}else this.text=s,this.textOff=0}let r=Math.min(this.text.length-this.textOff,e,512);this.flushBuffer(t.slice(t.length-n)),this.getLine().append($s(new vt(this.text.slice(this.textOff,this.textOff+r)),t),n),this.atCursorPos=!0,this.textOff+=r,e-=r,n=0}}span(e,t,n,r){this.buildText(t-e,n,r),this.pos=t,this.openStart<0&&(this.openStart=r)}point(e,t,n,r,s,o){if(this.disallowBlockEffectsFor[o]&&n instanceof Jt){if(n.block)throw new RangeError("Block decorations may not be specified via plugins");if(t>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let a=t-e;if(n instanceof Jt)if(n.block)n.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new vi(n.widget||Kt.block,a,n));else{let l=hr.create(n.widget||Kt.inline,a,a?0:n.startSide),h=this.atCursorPos&&!l.isEditable&&s<=r.length&&(e0),c=!l.isEditable&&(er.length||n.startSide<=0),f=this.getLine();this.pendingBuffer==2&&!h&&!l.isEditable&&(this.pendingBuffer=0),this.flushBuffer(r),h&&(f.append($s(new cr(1),r),s),s=r.length+Math.max(0,s-r.length)),f.append($s(l,r),s),this.atCursorPos=c,this.pendingBuffer=c?er.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=r.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(n);a&&(this.textOff+a<=this.text.length?this.textOff+=a:(this.skip+=a-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=t),this.openStart<0&&(this.openStart=s)}static build(e,t,n,r,s){let o=new i(e,t,n,s);return o.openEnd=j.spans(r,t,n,o),o.openStart<0&&(o.openStart=o.openEnd),o.finish(o.openEnd),o}};function $s(i,e){for(let t of e)i=new Zt(t,[i],i.length);return i}var Kt=class extends Be{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};Kt.inline=new Kt("span");Kt.block=new Kt("div");var H=function(i){return i[i.LTR=0]="LTR",i[i.RTL=1]="RTL",i}(H||(H={})),Si=H.LTR,wh=H.RTL;function Td(i){let e=[];for(let t=0;t=t){if(a.level==n)return o;(s<0||(r!=0?r<0?a.fromt:e[s].level>a.level))&&(s=o)}}if(s<0)throw new RangeError("Index out of range");return s}};function Cd(i,e){if(i.length!=e.length)return!1;for(let t=0;t=0;p-=3)if(Ot[p+1]==-d){let g=Ot[p+2],O=g&2?r:g&4?g&1?s:r:0;O&&(Y[f]=Y[Ot[p]]=O),a=p;break}}else{if(Ot.length==189)break;Ot[a++]=f,Ot[a++]=u,Ot[a++]=l}else if((m=Y[f])==2||m==1){let p=m==r;l=p?0:1;for(let g=a-3;g>=0;g-=3){let O=Ot[g+2];if(O&2)break;if(p)Ot[g+2]|=2;else{if(O&4)break;Ot[g+2]|=4}}}}}function ky(i,e,t,n){for(let r=0,s=n;r<=t.length;r++){let o=r?t[r-1].to:i,a=rl;)m==g&&(m=t[--p].from,g=p?t[p-1].to:i),Y[--m]=d;l=c}else s=h,l++}}}function ql(i,e,t,n,r,s,o){let a=n%2?2:1;if(n%2==r%2)for(let l=e,h=0;ll&&o.push(new bt(l,p.from,d));let g=p.direction==Si!=!(d%2);Bl(i,g?n+1:n,r,p.inner,p.from,p.to,o),l=p.to}m=p.to}else{if(m==t||(c?Y[m]!=a:Y[m]==a))break;m++}u?ql(i,l,m,n+1,r,u,o):le;){let c=!0,f=!1;if(!h||l>s[h-1].to){let p=Y[l-1];p!=a&&(c=!1,f=p==16)}let u=!c&&a==1?[]:null,d=c?n:n+1,m=l;e:for(;;)if(h&&m==s[h-1].to){if(f)break e;let p=s[--h];if(!c)for(let g=p.from,O=h;;){if(g==e)break e;if(O&&s[O-1].to==g)g=s[--O].from;else{if(Y[g-1]==a)break e;break}}if(u)u.push(p);else{p.toY.length;)Y[Y.length]=256;let n=[],r=e==Si?0:1;return Bl(i,r,r,t,0,i.length,n),n}function Rd(i){return[new bt(0,i,0)]}var Ed="";function Ty(i,e,t,n,r){var s;let o=n.head-i.from,a=bt.find(e,o,(s=n.bidiLevel)!==null&&s!==void 0?s:-1,n.assoc),l=e[a],h=l.side(r,t);if(o==h){let u=a+=r?1:-1;if(u<0||u>=e.length)return null;l=e[a=u],o=l.side(!r,t),h=l.side(r,t)}let c=ue(i.text,o,l.forward(r,t));(cl.to)&&(c=h),Ed=i.text.slice(Math.min(o,c),Math.max(o,c));let f=a==(r?e.length-1:0)?null:e[a+(r?1:-1)];return f&&c==h&&f.level+(r?0:1)i.some(e=>e)}),Ld=A.define({combine:i=>i.some(e=>e)}),qd=A.define(),ir=class i{constructor(e,t="nearest",n="nearest",r=5,s=5,o=!1){this.range=e,this.y=t,this.x=n,this.yMargin=r,this.xMargin=s,this.isSnapshot=o}map(e){return e.empty?this:new i(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new i(S.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},Vs=_.define({map:(i,e)=>i.map(e)}),Bd=_.define();function we(i,e,t){let n=i.facet(_d);n.length?n[0](e):window.onerror?window.onerror(String(e),t,void 0,void 0,e):t?console.error(t+":",e):console.error(e)}var Ht=A.define({combine:i=>i.length?i[0]:!0}),Cy=0,Gn=A.define(),re=class i{constructor(e,t,n,r,s){this.id=e,this.create=t,this.domEventHandlers=n,this.domEventObservers=r,this.extension=s(this)}static define(e,t){let{eventHandlers:n,eventObservers:r,provide:s,decorations:o}=t||{};return new i(Cy++,e,n,r,a=>{let l=[Gn.of(a)];return o&&l.push(dr.of(h=>{let c=h.plugin(a);return c?o(c):M.none})),s&&l.push(s(a)),l})}static fromClass(e,t){return i.define(n=>new e(n),t)}},nr=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(n){if(we(t.state,n,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(e)}catch(t){we(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(n){we(e.state,n,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},Xd=A.define(),vh=A.define(),dr=A.define(),Wd=A.define(),xh=A.define(),Id=A.define();function Mu(i,e){let t=i.state.facet(Id);if(!t.length)return t;let n=t.map(s=>s instanceof Function?s(i):s),r=[];return j.spans(n,e.from,e.to,{point(){},span(s,o,a,l){let h=s-e.from,c=o-e.from,f=r;for(let u=a.length-1;u>=0;u--,l--){let d=a[u].spec.bidiIsolate,m;if(d==null&&(d=Py(e.text,h,c)),l>0&&f.length&&(m=f[f.length-1]).to==h&&m.direction==d)m.to=c,f=m.inner;else{let p={from:h,to:c,direction:d,inner:[]};f.push(p),f=p.inner}}}}),r}var Nd=A.define();function jd(i){let e=0,t=0,n=0,r=0;for(let s of i.state.facet(Nd)){let o=s(i);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(n=Math.max(n,o.top)),o.bottom!=null&&(r=Math.max(r,o.bottom)))}return{left:e,right:t,top:n,bottom:r}}var Yn=A.define(),wt=class i{constructor(e,t,n,r){this.fromA=e,this.toA=t,this.fromB=n,this.toB=r}join(e){return new i(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,n=this;for(;t>0;t--){let r=e[t-1];if(!(r.fromA>n.toA)){if(r.toAc)break;s+=2}if(!l)return n;new i(l.fromA,l.toA,l.fromB,l.toB).addToSet(n),o=l.toA,a=l.toB}}},Ks=class i{constructor(e,t,n){this.view=e,this.state=t,this.transactions=n,this.flags=0,this.startState=e.state,this.changes=Ae.empty(this.startState.doc.length);for(let s of n)this.changes=this.changes.compose(s.changes);let r=[];this.changes.iterChangedRanges((s,o,a,l)=>r.push(new wt(s,o,a,l))),this.changedRanges=r}static create(e,t,n){return new i(e,t,n)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}},eo=class extends J{get length(){return this.view.state.doc.length}constructor(e){super(),this.view=e,this.decorations=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.markedForComposition=new Set,this.editContextFormatting=M.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(e.contentDOM),this.children=[new be],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new wt(0,0,0,e.state.doc.length)],0,null)}update(e){var t;let n=e.changedRanges;this.minWidth>0&&n.length&&(n.every(({fromA:h,toA:c})=>cthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let r=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?r=this.domChanged.newSel.head:!Dy(e.changes,this.hasComposition)&&!e.selectionSet&&(r=e.state.selection.main.head));let s=r>-1?Ey(this.view,e.changes,r):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from:h,to:c}=this.hasComposition;n=new wt(h,c,e.changes.mapPos(h,-1),e.changes.mapPos(c,1)).addToSet(n.slice())}this.hasComposition=s?{from:s.range.fromB,to:s.range.toB}:null,(Q.ie||Q.chrome)&&!s&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.updateDeco(),l=My(o,a,e.changes);return n=wt.extendWithRanges(n,l),!(this.flags&7)&&n.length==0?!1:(this.updateInner(n,e.startState.doc.length,s),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t,n){this.view.viewState.mustMeasureContent=!0,this.updateChildren(e,t,n);let{observer:r}=this.view;r.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let o=Q.chrome||Q.ios?{node:r.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,o),this.flags&=-8,o&&(o.written||r.selectionRange.focusNode!=o.node)&&(this.forceSelection=!0),this.dom.style.height=""}),this.markedForComposition.forEach(o=>o.flags&=-9);let s=[];if(this.view.viewport.from||this.view.viewport.to=0?r[o]:null;if(!a)break;let{fromA:l,toA:h,fromB:c,toB:f}=a,u,d,m,p;if(n&&n.range.fromBc){let x=tr.build(this.view.state.doc,c,n.range.fromB,this.decorations,this.dynamicDecorationMap),w=tr.build(this.view.state.doc,n.range.toB,f,this.decorations,this.dynamicDecorationMap);d=x.breakAtStart,m=x.openStart,p=w.openEnd;let P=this.compositionView(n);w.breakAtStart?P.breakAfter=1:w.content.length&&P.merge(P.length,P.length,w.content[0],!1,w.openStart,0)&&(P.breakAfter=w.content[0].breakAfter,w.content.shift()),x.content.length&&P.merge(0,0,x.content[x.content.length-1],!0,0,x.openEnd)&&x.content.pop(),u=x.content.concat(P).concat(w.content)}else({content:u,breakAtStart:d,openStart:m,openEnd:p}=tr.build(this.view.state.doc,c,f,this.decorations,this.dynamicDecorationMap));let{i:g,off:O}=s.findPos(h,1),{i:y,off:v}=s.findPos(l,-1);Od(this,y,v,g,O,u,d,m,p)}n&&this.fixCompositionDOM(n)}updateEditContextFormatting(e){this.editContextFormatting=this.editContextFormatting.map(e.changes);for(let t of e.transactions)for(let n of t.effects)n.is(Bd)&&(this.editContextFormatting=n.value)}compositionView(e){let t=new vt(e.text.nodeValue);t.flags|=8;for(let{deco:r}of e.marks)t=new Zt(r,[t],t.length);let n=new be;return n.append(t,0),n}fixCompositionDOM(e){let t=(s,o)=>{o.flags|=8|(o.children.some(l=>l.flags&7)?1:0),this.markedForComposition.add(o);let a=J.get(s);a&&a!=o&&(a.dom=null),o.setDOM(s)},n=this.childPos(e.range.fromB,1),r=this.children[n.i];t(e.line,r);for(let s=e.marks.length-1;s>=-1;s--)n=r.childPos(n.off,1),r=r.children[n.i],t(s>=0?e.marks[s].node:e.text,r)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let n=this.view.root.activeElement,r=n==this.dom,s=!r&&js(this.dom,this.view.observer.selectionRange)&&!(n&&this.dom.contains(n));if(!(r||t||s))return;let o=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,l=this.moveToLine(this.domAtPos(a.anchor)),h=a.empty?l:this.moveToLine(this.domAtPos(a.head));if(Q.gecko&&a.empty&&!this.hasComposition&&Ry(l)){let f=document.createTextNode("");this.view.observer.ignore(()=>l.node.insertBefore(f,l.node.childNodes[l.offset]||null)),l=h=new Me(f,0),o=!0}let c=this.view.observer.selectionRange;(o||!c.focusNode||(!er(l.node,l.offset,c.anchorNode,c.anchorOffset)||!er(h.node,h.offset,c.focusNode,c.focusOffset))&&!this.suppressWidgetCursorChange(c,a))&&(this.view.observer.ignore(()=>{Q.android&&Q.chrome&&this.dom.contains(c.focusNode)&&_y(c.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let f=ar(this.view.root);if(f)if(a.empty){if(Q.gecko){let u=Ay(l.node,l.offset);if(u&&u!=3){let d=(u==1?md:gd)(l.node,l.offset);d&&(l=new Me(d.node,d.offset))}}f.collapse(l.node,l.offset),a.bidiLevel!=null&&f.caretBidiLevel!==void 0&&(f.caretBidiLevel=a.bidiLevel)}else if(f.extend){f.collapse(l.node,l.offset);try{f.extend(h.node,h.offset)}catch{}}else{let u=document.createRange();a.anchor>a.head&&([l,h]=[h,l]),u.setEnd(h.node,h.offset),u.setStart(l.node,l.offset),f.removeAllRanges(),f.addRange(u)}s&&this.view.root.activeElement==this.dom&&(this.dom.blur(),n&&n.focus())}),this.view.observer.setSelectionRange(l,h)),this.impreciseAnchor=l.precise?null:new Me(c.anchorNode,c.anchorOffset),this.impreciseHead=h.precise?null:new Me(c.focusNode,c.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&er(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,n=ar(e.root),{anchorNode:r,anchorOffset:s}=e.observer.selectionRange;if(!n||!t.empty||!t.assoc||!n.modify)return;let o=be.find(this,t.head);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!l||!h||l.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc);n.collapse(c.node,c.offset),n.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let f=e.observer.selectionRange;e.docView.posFromDOM(f.anchorNode,f.anchorOffset)!=t.from&&n.collapse(r,s)}moveToLine(e){let t=this.dom,n;if(e.node!=t)return e;for(let r=e.offset;!n&&r=0;r--){let s=J.get(t.childNodes[r]);s instanceof be&&(n=s.domAtPos(s.length))}return n?new Me(n.node,n.offset,!0):e}nearest(e){for(let t=e;t;){let n=J.get(t);if(n&&n.rootView==this)return n;t=t.parentNode}return null}posFromDOM(e,t){let n=this.nearest(e);if(!n)throw new RangeError("Trying to find position for a DOM position outside of the document");return n.localPosFromDOM(e,t)+n.posAtStart}domAtPos(e){let{i:t,off:n}=this.childCursor().findPos(e,-1);for(;t=0;o--){let a=this.children[o],l=s-a.breakAfter,h=l-a.length;if(le||a.covers(1))&&(!n||a instanceof be&&!(n instanceof be&&t>=0)))n=a,r=h;else if(n&&h==e&&l==e&&a instanceof vi&&Math.abs(t)<2){if(a.deco.startSide<0)break;o&&(n=null)}s=h}return n?n.coordsAt(e-r,t):null}coordsForChar(e){let{i:t,off:n}=this.childPos(e,1),r=this.children[t];if(!(r instanceof be))return null;for(;r.children.length;){let{i:a,off:l}=r.childPos(n,1);for(;;a++){if(a==r.children.length)return null;if((r=r.children[a]).length)break}n=l}if(!(r instanceof vt))return null;let s=ue(r.text,n);if(s==n)return null;let o=ki(r.dom,n,s).getClientRects();for(let a=0;aMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==H.LTR;for(let h=0,c=0;cr)break;if(h>=n){let d=f.dom.getBoundingClientRect();if(t.push(d.height),o){let m=f.dom.lastChild,p=m?lr(m):[];if(p.length){let g=p[p.length-1],O=l?g.right-d.left:d.right-g.left;O>a&&(a=O,this.minWidth=s,this.minWidthFrom=h,this.minWidthTo=u)}}}h=u+f.breakAfter}return t}textDirectionAt(e){let{i:t}=this.childPos(e,1);return getComputedStyle(this.children[t].dom).direction=="rtl"?H.RTL:H.LTR}measureTextSize(){for(let s of this.children)if(s instanceof be){let o=s.measureTextSize();if(o)return o}let e=document.createElement("div"),t,n,r;return e.className="cm-line",e.style.width="99999px",e.style.position="absolute",e.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.dom.appendChild(e);let s=lr(e.firstChild)[0];t=e.getBoundingClientRect().height,n=s?s.width/27:7,r=s?s.height:t,e.remove()}),{lineHeight:t,charWidth:n,textHeight:r}}childCursor(e=this.length){let t=this.children.length;return t&&(e-=this.children[--t].length),new Zs(this.children,e,t)}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let n=0,r=0;;r++){let s=r==t.viewports.length?null:t.viewports[r],o=s?s.from-1:this.length;if(o>n){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(n).top)/this.view.scaleY;e.push(M.replace({widget:new to(a),block:!0,inclusive:!0,isBlockGap:!0}).range(n,o))}if(!s)break;n=s.to+1}return M.set(e)}updateDeco(){let e=1,t=this.view.state.facet(dr).map(s=>(this.dynamicDecorationMap[e++]=typeof s=="function")?s(this.view):s),n=!1,r=this.view.state.facet(Wd).map((s,o)=>{let a=typeof s=="function";return a&&(n=!0),a?s(this.view):s});for(r.length&&(this.dynamicDecorationMap[e++]=n,t.push(j.join(r))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];et.anchor?-1:1),r;if(!n)return;!t.empty&&(r=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(n={left:Math.min(n.left,r.left),top:Math.min(n.top,r.top),right:Math.max(n.right,r.right),bottom:Math.max(n.bottom,r.bottom)});let s=jd(this.view),o={left:n.left-s.left,top:n.top-s.top,right:n.right+s.right,bottom:n.bottom+s.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;hy(this.view.scrollDOM,o,t.head{ne.from&&(t=!0)}),t}function $y(i,e,t=1){let n=i.charCategorizer(e),r=i.doc.lineAt(e),s=e-r.from;if(r.length==0)return S.cursor(e);s==0?t=1:s==r.length&&(t=-1);let o=s,a=s;t<0?o=ue(r.text,s,!1):a=ue(r.text,s);let l=n(r.text.slice(o,a));for(;o>0;){let h=ue(r.text,o,!1);if(n(r.text.slice(h,o))!=l)break;o=h}for(;ai?e.left-i:Math.max(0,i-e.right)}function Ly(i,e){return e.top>i?e.top-i:Math.max(0,i-e.bottom)}function kl(i,e){return i.tope.top+1}function _u(i,e){return ei.bottom?{top:i.top,left:i.left,right:i.right,bottom:e}:i}function Wl(i,e,t){let n,r,s,o,a=!1,l,h,c,f;for(let m=i.firstChild;m;m=m.nextSibling){let p=lr(m);for(let g=0;gv||o==v&&s>y){n=m,r=O,s=y,o=v;let x=v?t0?g0)}y==0?t>O.bottom&&(!c||c.bottomO.top)&&(h=m,f=O):c&&kl(c,O)?c=Du(c,O.bottom):f&&kl(f,O)&&(f=_u(f,O.top))}}if(c&&c.bottom>=t?(n=l,r=c):f&&f.top<=t&&(n=h,r=f),!n)return{node:i,offset:0};let u=Math.max(r.left,Math.min(r.right,e));if(n.nodeType==3)return $u(n,u,t);if(a&&n.contentEditable!="false")return Wl(n,u,t);let d=Array.prototype.indexOf.call(i.childNodes,n)+(e>=(r.left+r.right)/2?1:0);return{node:i,offset:d}}function $u(i,e,t){let n=i.nodeValue.length,r=-1,s=1e9,o=0;for(let a=0;at?c.top-t:t-c.bottom)-1;if(c.left-1<=e&&c.right+1>=e&&f=(c.left+c.right)/2,d=u;if((Q.chrome||Q.gecko)&&ki(i,a).getBoundingClientRect().left==c.right&&(d=!u),f<=0)return{node:i,offset:a+(d?1:0)};r=a+(d?1:0),s=f}}}return{node:i,offset:r>-1?r:o>0?i.nodeValue.length:0}}function Ud(i,e,t,n=-1){var r,s;let o=i.contentDOM.getBoundingClientRect(),a=o.top+i.viewState.paddingTop,l,{docHeight:h}=i.viewState,{x:c,y:f}=e,u=f-a;if(u<0)return 0;if(u>h)return i.state.doc.length;for(let x=i.viewState.heightOracle.textHeight/2,w=!1;l=i.elementAtHeight(u),l.type!=_e.Text;)for(;u=n>0?l.bottom+x:l.top-x,!(u>=0&&u<=h);){if(w)return t?null:0;w=!0,n=-n}f=a+u;let d=l.from;if(di.viewport.to)return i.viewport.to==i.state.doc.length?i.state.doc.length:t?null:Vu(i,o,l,c,f);let m=i.dom.ownerDocument,p=i.root.elementFromPoint?i.root:m,g=p.elementFromPoint(c,f);g&&!i.contentDOM.contains(g)&&(g=null),g||(c=Math.max(o.left+1,Math.min(o.right-1,c)),g=p.elementFromPoint(c,f),g&&!i.contentDOM.contains(g)&&(g=null));let O,y=-1;if(g&&((r=i.docView.nearest(g))===null||r===void 0?void 0:r.isEditable)!=!1){if(m.caretPositionFromPoint){let x=m.caretPositionFromPoint(c,f);x&&({offsetNode:O,offset:y}=x)}else if(m.caretRangeFromPoint){let x=m.caretRangeFromPoint(c,f);x&&({startContainer:O,startOffset:y}=x,(!i.contentDOM.contains(O)||Q.safari&&qy(O,y,c)||Q.chrome&&By(O,y,c))&&(O=void 0))}}if(!O||!i.docView.dom.contains(O)){let x=be.find(i.docView,d);if(!x)return u>l.top+l.height/2?l.to:l.from;({node:O,offset:y}=Wl(x.dom,c,f))}let v=i.docView.nearest(O);if(!v)return null;if(v.isWidget&&((s=v.dom)===null||s===void 0?void 0:s.nodeType)==1){let x=v.dom.getBoundingClientRect();return e.yi.defaultLineHeight*1.5){let a=i.viewState.heightOracle.textHeight,l=Math.floor((r-t.top-(i.defaultLineHeight-a)*.5)/a);s+=l*i.viewState.heightOracle.lineLength}let o=i.state.sliceDoc(t.from,t.to);return t.from+_s(o,s,i.state.tabSize)}function qy(i,e,t){let n;if(i.nodeType!=3||e!=(n=i.nodeValue.length))return!1;for(let r=i.nextSibling;r;r=r.nextSibling)if(r.nodeType!=1||r.nodeName!="BR")return!1;return ki(i,n-1,n).getBoundingClientRect().left>t}function By(i,e,t){if(e!=0)return!1;for(let r=i;;){let s=r.parentNode;if(!s||s.nodeType!=1||s.firstChild!=r)return!1;if(s.classList.contains("cm-line"))break;r=s}let n=i.nodeType==1?i.getBoundingClientRect():ki(i,0,Math.max(i.nodeValue.length,1)).getBoundingClientRect();return t-n.left>5}function Il(i,e){let t=i.lineBlockAt(e);if(Array.isArray(t.type)){for(let n of t.type)if(n.to>e||n.to==e&&(n.to==t.to||n.type==_e.Text))return n}return t}function Xy(i,e,t,n){let r=Il(i,e.head),s=!n||r.type!=_e.Text||!(i.lineWrapping||r.widgetLineBreaks)?null:i.coordsAtPos(e.assoc<0&&e.head>r.from?e.head-1:e.head);if(s){let o=i.dom.getBoundingClientRect(),a=i.textDirectionAt(r.from),l=i.posAtCoords({x:t==(a==H.LTR)?o.right-1:o.left+1,y:(s.top+s.bottom)/2});if(l!=null)return S.cursor(l,t?-1:1)}return S.cursor(t?r.to:r.from,t?-1:1)}function Lu(i,e,t,n){let r=i.state.doc.lineAt(e.head),s=i.bidiSpans(r),o=i.textDirectionAt(r.from);for(let a=e,l=null;;){let h=Ty(r,s,o,a,t),c=Ed;if(!h){if(r.number==(t?i.state.doc.lines:1))return a;c=` +`,r=i.state.doc.line(r.number+(t?1:-1)),s=i.bidiSpans(r),h=i.visualLineSide(r,!t)}if(l){if(!l(c))return a}else{if(!n)return h;l=n(c)}a=h}}function Wy(i,e,t){let n=i.state.charCategorizer(e),r=n(t);return s=>{let o=n(s);return r==F.Space&&(r=o),r==o}}function Iy(i,e,t,n){let r=e.head,s=t?1:-1;if(r==(t?i.state.doc.length:0))return S.cursor(r,e.assoc);let o=e.goalColumn,a,l=i.contentDOM.getBoundingClientRect(),h=i.coordsAtPos(r,e.assoc||-1),c=i.documentTop;if(h)o==null&&(o=h.left-l.left),a=s<0?h.top:h.bottom;else{let d=i.viewState.lineBlockAt(r);o==null&&(o=Math.min(l.right-l.left,i.defaultCharacterWidth*(r-d.from))),a=(s<0?d.top:d.bottom)+c}let f=l.left+o,u=n??i.viewState.heightOracle.textHeight>>1;for(let d=0;;d+=10){let m=a+(u+d)*s,p=Ud(i,{x:f,y:m},!1,s);if(ml.bottom||(s<0?pr)){let g=i.docView.coordsForChar(p),O=!g||m{if(e>s&&er(i)),t.from,e.head>t.from?-1:1);return n==t.from?t:S.cursor(n,nnull),Q.gecko&&nb(e.contentDOM.ownerDocument)}handleEvent(e){!Gy(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||this.runHandlers(e.type,e)}runHandlers(e,t){let n=this.handlers[e];if(n){for(let r of n.observers)r(this.view,t);for(let r of n.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Ny(e),n=this.handlers,r=this.view.contentDOM;for(let s in t)if(s!="scroll"){let o=!t[s].handlers.length,a=n[s];a&&o!=!a.handlers.length&&(r.removeEventListener(s,this.handleEvent),a=null),a||r.addEventListener(s,this.handleEvent,{passive:o})}for(let s in n)s!="scroll"&&!t[s]&&r.removeEventListener(s,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Hd.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),Q.android&&Q.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return Q.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&((t=Fd.find(n=>n.keyCode==e.keyCode))&&!e.ctrlKey||jy.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from0?!0:Q.safari&&!Q.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function qu(i,e){return(t,n)=>{try{return e.call(i,n,t)}catch(r){we(t.state,r)}}}function Ny(i){let e=Object.create(null);function t(n){return e[n]||(e[n]={observers:[],handlers:[]})}for(let n of i){let r=n.spec;if(r&&r.domEventHandlers)for(let s in r.domEventHandlers){let o=r.domEventHandlers[s];o&&t(s).handlers.push(qu(n.value,o))}if(r&&r.domEventObservers)for(let s in r.domEventObservers){let o=r.domEventObservers[s];o&&t(s).observers.push(qu(n.value,o))}}for(let n in ht)t(n).handlers.push(ht[n]);for(let n in it)t(n).observers.push(it[n]);return e}var Fd=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],jy="dthko",Hd=[16,17,18,20,91,92,224,225],Ls=6;function qs(i){return Math.max(0,i)*.7+8}function zy(i,e){return Math.max(Math.abs(i.clientX-e.clientX),Math.abs(i.clientY-e.clientY))}var jl=class{constructor(e,t,n,r){this.view=e,this.startEvent=t,this.style=n,this.mustSelect=r,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParent=cy(e.contentDOM),this.atoms=e.state.facet(xh).map(o=>o(e));let s=e.contentDOM.ownerDocument;s.addEventListener("mousemove",this.move=this.move.bind(this)),s.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(N.allowMultipleSelections)&&Uy(e,t),this.dragging=Hy(e,t)&&Jd(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){var t;if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&zy(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let n=0,r=0,s=((t=this.scrollParent)===null||t===void 0?void 0:t.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},o=jd(this.view);e.clientX-o.left<=s.left+Ls?n=-qs(s.left-e.clientX):e.clientX+o.right>=s.right-Ls&&(n=qs(e.clientX-s.right)),e.clientY-o.top<=s.top+Ls?r=-qs(s.top-e.clientY):e.clientY+o.bottom>=s.bottom-Ls&&(r=qs(e.clientY-s.bottom)),this.setScrollSpeed(n,r)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),this.dragging===!1&&this.select(this.lastEvent)}skipAtoms(e){let t=null;for(let n=0;nt.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function Uy(i,e){let t=i.state.facet(Ad);return t.length?t[0](e):Q.mac?e.metaKey:e.ctrlKey}function Fy(i,e){let t=i.state.facet(Qd);return t.length?t[0](e):Q.mac?!e.altKey:!e.ctrlKey}function Hy(i,e){let{main:t}=i.state.selection;if(t.empty)return!1;let n=ar(i.root);if(!n||n.rangeCount==0)return!0;let r=n.getRangeAt(0).getClientRects();for(let s=0;s=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Gy(i,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,n;t!=i.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(n=J.get(t))&&n.ignoreEvent(e))return!1;return!0}var ht=Object.create(null),it=Object.create(null),Gd=Q.ie&&Q.ie_version<15||Q.ios&&Q.webkit_version<604;function Yy(i){let e=i.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{i.focus(),t.remove(),Yd(i,t.value)},50)}function Yd(i,e){let{state:t}=i,n,r=1,s=t.toText(e),o=s.lines==t.selection.ranges.length;if(zl!=null&&t.selection.ranges.every(l=>l.empty)&&zl==s.toString()){let l=-1;n=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==l)return{range:h};l=c.from;let f=t.toText((o?s.line(r++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:f},range:S.cursor(h.from+f.length)}})}else o?n=t.changeByRange(l=>{let h=s.line(r++);return{changes:{from:l.from,to:l.to,insert:h.text},range:S.cursor(l.from+h.length)}}):n=t.replaceSelection(s);i.dispatch(n,{userEvent:"input.paste",scrollIntoView:!0})}it.scroll=i=>{i.inputState.lastScrollTop=i.scrollDOM.scrollTop,i.inputState.lastScrollLeft=i.scrollDOM.scrollLeft};ht.keydown=(i,e)=>(i.inputState.setSelectionOrigin("select"),e.keyCode==27&&i.inputState.tabFocusMode!=0&&(i.inputState.tabFocusMode=Date.now()+2e3),!1);it.touchstart=(i,e)=>{i.inputState.lastTouchTime=Date.now(),i.inputState.setSelectionOrigin("select.pointer")};it.touchmove=i=>{i.inputState.setSelectionOrigin("select.pointer")};ht.mousedown=(i,e)=>{if(i.observer.flush(),i.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let n of i.state.facet(Md))if(t=n(i,e),t)break;if(!t&&e.button==0&&(t=Ky(i,e)),t){let n=!i.hasFocus;i.inputState.startMouseSelection(new jl(i,e,t,n)),n&&i.observer.ignore(()=>{ud(i.contentDOM);let s=i.root.activeElement;s&&!s.contains(i.contentDOM)&&s.blur()});let r=i.inputState.mouseSelection;if(r)return r.start(e),r.dragging===!1}return!1};function Bu(i,e,t,n){if(n==1)return S.cursor(e,t);if(n==2)return $y(i.state,e,t);{let r=be.find(i.docView,e),s=i.state.doc.lineAt(r?r.posAtEnd:e),o=r?r.posAtStart:s.from,a=r?r.posAtEnd:s.to;return ai>=e.top&&i<=e.bottom,Xu=(i,e,t)=>Zd(e,t)&&i>=t.left&&i<=t.right;function Zy(i,e,t,n){let r=be.find(i.docView,e);if(!r)return 1;let s=e-r.posAtStart;if(s==0)return 1;if(s==r.length)return-1;let o=r.coordsAt(s,-1);if(o&&Xu(t,n,o))return-1;let a=r.coordsAt(s,1);return a&&Xu(t,n,a)?1:o&&Zd(n,o)?-1:1}function Wu(i,e){let t=i.posAtCoords({x:e.clientX,y:e.clientY},!1);return{pos:t,bias:Zy(i,t,e.clientX,e.clientY)}}var Jy=Q.ie&&Q.ie_version<=11,Iu=null,Nu=0,ju=0;function Jd(i){if(!Jy)return i.detail;let e=Iu,t=ju;return Iu=i,ju=Date.now(),Nu=!e||t>Date.now()-400&&Math.abs(e.clientX-i.clientX)<2&&Math.abs(e.clientY-i.clientY)<2?(Nu+1)%3:1}function Ky(i,e){let t=Wu(i,e),n=Jd(e),r=i.state.selection;return{update(s){s.docChanged&&(t.pos=s.changes.mapPos(t.pos),r=r.map(s.changes))},get(s,o,a){let l=Wu(i,s),h,c=Bu(i,l.pos,l.bias,n);if(t.pos!=l.pos&&!o){let f=Bu(i,t.pos,t.bias,n),u=Math.min(f.from,c.from),d=Math.max(f.to,c.to);c=u1&&(h=eb(r,l.pos))?h:a?r.addRange(c):S.create([c])}}}function eb(i,e){for(let t=0;t=e)return S.create(i.ranges.slice(0,t).concat(i.ranges.slice(t+1)),i.mainIndex==t?0:i.mainIndex-(i.mainIndex>t?1:0))}return null}ht.dragstart=(i,e)=>{let{selection:{main:t}}=i.state;if(e.target.draggable){let r=i.docView.nearest(e.target);if(r&&r.isWidget){let s=r.posAtStart,o=s+r.length;(s>=t.to||o<=t.from)&&(t=S.range(s,o))}}let{inputState:n}=i;return n.mouseSelection&&(n.mouseSelection.dragging=!0),n.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",i.state.sliceDoc(t.from,t.to)),e.dataTransfer.effectAllowed="copyMove"),!1};ht.dragend=i=>(i.inputState.draggedContent=null,!1);function zu(i,e,t,n){if(!t)return;let r=i.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:s}=i.inputState,o=n&&s&&Fy(i,e)?{from:s.from,to:s.to}:null,a={from:r,insert:t},l=i.state.changes(o?[o,a]:a);i.focus(),i.dispatch({changes:l,selection:{anchor:l.mapPos(r,-1),head:l.mapPos(r,1)},userEvent:o?"move.drop":"input.drop"}),i.inputState.draggedContent=null}ht.drop=(i,e)=>{if(!e.dataTransfer)return!1;if(i.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let n=Array(t.length),r=0,s=()=>{++r==t.length&&zu(i,e,n.filter(o=>o!=null).join(i.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(n[o]=a.result),s()},a.readAsText(t[o])}return!0}else{let n=e.dataTransfer.getData("Text");if(n)return zu(i,e,n,!0),!0}return!1};ht.paste=(i,e)=>{if(i.state.readOnly)return!0;i.observer.flush();let t=Gd?null:e.clipboardData;return t?(Yd(i,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Yy(i),!1)};function tb(i,e){let t=i.dom.parentNode;if(!t)return;let n=t.appendChild(document.createElement("textarea"));n.style.cssText="position: fixed; left: -10000px; top: 10px",n.value=e,n.focus(),n.selectionEnd=e.length,n.selectionStart=0,setTimeout(()=>{n.remove(),i.focus()},50)}function ib(i){let e=[],t=[],n=!1;for(let r of i.selection.ranges)r.empty||(e.push(i.sliceDoc(r.from,r.to)),t.push(r));if(!e.length){let r=-1;for(let{from:s}of i.selection.ranges){let o=i.doc.lineAt(s);o.number>r&&(e.push(o.text),t.push({from:o.from,to:Math.min(i.doc.length,o.to+1)})),r=o.number}n=!0}return{text:e.join(i.lineBreak),ranges:t,linewise:n}}var zl=null;ht.copy=ht.cut=(i,e)=>{let{text:t,ranges:n,linewise:r}=ib(i.state);if(!t&&!r)return!1;zl=r?t:null,e.type=="cut"&&!i.state.readOnly&&i.dispatch({changes:n,scrollIntoView:!0,userEvent:"delete.cut"});let s=Gd?null:e.clipboardData;return s?(s.clearData(),s.setData("text/plain",t),!0):(tb(i,t),!1)};var Kd=Le.define();function ep(i,e){let t=[];for(let n of i.facet($d)){let r=n(i,e);r&&t.push(r)}return t?i.update({effects:t,annotations:Kd.of(!0)}):null}function tp(i){setTimeout(()=>{let e=i.hasFocus;if(e!=i.inputState.notifiedFocused){let t=ep(i.state,e);t?i.dispatch(t):i.update([])}},10)}it.focus=i=>{i.inputState.lastFocusTime=Date.now(),!i.scrollDOM.scrollTop&&(i.inputState.lastScrollTop||i.inputState.lastScrollLeft)&&(i.scrollDOM.scrollTop=i.inputState.lastScrollTop,i.scrollDOM.scrollLeft=i.inputState.lastScrollLeft),tp(i)};it.blur=i=>{i.observer.clearSelectionRange(),tp(i)};it.compositionstart=it.compositionupdate=i=>{i.observer.editContext||(i.inputState.compositionFirstChange==null&&(i.inputState.compositionFirstChange=!0),i.inputState.composing<0&&(i.inputState.composing=0))};it.compositionend=i=>{i.observer.editContext||(i.inputState.composing=-1,i.inputState.compositionEndedAt=Date.now(),i.inputState.compositionPendingKey=!0,i.inputState.compositionPendingChange=i.observer.pendingRecords().length>0,i.inputState.compositionFirstChange=null,Q.chrome&&Q.android?i.observer.flushSoon():i.inputState.compositionPendingChange?Promise.resolve().then(()=>i.observer.flush()):setTimeout(()=>{i.inputState.composing<0&&i.docView.hasComposition&&i.update([])},50))};it.contextmenu=i=>{i.inputState.lastContextMenu=Date.now()};ht.beforeinput=(i,e)=>{var t;let n;if(Q.chrome&&Q.android&&(n=Fd.find(r=>r.inputType==e.inputType))&&(i.observer.delayAndroidKey(n.key,n.keyCode),n.key=="Backspace"||n.key=="Delete")){let r=((t=window.visualViewport)===null||t===void 0?void 0:t.height)||0;setTimeout(()=>{var s;(((s=window.visualViewport)===null||s===void 0?void 0:s.height)||0)>r+10&&i.hasFocus&&(i.contentDOM.blur(),i.focus())},100)}return Q.ios&&e.inputType=="deleteContentForward"&&i.observer.flushSoon(),Q.safari&&e.inputType=="insertText"&&i.inputState.composing>=0&&setTimeout(()=>it.compositionend(i,e),20),!1};var Uu=new Set;function nb(i){Uu.has(i)||(Uu.add(i),i.addEventListener("copy",()=>{}),i.addEventListener("cut",()=>{}))}var Fu=["pre-wrap","normal","pre-line","break-spaces"],Ul=class{constructor(e){this.lineWrapping=e,this.doc=W.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(e,t){let n=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(n+=Math.max(0,Math.ceil((t-e-n*this.lineLength*.5)/this.lineLength))),this.lineHeight*n}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Fu.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let n=0;n-1,l=Math.round(t)!=Math.round(this.lineHeight)||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=n,this.textHeight=r,this.lineLength=s,l){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e,t){this.height!=t&&(Math.abs(this.height-t)>Us&&(e.heightChanged=!0),this.height=t)}replace(e,t,n){return i.of(n)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,n,r){let s=this,o=n.doc;for(let a=r.length-1;a>=0;a--){let{fromA:l,toA:h,fromB:c,toB:f}=r[a],u=s.lineAt(l,K.ByPosNoHeight,n.setDoc(t),0,0),d=u.to>=h?u:s.lineAt(h,K.ByPosNoHeight,n,0,0);for(f+=d.to-h,h=d.to;a>0&&u.from<=r[a-1].toA;)l=r[a-1].fromA,c=r[a-1].fromB,a--,ls*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),n+=1+a.break,r-=a.size}else if(s>r*2){let a=e[n];a.break?e.splice(n,1,a.left,null,a.right):e.splice(n,1,a.left,a.right),n+=2+a.break,s-=a.size}else break;else if(r=s&&o(this.blockAt(0,n,r,s))}updateHeight(e,t=0,n=!1,r){return r&&r.from<=t&&r.more&&this.setHeight(e,r.heights[r.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}},tt=class i extends io{constructor(e,t){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(e,t,n,r){return new yt(r,this.length,n,this.height,this.breaks)}replace(e,t,n){let r=n[0];return n.length==1&&(r instanceof i||r instanceof Yt&&r.flags&4)&&Math.abs(this.length-r.length)<10?(r instanceof Yt?r=new i(r.length,this.height):r.height=this.height,this.outdated||(r.outdated=!1),r):je.of(n)}updateHeight(e,t=0,n=!1,r){return r&&r.from<=t&&r.more?this.setHeight(e,r.heights[r.index++]):(n||this.outdated)&&this.setHeight(e,Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}},Yt=class i extends je{constructor(e){super(e,0)}heightMetrics(e,t){let n=e.doc.lineAt(t).number,r=e.doc.lineAt(t+this.length).number,s=r-n+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*s);o=l/s,this.length>s+1&&(a=(this.height-l)/(this.length-s-1))}else o=this.height/s;return{firstLine:n,lastLine:r,perLine:o,perChar:a}}blockAt(e,t,n,r){let{firstLine:s,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,r);if(t.lineWrapping){let h=r+(e0){let s=n[n.length-1];s instanceof i?n[n.length-1]=new i(s.length+r):n.push(null,new i(r-1))}if(e>0){let s=n[0];s instanceof i?n[0]=new i(e+s.length):n.unshift(new i(e-1),null)}return je.of(n)}decomposeLeft(e,t){t.push(new i(e-1),null)}decomposeRight(e,t){t.push(null,new i(this.length-e-1))}updateHeight(e,t=0,n=!1,r){let s=t+this.length;if(r&&r.from<=t+this.length&&r.more){let o=[],a=Math.max(t,r.from),l=-1;for(r.from>t&&o.push(new i(r.from-t-1).updateHeight(e,t));a<=s&&r.more;){let c=e.doc.lineAt(a).length;o.length&&o.push(null);let f=r.heights[r.index++];l==-1?l=f:Math.abs(f-l)>=Us&&(l=-2);let u=new tt(c,f);u.outdated=!1,o.push(u),a+=c+1}a<=s&&o.push(null,new i(s-a).updateHeight(e,a));let h=je.of(o);return(l<0||Math.abs(h.height-this.height)>=Us||Math.abs(l-this.heightMetrics(e,t).perLine)>=Us)&&(e.heightChanged=!0),h}else(n||this.outdated)&&(this.setHeight(e,e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},Hl=class extends je{constructor(e,t,n){super(e.length+t+n.length,e.height+n.height,t|(e.outdated||n.outdated?2:0)),this.left=e,this.right=n,this.size=e.size+n.size}get break(){return this.flags&1}blockAt(e,t,n,r){let s=n+this.left.height;return ea))return h;let c=t==K.ByPosNoHeight?K.ByPosNoHeight:K.ByPos;return l?h.join(this.right.lineAt(a,c,n,o,a)):this.left.lineAt(a,c,n,r,s).join(h)}forEachLine(e,t,n,r,s,o){let a=r+this.left.height,l=s+this.left.length+this.break;if(this.break)e=l&&this.right.forEachLine(e,t,n,a,l,o);else{let h=this.lineAt(l,K.ByPos,n,r,s);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,n,a,l,o)}}replace(e,t,n){let r=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-r,t-r,n));let s=[];e>0&&this.decomposeLeft(e,s);let o=s.length;for(let a of n)s.push(a);if(e>0&&Hu(s,o-1),t=n&&t.push(null)),e>n&&this.right.decomposeLeft(e-n,t)}decomposeRight(e,t){let n=this.left.length,r=n+this.break;if(e>=r)return this.right.decomposeRight(e-r,t);e2*t.size||t.size>2*e.size?je.of(this.break?[e,null,t]:[e,t]):(this.left=e,this.right=t,this.height=e.height+t.height,this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,n=!1,r){let{left:s,right:o}=this,a=t+s.length+this.break,l=null;return r&&r.from<=t+s.length&&r.more?l=s=s.updateHeight(e,t,n,r):s.updateHeight(e,t,n),r&&r.from<=a+o.length&&r.more?l=o=o.updateHeight(e,a,n,r):o.updateHeight(e,a,n),l?this.balanced(s,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function Hu(i,e){let t,n;i[e]==null&&(t=i[e-1])instanceof Yt&&(n=i[e+1])instanceof Yt&&i.splice(e-1,3,new Yt(t.length+1+n.length))}var rb=5,Gl=class i{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let n=Math.min(t,this.lineEnd),r=this.nodes[this.nodes.length-1];r instanceof tt?r.length+=n-this.pos:(n>this.pos||!this.isCovered)&&this.nodes.push(new tt(n-this.pos,-1)),this.writtenTo=n,t>n&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,n){if(e=rb)&&this.addLineDeco(r,s,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new tt(this.pos-e,-1)),this.writtenTo=this.pos}blankContent(e,t){let n=new Yt(t-e);return this.oracle.doc.lineAt(e).to==t&&(n.flags|=4),n}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof tt)return e;let t=new tt(0,-1);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,n){let r=this.ensureLine();r.length+=n,r.collapsed+=n,r.widgetHeight=Math.max(r.widgetHeight,e),r.breaks+=t,this.writtenTo=this.pos=this.pos+n}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof tt)&&!this.isCovered?this.nodes.push(new tt(0,-1)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&f.overflow!="visible"){let u=c.getBoundingClientRect();s=Math.max(s,u.left),o=Math.min(o,u.right),a=Math.max(a,u.top),l=h==i.parentNode?u.bottom:Math.min(l,u.bottom)}h=f.position=="absolute"||f.position=="fixed"?c.offsetParent:c.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:s-t.left,right:Math.max(s,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function ab(i,e){let t=i.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var rr=class{constructor(e,t,n){this.from=e,this.to=t,this.size=n}static same(e,t){if(e.length!=t.length)return!1;for(let n=0;ntypeof n!="function"&&n.class=="cm-lineWrapping");this.heightOracle=new Ul(t),this.stateDeco=e.facet(dr).filter(n=>typeof n!="function"),this.heightMap=je.empty().applyChanges(this.stateDeco,W.empty,this.heightOracle.setDoc(e.doc),[new wt(0,0,0,e.doc.length)]);for(let n=0;n<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());n++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=M.set(this.lineGaps.map(n=>n.draw(this,!1))),this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let n=0;n<=1;n++){let r=n?t.head:t.anchor;if(!e.some(({from:s,to:o})=>r>=s&&r<=o)){let{from:s,to:o}=this.lineBlockAt(r);e.push(new rn(s,o))}}return this.viewports=e.sort((n,r)=>n.from-r.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?Gu:new Jl(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Zn(e,this.scaler))})}update(e,t=null){this.state=e.state;let n=this.stateDeco;this.stateDeco=this.state.facet(dr).filter(c=>typeof c!="function");let r=e.changedRanges,s=wt.extendWithRanges(r,sb(n,this.stateDeco,e?e.changes:Ae.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),s),this.heightMap.height!=o&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let l=s.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let h=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(h||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&e.selectionSet&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(Ld)&&(this.mustEnforceCursorAssoc=!0)}measure(e){let t=e.contentDOM,n=window.getComputedStyle(t),r=this.heightOracle,s=n.whiteSpace;this.defaultTextDirection=n.direction=="rtl"?H.RTL:H.LTR;let o=this.heightOracle.mustRefreshForWrapping(s),a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let h=0,c=0;if(a.width&&a.height){let{scaleX:x,scaleY:w}=fd(t,a);(x>.005&&Math.abs(this.scaleX-x)>.005||w>.005&&Math.abs(this.scaleY-w)>.005)&&(this.scaleX=x,this.scaleY=w,h|=8,o=l=!0)}let f=(parseInt(n.paddingTop)||0)*this.scaleY,u=(parseInt(n.paddingBottom)||0)*this.scaleY;(this.paddingTop!=f||this.paddingBottom!=u)&&(this.paddingTop=f,this.paddingBottom=u,h|=10),this.editorWidth!=e.scrollDOM.clientWidth&&(r.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=8);let d=e.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=d&&(this.scrollAnchorHeight=-1,this.scrollTop=d),this.scrolledToBottom=pd(e.scrollDOM);let m=(this.printing?ab:ob)(t,this.paddingTop),p=m.top-this.pixelViewport.top,g=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let O=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(O!=this.inView&&(this.inView=O,O&&(l=!0)),!this.inView&&!this.scrollTarget)return 0;let y=a.width;if((this.contentDOMWidth!=y||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,h|=8),l){let x=e.docView.measureVisibleLineHeights(this.viewport);if(r.mustRefreshForHeights(x)&&(o=!0),o||r.lineWrapping&&Math.abs(y-this.contentDOMWidth)>r.charWidth){let{lineHeight:w,charWidth:P,textHeight:C}=e.docView.measureTextSize();o=w>0&&r.refresh(s,w,P,C,y/P,x),o&&(e.docView.minWidth=0,h|=8)}p>0&&g>0?c=Math.max(p,g):p<0&&g<0&&(c=Math.min(p,g)),r.heightChanged=!1;for(let w of this.viewports){let P=w.from==this.viewport.from?x:e.docView.measureVisibleLineHeights(w);this.heightMap=(o?je.empty().applyChanges(this.stateDeco,W.empty,this.heightOracle,[new wt(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(r,0,o,new Fl(w.from,P))}r.heightChanged&&(h|=2)}let v=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return v&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(c,this.scrollTarget),h|=this.updateForViewport()),(h&2||v)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let n=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),r=this.heightMap,s=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new rn(r.lineAt(o-n*1e3,K.ByHeight,s,0,0).from,r.lineAt(a+(1-n)*1e3,K.ByHeight,s,0,0).to);if(t){let{head:h}=t.range;if(hl.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),f=r.lineAt(h,K.ByPos,s,0,0),u;t.y=="center"?u=(f.top+f.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=a+Math.max(10,Math.min(n,250)))&&r>o-2*1e3&&s>1,o=r<<1;if(this.defaultTextDirection!=H.LTR&&!n)return[];let a=[],l=(c,f,u,d)=>{if(f-cc&&OO.from>=u.from&&O.to<=u.to&&Math.abs(O.from-c)O.fromy));if(!g){if(fO.from<=f&&O.to>=f)){let O=t.moveToLineBoundary(S.cursor(f),!1,!0).head;O>c&&(f=O)}g=new rr(c,f,this.gapSize(u,c,f,d))}a.push(g)},h=c=>{if(c.lengthc.from&&l(c.from,d,c,f),mt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(){let e=this.stateDeco;this.lineGaps.length&&(e=e.concat(this.lineGapDeco));let t=[];j.spans(e,this.viewport.from,this.viewport.to,{span(r,s){t.push({from:r,to:s})},point(){}},20);let n=t.length!=this.visibleRanges.length||this.visibleRanges.some((r,s)=>r.from!=t[s].from||r.to!=t[s].to);return this.visibleRanges=t,n?4:0}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Zn(this.heightMap.lineAt(e,K.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Zn(this.heightMap.lineAt(this.scaler.fromDOM(e),K.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Zn(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},rn=class{constructor(e,t){this.from=e,this.to=t}};function lb(i,e,t){let n=[],r=i,s=0;return j.spans(t,i,e,{span(){},point(o,a){o>r&&(n.push({from:r,to:o}),s+=o-r),r=a}},20),r=1)return e[e.length-1].to;let n=Math.floor(i*t);for(let r=0;;r++){let{from:s,to:o}=e[r],a=o-s;if(n<=a)return s+n;n-=a}}function Xs(i,e){let t=0;for(let{from:n,to:r}of i.ranges){if(e<=r){t+=e-n;break}t+=r-n}return t/i.total}function hb(i,e){for(let t of i)if(e(t))return t}var Gu={toDOM(i){return i},fromDOM(i){return i},scale:1,eq(i){return i==this}},Jl=class i{constructor(e,t,n){let r=0,s=0,o=0;this.viewports=n.map(({from:a,to:l})=>{let h=t.lineAt(a,K.ByPos,e,0,0).top,c=t.lineAt(l,K.ByPos,e,0,0).bottom;return r+=c-h,{from:a,to:l,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-r)/(t.height-r);for(let a of this.viewports)a.domTop=o+(a.top-s)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),s=a.bottom}toDOM(e){for(let t=0,n=0,r=0;;t++){let s=tt.from==e.viewports[n].from&&t.to==e.viewports[n].to):!1}};function Zn(i,e){if(e.scale==1)return i;let t=e.toDOM(i.top),n=e.toDOM(i.bottom);return new yt(i.from,i.length,t,n-t,Array.isArray(i._content)?i._content.map(r=>Zn(r,e)):i._content)}var Ws=A.define({combine:i=>i.join(" ")}),Kl=A.define({combine:i=>i.indexOf(!0)>-1}),eh=et.newName(),ip=et.newName(),np=et.newName(),rp={"&light":"."+ip,"&dark":"."+np};function th(i,e,t){return new et(e,{finish(n){return/&/.test(n)?n.replace(/&\w*/,r=>{if(r=="&")return i;if(!t||!t[r])throw new RangeError(`Unsupported selector: ${r}`);return t[r]}):i+" "+n}})}var cb=th("."+eh,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},rp),Jn="\uFFFF",ih=class{constructor(e,t){this.points=e,this.text="",this.lineSeparator=t.facet(N.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Jn}readRange(e,t){if(!e)return this;let n=e.parentNode;for(let r=e;;){this.findPointBefore(n,r);let s=this.text.length;this.readNode(r);let o=r.nextSibling;if(o==t)break;let a=J.get(r),l=J.get(o);(a&&l?a.breakAfter:(a?a.breakAfter:Ys(r))||Ys(o)&&(r.nodeName!="BR"||r.cmIgnore)&&this.text.length>s)&&this.lineBreak(),r=o}return this.findPointBefore(n,t),this}readTextNode(e){let t=e.nodeValue;for(let n of this.points)n.node==e&&(n.pos=this.text.length+Math.min(n.offset,t.length));for(let n=0,r=this.lineSeparator?null:/\r\n?|\n/g;;){let s=-1,o=1,a;if(this.lineSeparator?(s=t.indexOf(this.lineSeparator,n),o=this.lineSeparator.length):(a=r.exec(t))&&(s=a.index,o=a[0].length),this.append(t.slice(n,s<0?t.length:s)),s<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);n=s+o}}readNode(e){if(e.cmIgnore)return;let t=J.get(e),n=t&&t.overrideDOMText;if(n!=null){this.findPointInside(e,n.length);for(let r=n.iter();!r.next().done;)r.lineBreak?this.lineBreak():this.append(r.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let n of this.points)n.node==e&&e.childNodes[n.offset]==t&&(n.pos=this.text.length)}findPointInside(e,t){for(let n of this.points)(e.nodeType==3?n.node==e:e.contains(n.node))&&(n.pos=this.text.length+(fb(e,n.node,n.offset)?t:0))}};function fb(i,e,t){for(;;){if(!e||t-1;let{impreciseHead:s,impreciseAnchor:o}=e.docView;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=e.docView.domBoundsAround(t,n,0))){let a=s||o?[]:pb(e),l=new ih(a,e.state);l.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=l.text,this.newSel=mb(a,this.bounds.from)}else{let a=e.observer.selectionRange,l=s&&s.node==a.focusNode&&s.offset==a.focusOffset||!El(e.contentDOM,a.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),h=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!El(e.contentDOM,a.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),c=e.viewport;if((Q.ios||Q.chrome)&&e.state.selection.main.empty&&l!=h&&(c.from>0||c.toDate.now()-100?i.inputState.lastKeyCode:-1;if(e.bounds){let{from:o,to:a}=e.bounds,l=r.from,h=null;(s===8||Q.android&&e.text.length=r.from&&t.to<=r.to&&(t.from!=r.from||t.to!=r.to)&&r.to-r.from-(t.to-t.from)<=4?t={from:r.from,to:r.to,insert:i.state.doc.slice(r.from,t.from).append(t.insert).append(i.state.doc.slice(t.to,r.to))}:(Q.mac||Q.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&i.contentDOM.getAttribute("autocorrect")=="off"?(n&&t.insert.length==2&&(n=S.single(n.main.anchor-1,n.main.head-1)),t={from:r.from,to:r.to,insert:W.of([" "])}):Q.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&i.lineWrapping&&(n&&(n=S.single(n.main.anchor-1,n.main.head-1)),t={from:r.from,to:r.to,insert:W.of([" "])}),t)return op(i,t,n,s);if(n&&!n.main.eq(r)){let o=!1,a="select";return i.inputState.lastSelectionTime>Date.now()-50&&(i.inputState.lastSelectionOrigin=="select"&&(o=!0),a=i.inputState.lastSelectionOrigin),i.dispatch({selection:n,scrollIntoView:o,userEvent:a}),!0}else return!1}function op(i,e,t,n=-1){if(Q.ios&&i.inputState.flushIOSKey(e))return!0;let r=i.state.selection.main;if(Q.android&&(e.to==r.to&&(e.from==r.from||e.from==r.from-1&&i.state.sliceDoc(e.from,r.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&an(i.contentDOM,"Enter",13)||(e.from==r.from-1&&e.to==r.to&&e.insert.length==0||n==8&&e.insert.lengthr.head)&&an(i.contentDOM,"Backspace",8)||e.from==r.from&&e.to==r.to+1&&e.insert.length==0&&an(i.contentDOM,"Delete",46)))return!0;let s=e.insert.toString();i.inputState.composing>=0&&i.inputState.composing++;let o,a=()=>o||(o=ub(i,e,t));return i.state.facet(Dd).some(l=>l(i,e.from,e.to,s,a))||i.dispatch(a()),!0}function ub(i,e,t){let n,r=i.state,s=r.selection.main;if(e.from>=s.from&&e.to<=s.to&&e.to-e.from>=(s.to-s.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&i.inputState.composing<0){let a=s.frome.to?r.sliceDoc(e.to,s.to):"";n=r.replaceSelection(i.state.toText(a+e.insert.sliceString(0,void 0,i.state.lineBreak)+l))}else{let a=r.changes(e),l=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&i.inputState.composing>=0&&e.to<=s.to&&e.to>=s.to-10){let h=i.state.sliceDoc(e.from,e.to),c,f=t&&zd(i,t.main.head);if(f){let m=e.insert.length-(e.to-e.from);c={from:f.from,to:f.to-m}}else c=i.state.doc.lineAt(s.head);let u=s.to-e.to,d=s.to-s.from;n=r.changeByRange(m=>{if(m.from==s.from&&m.to==s.to)return{changes:a,range:l||m.map(a)};let p=m.to-u,g=p-h.length;if(m.to-m.from!=d||i.state.sliceDoc(g,p)!=h||m.to>=c.from&&m.from<=c.to)return{range:m};let O=r.changes({from:g,to:p,insert:e.insert}),y=m.to-s.to;return{changes:O,range:l?S.range(Math.max(0,l.anchor+y),Math.max(0,l.head+y)):m.map(O)}})}else n={changes:a,selection:l&&r.selection.replaceRange(l)}}let o="input.type";return(i.composing||i.inputState.compositionPendingChange&&i.inputState.compositionEndedAt>Date.now()-50)&&(i.inputState.compositionPendingChange=!1,o+=".compose",i.inputState.compositionFirstChange&&(o+=".start",i.inputState.compositionFirstChange=!1)),r.update(n,{userEvent:o,scrollIntoView:!0})}function db(i,e,t,n){let r=Math.min(i.length,e.length),s=0;for(;s0&&a>0&&i.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(n=="end"){let l=Math.max(0,s-Math.min(o,a));t-=o+l-s}if(o=o?s-t:0;s-=l,a=s+(a-o),o=s}else if(a=a?s-t:0;s-=l,o=s+(o-a),a=s}return{from:s,toA:o,toB:a}}function pb(i){let e=[];if(i.root.activeElement!=i.contentDOM)return e;let{anchorNode:t,anchorOffset:n,focusNode:r,focusOffset:s}=i.observer.selectionRange;return t&&(e.push(new ro(t,n)),(r!=t||s!=n)&&e.push(new ro(r,s))),e}function mb(i,e){if(i.length==0)return null;let t=i[0].pos,n=i.length==2?i[1].pos:t;return t>-1&&n>-1?S.single(t+e,n+e):null}var gb={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Tl=Q.ie&&Q.ie_version<=11,rh=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new Al,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let n of t)this.queue.push(n);(Q.ie&&Q.ie_version<=11||Q.ios&&e.composing)&&t.some(n=>n.type=="childList"&&n.removedNodes.length||n.type=="characterData"&&n.oldValue.length>n.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&e.constructor.EDIT_CONTEXT!==!1&&!(Q.chrome&&Q.chrome_version<126)&&(this.editContext=new sh(e),e.state.facet(Ht)&&(e.contentDOM.editContext=this.editContext.editContext)),Tl&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){e.type=="change"&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,n)=>t!=e[n]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:n}=this,r=this.selectionRange;if(n.state.facet(Ht)?n.root.activeElement!=this.dom:!js(n.dom,r))return;let s=r.anchorNode&&n.docView.nearest(r.anchorNode);if(s&&s.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(Q.ie&&Q.ie_version<=11||Q.android&&Q.chrome)&&!n.state.selection.main.empty&&r.focusNode&&er(r.focusNode,r.focusOffset,r.anchorNode,r.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=ar(e.root);if(!t)return!1;let n=Q.safari&&e.root.nodeType==11&&ay(this.dom.ownerDocument)==this.dom&&Ob(this.view,t)||t;if(!n||this.selectionRange.eq(n))return!1;let r=js(this.dom,n);return r&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let s=this.delayedAndroidKey;s&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=s.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&s.force&&an(this.dom,s.key,s.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(r)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,n=-1,r=!1;for(let s of e){let o=this.readMutation(s);o&&(o.typeOver&&(r=!0),t==-1?{from:t,to:n}=o:(t=Math.min(o.from,t),n=Math.max(o.to,n)))}return{from:t,to:n,typeOver:r}}readChange(){let{from:e,to:t,typeOver:n}=this.processRecords(),r=this.selectionChanged&&js(this.dom,this.selectionRange);if(e<0&&!r)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let s=new nh(this.view,e,t,n);return this.view.docView.domChanged={newSel:s.newSel?s.newSel.main:null},s}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let n=this.view.state,r=sp(this.view,t);return this.view.state==n&&(t.domChanged||t.newSel&&!t.newSel.main.eq(this.view.state.selection.main))&&this.view.update([]),r}readMutation(e){let t=this.view.docView.nearest(e.target);if(!t||t.ignoreMutation(e))return null;if(t.markDirty(e.type=="attributes"),e.type=="attributes"&&(t.flags|=4),e.type=="childList"){let n=Yu(t,e.previousSibling||e.target.previousSibling,-1),r=Yu(t,e.nextSibling||e.target.nextSibling,1);return{from:n?t.posAfter(n):t.posAtStart,to:r?t.posBefore(r):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener("change",this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener("change",this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Ht)!=e.state.facet(Ht)&&(e.view.contentDOM.editContext=e.state.facet(Ht)?this.editContext.editContext:null))}destroy(){var e,t,n;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(n=this.resizeScroll)===null||n===void 0||n.disconnect();for(let r of this.scrollTargets)r.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}};function Yu(i,e,t){for(;e;){let n=J.get(e);if(n&&n.parent==i)return n;let r=e.parentNode;e=r!=i.dom?r:t>0?e.nextSibling:e.previousSibling}return null}function Zu(i,e){let t=e.startContainer,n=e.startOffset,r=e.endContainer,s=e.endOffset,o=i.docView.domAtPos(i.state.selection.main.anchor);return er(o.node,o.offset,r,s)&&([t,n,r,s]=[r,s,t,n]),{anchorNode:t,anchorOffset:n,focusNode:r,focusOffset:s}}function Ob(i,e){if(e.getComposedRanges){let r=e.getComposedRanges(i.root)[0];if(r)return Zu(i,r)}let t=null;function n(r){r.preventDefault(),r.stopImmediatePropagation(),t=r.getTargetRanges()[0]}return i.contentDOM.addEventListener("beforeinput",n,!0),i.dom.ownerDocument.execCommand("indent"),i.contentDOM.removeEventListener("beforeinput",n,!0),t?Zu(i,t):null}var sh=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});t.addEventListener("textupdate",n=>{let{anchor:r}=e.state.selection.main,s={from:this.toEditorPos(n.updateRangeStart),to:this.toEditorPos(n.updateRangeEnd),insert:W.of(n.text.split(` +`))};s.from==this.from&&rthis.to&&(s.to=r),!(s.from==s.to&&!s.insert.length)&&(this.pendingContextChange=s,op(e,s,S.single(this.toEditorPos(n.selectionStart),this.toEditorPos(n.selectionEnd))),this.pendingContextChange&&this.revertPending(e.state))}),t.addEventListener("characterboundsupdate",n=>{let r=[],s=null;for(let o=this.toEditorPos(n.rangeStart),a=this.toEditorPos(n.rangeEnd);o{let r=[];for(let s of n.getTextFormats()){let o=s.underlineStyle,a=s.underlineThickness;if(o!="None"&&a!="None"){let l=`text-decoration: underline ${o=="Dashed"?"dashed ":o=="Squiggle"?"wavy ":""}${a=="Thin"?1:2}px`;r.push(M.mark({attributes:{style:l}}).range(this.toEditorPos(s.rangeStart),this.toEditorPos(s.rangeEnd)))}}e.dispatch({effects:Bd.of(M.set(r))})}),t.addEventListener("compositionstart",()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)}),t.addEventListener("compositionend",()=>{e.inputState.composing=-1,e.inputState.compositionFirstChange=null}),this.measureReq={read:n=>{this.editContext.updateControlBounds(n.contentDOM.getBoundingClientRect());let r=ar(n.root);r&&r.rangeCount&&this.editContext.updateSelectionBounds(r.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,n=!1,r=this.pendingContextChange;return e.changes.iterChanges((s,o,a,l,h)=>{if(n)return;let c=h.length-(o-s);if(r&&o>=r.to)if(r.from==s&&r.to==o&&r.insert.eq(h)){r=this.pendingContextChange=null,t+=c;return}else r=null,this.revertPending(e.state);if(s+=t,o+=t,o<=this.from)this.from+=c,this.to+=c;else if(sthis.to||this.to-this.from+h.length>3e4){n=!0;return}this.editContext.updateText(this.toContextPos(s),this.toContextPos(o),h.toString()),this.to+=c}t+=c}),r&&!n&&this.revertPending(e.state),!n}update(e){!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.resetRange(e.state),this.editContext.updateText(0,this.editContext.text.length,e.state.doc.sliceString(this.from,this.to)),this.setSelection(e.state)):(e.docChanged||e.selectionSet)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.to+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,n=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),r=this.toContextPos(t.head);(this.editContext.selectionStart!=n||this.editContext.selectionEnd!=r)&&this.editContext.updateSelection(n,r)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e){return e+this.from}toContextPos(e){return e-this.from}},E=class i{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:t}=e;this.dispatchTransactions=e.dispatchTransactions||t&&(n=>n.forEach(r=>t(r,this)))||(n=>this.update(n)),this.dispatch=this.dispatch.bind(this),this._root=e.root||fy(e.parent)||document,this.viewState=new no(e.state||N.create(e)),e.scrollTo&&e.scrollTo.is(Vs)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Gn).map(n=>new nr(n));for(let n of this.plugins)n.update(this);this.observer=new rh(this),this.inputState=new Nl(this),this.inputState.ensureHandlers(this.plugins),this.docView=new eo(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure()}dispatch(...e){let t=e.length==1&&e[0]instanceof fe?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,n=!1,r,s=this.state;for(let u of e){if(u.startState!=s)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");s=u.state}if(this.destroyed){this.viewState.state=s;return}let o=this.hasFocus,a=0,l=null;e.some(u=>u.annotation(Kd))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=ep(s,o),l||(a=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(s.doc)||!this.state.selection.eq(s.selection))&&(c=null)):this.observer.clear(),s.facet(N.phrases)!=this.state.facet(N.phrases))return this.setState(s);r=Ks.create(this,s,e),r.flags|=a;let f=this.viewState.scrollTarget;try{this.updateState=2;for(let u of e){if(f&&(f=f.map(u.changes)),u.scrollIntoView){let{main:d}=u.state.selection;f=new ir(d.empty?d:S.cursor(d.head,d.head>d.anchor?-1:1))}for(let d of u.effects)d.is(Vs)&&(f=d.value.clip(this.state))}this.viewState.update(r,f),this.bidiCache=so.update(this.bidiCache,r.changes),r.empty||(this.updatePlugins(r),this.inputState.update(r)),t=this.docView.update(r),this.state.facet(Yn)!=this.styleModules&&this.mountStyles(),n=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(r.startState.facet(Ws)!=r.state.facet(Ws)&&(this.viewState.mustMeasureContent=!0),(t||n||f||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!r.empty)for(let u of this.state.facet(Xl))try{u(r)}catch(d){we(this.state,d,"update listener")}(l||c)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),c&&!sp(this,c)&&h.force&&an(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let n of this.plugins)n.destroy(this);this.viewState=new no(e),this.plugins=e.facet(Gn).map(n=>new nr(n)),this.pluginMap.clear();for(let n of this.plugins)n.update(this);this.docView.destroy(),this.docView=new eo(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Gn),n=e.state.facet(Gn);if(t!=n){let r=[];for(let s of n){let o=t.indexOf(s);if(o<0)r.push(new nr(s));else{let a=this.plugins[o];a.mustUpdate=e,r.push(a)}}for(let s of this.plugins)s.mustUpdate!=e&&s.destroy(this);this.plugins=r,this.pluginMap.clear()}else for(let r of this.plugins)r.mustUpdate=e;for(let r=0;r-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,n=this.scrollDOM,r=n.scrollTop*this.scaleY,{scrollAnchorPos:s,scrollAnchorHeight:o}=this.viewState;Math.abs(r-this.viewState.scrollTop)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(pd(n))s=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(r);s=d.from,o=d.top}this.updateState=1;let l=this.viewState.measure(this);if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let h=[];l&4||([this.measureRequests,h]=[h,this.measureRequests]);let c=h.map(d=>{try{return d.read(this)}catch(m){return we(this.state,m),Ju}}),f=Ks.create(this,this.state,[]),u=!1;f.flags|=l,t?t.flags|=l:t=f,this.updateState=2,f.empty||(this.updatePlugins(f),this.inputState.update(f),this.updateAttrs(),u=this.docView.update(f),u&&this.docViewUpdate());for(let d=0;d1||m<-1){r=r+m,n.scrollTop=r/this.scaleY,o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Xl))a(t)}get themeClasses(){return eh+" "+(this.state.facet(Kl)?np:ip)+" "+this.state.facet(Ws)}updateAttrs(){let e=Ku(this,Xd,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(Ht)?"true":"false",class:"cm-content",style:`${Q.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Ku(this,vh,t);let n=this.observer.ignore(()=>{let r=$l(this.contentDOM,this.contentAttrs,t),s=$l(this.dom,this.editorAttrs,e);return r||s});return this.editorAttrs=e,this.contentAttrs=t,n}showAnnouncements(e){let t=!0;for(let n of e)for(let r of n.effects)if(r.is(i.announce)){t&&(this.announceDOM.textContent=""),t=!1;let s=this.announceDOM.appendChild(document.createElement("div"));s.textContent=r.value}}mountStyles(){this.styleModules=this.state.facet(Yn);let e=this.state.facet(i.cspNonce);et.mount(this.root,this.styleModules.concat(cb).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;tn.spec==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,n){return Sl(this,e,Lu(this,e,t,n))}moveByGroup(e,t){return Sl(this,e,Lu(this,e,t,n=>Wy(this,e.head,n)))}visualLineSide(e,t){let n=this.bidiSpans(e),r=this.textDirectionAt(e.from),s=n[t?n.length-1:0];return S.cursor(s.side(t,r)+e.from,s.forward(!t,r)?1:-1)}moveToLineBoundary(e,t,n=!0){return Xy(this,e,t,n)}moveVertically(e,t,n){return Sl(this,e,Iy(this,e,t,n))}domAtPos(e){return this.docView.domAtPos(e)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){return this.readMeasured(),Ud(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let n=this.docView.coordsAt(e,t);if(!n||n.left==n.right)return n;let r=this.state.doc.lineAt(e),s=this.bidiSpans(r),o=s[bt.find(s,e-r.from,-1,t)];return yh(n,o.dir==H.LTR==t>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Vd)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>yb)return Rd(e.length);let t=this.textDirectionAt(e.from),n;for(let s of this.bidiCache)if(s.from==e.from&&s.dir==t&&(s.fresh||Cd(s.isolates,n=Mu(this,e))))return s.order;n||(n=Mu(this,e));let r=Sy(e.text,t,n);return this.bidiCache.push(new so(e.from,e.to,t,n,!0,r)),r}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||Q.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{ud(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return Vs.of(new ir(typeof e=="number"?S.cursor(e):e,t.y,t.x,t.yMargin,t.xMargin))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return Vs.of(new ir(S.cursor(n.from),"start","start",n.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return re.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return re.define(()=>({}),{eventObservers:e})}static theme(e,t){let n=et.newName(),r=[Ws.of(n),Yn.of(th(`.${n}`,e))];return t&&t.dark&&r.push(Kl.of(!0)),r}static baseTheme(e){return Qe.lowest(Yn.of(th("."+eh,e,rp)))}static findFromDOM(e){var t;let n=e.querySelector(".cm-content"),r=n&&J.get(n)||J.get(e);return((t=r?.rootView)===null||t===void 0?void 0:t.view)||null}};E.styleModule=Yn;E.inputHandler=Dd;E.scrollHandler=qd;E.focusChangeEffect=$d;E.perLineTextDirection=Vd;E.exceptionSink=_d;E.updateListener=Xl;E.editable=Ht;E.mouseSelectionStyle=Md;E.dragMovesSelection=Qd;E.clickAddsSelectionRange=Ad;E.decorations=dr;E.outerDecorations=Wd;E.atomicRanges=xh;E.bidiIsolatedRanges=Id;E.scrollMargins=Nd;E.darkTheme=Kl;E.cspNonce=A.define({combine:i=>i.length?i[0]:""});E.contentAttributes=vh;E.editorAttributes=Xd;E.lineWrapping=E.contentAttributes.of({class:"cm-lineWrapping"});E.announce=_.define();var yb=4096,Ju={},so=class i{constructor(e,t,n,r,s,o){this.from=e,this.to=t,this.dir=n,this.isolates=r,this.fresh=s,this.order=o}static update(e,t){if(t.empty&&!e.some(s=>s.fresh))return e;let n=[],r=e.length?e[e.length-1].dir:H.LTR;for(let s=Math.max(0,e.length-10);s=0;r--){let s=n[r],o=typeof s=="function"?s(i):s;o&&Dl(o,t)}return t}var bb=Q.mac?"mac":Q.windows?"win":Q.linux?"linux":"key";function wb(i,e){let t=i.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let r,s,o,a;for(let l=0;ln.concat(r),[]))),t}function lp(i,e,t){return hp(ap(i.state),e,i,t)}var Gt=null,xb=4e3;function kb(i,e=bb){let t=Object.create(null),n=Object.create(null),r=(o,a)=>{let l=n[o];if(l==null)n[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},s=(o,a,l,h,c)=>{var f,u;let d=t[o]||(t[o]=Object.create(null)),m=a.split(/ (?!$)/).map(O=>wb(O,e));for(let O=1;O{let x=Gt={view:v,prefix:y,scope:o};return setTimeout(()=>{Gt==x&&(Gt=null)},xb),!0}]})}let p=m.join(" ");r(p,!1);let g=d[p]||(d[p]={preventDefault:!1,stopPropagation:!1,run:((u=(f=d._any)===null||f===void 0?void 0:f.run)===null||u===void 0?void 0:u.slice())||[]});l&&g.run.push(l),h&&(g.preventDefault=!0),c&&(g.stopPropagation=!0)};for(let o of i){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of a){let c=t[h]||(t[h]=Object.create(null));c._any||(c._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:f}=o;for(let u in c)c[u].run.push(d=>f(d,oh))}let l=o[e]||o.key;if(l)for(let h of a)s(h,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&s(h,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}var oh=null;function hp(i,e,t,n){oh=e;let r=Su(e),s=ce(r,0),o=Ee(s)==r.length&&r!=" ",a="",l=!1,h=!1,c=!1;Gt&&Gt.view==t&&Gt.scope==n&&(a=Gt.prefix+" ",Hd.indexOf(e.keyCode)<0&&(h=!0,Gt=null));let f=new Set,u=g=>{if(g){for(let O of g.run)if(!f.has(O)&&(f.add(O),O(t)))return g.stopPropagation&&(c=!0),!0;g.preventDefault&&(g.stopPropagation&&(c=!0),h=!0)}return!1},d=i[n],m,p;return d&&(u(d[a+Is(r,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(Q.windows&&e.ctrlKey&&e.altKey)&&(m=Vt[e.keyCode])&&m!=r?(u(d[a+Is(m,e,!0)])||e.shiftKey&&(p=tn[e.keyCode])!=r&&p!=m&&u(d[a+Is(p,e,!1)]))&&(l=!0):o&&e.shiftKey&&u(d[a+Is(r,e,!0)])&&(l=!0),!l&&u(d._any)&&(l=!0)),h&&(l=!0),l&&c&&e.stopPropagation(),oh=null,l}var pr=class i{constructor(e,t,n,r,s){this.className=e,this.left=t,this.top=n,this.width=r,this.height=s}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,n){if(n.empty){let r=e.coordsAtPos(n.head,n.assoc||1);if(!r)return[];let s=cp(e);return[new i(t,r.left-s.left,r.top-s.top,null,r.bottom-r.top)]}else return Sb(e,t,n)}};function cp(i){let e=i.scrollDOM.getBoundingClientRect();return{left:(i.textDirection==H.LTR?e.left:e.right-i.scrollDOM.clientWidth*i.scaleX)-i.scrollDOM.scrollLeft*i.scaleX,top:e.top-i.scrollDOM.scrollTop*i.scaleY}}function td(i,e,t,n){let r=i.coordsAtPos(e,t*2);if(!r)return n;let s=i.dom.getBoundingClientRect(),o=(r.top+r.bottom)/2,a=i.posAtCoords({x:s.left+1,y:o}),l=i.posAtCoords({x:s.right-1,y:o});return a==null||l==null?n:{from:Math.max(n.from,Math.min(a,l)),to:Math.min(n.to,Math.max(a,l))}}function Sb(i,e,t){if(t.to<=i.viewport.from||t.from>=i.viewport.to)return[];let n=Math.max(t.from,i.viewport.from),r=Math.min(t.to,i.viewport.to),s=i.textDirection==H.LTR,o=i.contentDOM,a=o.getBoundingClientRect(),l=cp(i),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),f=a.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),u=a.right-(c?parseInt(c.paddingRight):0),d=Il(i,n),m=Il(i,r),p=d.type==_e.Text?d:null,g=m.type==_e.Text?m:null;if(p&&(i.lineWrapping||d.widgetLineBreaks)&&(p=td(i,n,1,p)),g&&(i.lineWrapping||m.widgetLineBreaks)&&(g=td(i,r,-1,g)),p&&g&&p.from==g.from&&p.to==g.to)return y(v(t.from,t.to,p));{let w=p?v(t.from,null,p):x(d,!1),P=g?v(null,t.to,g):x(m,!0),C=[];return(p||d).to<(g||m).from-(p&&g?1:0)||d.widgetLineBreaks>1&&w.bottom+i.defaultLineHeight/2q&&I.from=De)break;pe>ie&&X(Math.max(Ye,ie),w==null&&Ye<=q,Math.min(pe,De),P==null&&pe>=G,We.dir)}if(ie=$e.to+1,ie>=De)break}return V.length==0&&X(q,w==null,G,P==null,i.textDirection),{top:D,bottom:B,horizontal:V}}function x(w,P){let C=a.top+(P?w.top:w.bottom);return{top:C,bottom:C,horizontal:[]}}}function Tb(i,e){return i.constructor==e.constructor&&i.eq(e)}var ah=class{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(Fs)!=e.state.facet(Fs)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,n=e.facet(Fs);for(;t!Tb(t,this.drawn[n]))){let t=this.dom.firstChild,n=0;for(let r of e)r.update&&t&&r.constructor&&this.drawn[n].constructor&&r.update(t,this.drawn[n])?(t=t.nextSibling,n++):this.dom.insertBefore(r.draw(),t);for(;t;){let r=t.nextSibling;t.remove(),t=r}this.drawn=e}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},Fs=A.define();function fp(i){return[re.define(e=>new ah(e,i)),Fs.of(i)]}var up=!Q.ios,mr=A.define({combine(i){return Te(i,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function dp(i={}){return[mr.of(i),Pb,Cb,Rb,Ld.of(!0)]}function pp(i){return i.startState.facet(mr)!=i.state.facet(mr)}var Pb=fp({above:!0,markers(i){let{state:e}=i,t=e.facet(mr),n=[];for(let r of e.selection.ranges){let s=r==e.selection.main;if(r.empty?!s||up:t.drawRangeCursor){let o=s?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=r.empty?r:S.cursor(r.head,r.head>r.anchor?-1:1);for(let l of pr.forRange(i,o,a))n.push(l)}}return n},update(i,e){i.transactions.some(n=>n.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=pp(i);return t&&id(i.state,e),i.docChanged||i.selectionSet||t},mount(i,e){id(e.state,i)},class:"cm-cursorLayer"});function id(i,e){e.style.animationDuration=i.facet(mr).cursorBlinkRate+"ms"}var Cb=fp({above:!1,markers(i){return i.state.selection.ranges.map(e=>e.empty?[]:pr.forRange(i,"cm-selectionBackground",e)).reduce((e,t)=>e.concat(t))},update(i,e){return i.docChanged||i.selectionSet||i.viewportChanged||pp(i)},class:"cm-selectionLayer"}),lh={".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"}},".cm-content":{"& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}};up&&(lh[".cm-line"].caretColor=lh[".cm-content"].caretColor="transparent !important");var Rb=Qe.highest(E.theme(lh)),mp=_.define({map(i,e){return i==null?null:e.mapPos(i)}}),Kn=te.define({create(){return null},update(i,e){return i!=null&&(i=e.changes.mapPos(i)),e.effects.reduce((t,n)=>n.is(mp)?n.value:t,i)}}),Eb=re.fromClass(class{constructor(i){this.view=i,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(i){var e;let t=i.state.field(Kn);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(i.startState.field(Kn)!=t||i.docChanged||i.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:i}=this,e=i.state.field(Kn),t=e!=null&&i.coordsAtPos(e);if(!t)return null;let n=i.scrollDOM.getBoundingClientRect();return{left:t.left-n.left+i.scrollDOM.scrollLeft*i.scaleX,top:t.top-n.top+i.scrollDOM.scrollTop*i.scaleY,height:t.bottom-t.top}}drawCursor(i){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;i?(this.cursor.style.left=i.left/e+"px",this.cursor.style.top=i.top/t+"px",this.cursor.style.height=i.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(i){this.view.state.field(Kn)!=i&&this.view.dispatch({effects:mp.of(i)})}},{eventObservers:{dragover(i){this.setDropPos(this.view.posAtCoords({x:i.clientX,y:i.clientY}))},dragleave(i){(i.target==this.view.contentDOM||!this.view.contentDOM.contains(i.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function gp(){return[Kn,Eb]}function nd(i,e,t,n,r){e.lastIndex=0;for(let s=i.iterRange(t,n),o=t,a;!s.next().done;o+=s.value.length)if(!s.lineBreak)for(;a=e.exec(s.value);)r(o+a.index,a)}function Ab(i,e){let t=i.visibleRanges;if(t.length==1&&t[0].from==i.viewport.from&&t[0].to==i.viewport.to)return t;let n=[];for(let{from:r,to:s}of t)r=Math.max(i.state.doc.lineAt(r).from,r-e),s=Math.min(i.state.doc.lineAt(s).to,s+e),n.length&&n[n.length-1].to>=r?n[n.length-1].to=s:n.push({from:r,to:s});return n}var hh=class{constructor(e){let{regexp:t,decoration:n,decorate:r,boundary:s,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,r)this.addMatch=(a,l,h,c)=>r(c,h,h+a[0].length,a,l);else if(typeof n=="function")this.addMatch=(a,l,h,c)=>{let f=n(a,l,h);f&&c(h,h+a[0].length,f)};else if(n)this.addMatch=(a,l,h,c)=>c(h,h+a[0].length,n);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=s,this.maxLength=o}createDeco(e){let t=new lt,n=t.add.bind(t);for(let{from:r,to:s}of Ab(e,this.maxLength))nd(e.state.doc,this.regexp,r,s,(o,a)=>this.addMatch(a,e,o,n));return t.finish()}updateDeco(e,t){let n=1e9,r=-1;return e.docChanged&&e.changes.iterChanges((s,o,a,l)=>{l>e.view.viewport.from&&a1e3?this.createDeco(e.view):r>-1?this.updateRange(e.view,t.map(e.changes),n,r):t}updateRange(e,t,n,r){for(let s of e.visibleRanges){let o=Math.max(s.from,n),a=Math.min(s.to,r);if(a>o){let l=e.state.doc.lineAt(o),h=l.tol.from;o--)if(this.boundary.test(l.text[o-1-l.from])){c=o;break}for(;au.push(O.range(p,g));if(l==h)for(this.regexp.lastIndex=c-l.from;(d=this.regexp.exec(l.text))&&d.indexthis.addMatch(g,e,p,m));t=t.update({filterFrom:c,filterTo:f,filter:(p,g)=>pf,add:u})}}return t}},ch=/x/.unicode!=null?"gu":"g",Qb=new RegExp(`[\0-\b +-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,ch),Mb={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"},Pl=null;function _b(){var i;if(Pl==null&&typeof document<"u"&&document.body){let e=document.body.style;Pl=((i=e.tabSize)!==null&&i!==void 0?i:e.MozTabSize)!=null}return Pl||!1}var Hs=A.define({combine(i){let e=Te(i,{render:null,specialChars:Qb,addSpecialChars:null});return(e.replaceTabs=!_b())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,ch)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,ch)),e}});function Op(i={}){return[Hs.of(i),Db()]}var rd=null;function Db(){return rd||(rd=re.fromClass(class{constructor(i){this.view=i,this.decorations=M.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(i.state.facet(Hs)),this.decorations=this.decorator.createDeco(i)}makeDecorator(i){return new hh({regexp:i.specialChars,decoration:(e,t,n)=>{let{doc:r}=t.state,s=ce(e[0],0);if(s==9){let o=r.lineAt(n),a=t.state.tabSize,l=$t(o.text,a,n-o.from);return M.replace({widget:new uh((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[s]||(this.decorationCache[s]=M.replace({widget:new fh(i,s)}))},boundary:i.replaceTabs?void 0:/[^]/})}update(i){let e=i.state.facet(Hs);i.startState.facet(Hs)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(i.view)):this.decorations=this.decorator.updateDeco(i,this.decorations)}},{decorations:i=>i.decorations}))}var $b="\u2022";function Vb(i){return i>=32?$b:i==10?"\u2424":String.fromCharCode(9216+i)}var fh=class extends Be{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=Vb(this.code),n=e.state.phrase("Control character")+" "+(Mb[this.code]||"0x"+this.code.toString(16)),r=this.options.render&&this.options.render(this.code,n,t);if(r)return r;let s=document.createElement("span");return s.textContent=t,s.title=n,s.setAttribute("aria-label",n),s.className="cm-specialChar",s}ignoreEvent(){return!1}},uh=class extends Be{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}};function yp(){return qb}var Lb=M.line({class:"cm-activeLine"}),qb=re.fromClass(class{constructor(i){this.decorations=this.getDeco(i)}update(i){(i.docChanged||i.selectionSet)&&(this.decorations=this.getDeco(i.view))}getDeco(i){let e=-1,t=[];for(let n of i.state.selection.ranges){let r=i.lineBlockAt(n.head);r.from>e&&(t.push(Lb.range(r.from)),e=r.from)}return M.set(t)}},{decorations:i=>i.decorations});var dh=2e3;function Bb(i,e,t){let n=Math.min(e.line,t.line),r=Math.max(e.line,t.line),s=[];if(e.off>dh||t.off>dh||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=n;l<=r;l++){let h=i.doc.line(l);h.length<=a&&s.push(S.range(h.from+o,h.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=n;l<=r;l++){let h=i.doc.line(l),c=_s(h.text,o,i.tabSize,!0);if(c<0)s.push(S.cursor(h.to));else{let f=_s(h.text,a,i.tabSize);s.push(S.range(h.from+c,h.from+f))}}}return s}function Xb(i,e){let t=i.coordsAtPos(i.viewport.from);return t?Math.round(Math.abs((t.left-e)/i.defaultCharacterWidth)):-1}function sd(i,e){let t=i.posAtCoords({x:e.clientX,y:e.clientY},!1),n=i.state.doc.lineAt(t),r=t-n.from,s=r>dh?-1:r==n.length?Xb(i,e.clientX):$t(n.text,i.state.tabSize,t-n.from);return{line:n.number,col:s,off:r}}function Wb(i,e){let t=sd(i,e),n=i.state.selection;return t?{update(r){if(r.docChanged){let s=r.changes.mapPos(r.startState.doc.line(t.line).from),o=r.state.doc.lineAt(s);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},n=n.map(r.changes)}},get(r,s,o){let a=sd(i,r);if(!a)return n;let l=Bb(i.state,t,a);return l.length?o?S.create(l.concat(n.ranges)):S.create(l):n}}:null}function bp(i){let e=i?.eventFilter||(t=>t.altKey&&t.button==0);return E.mouseSelectionStyle.of((t,n)=>e(n)?Wb(t,n):null)}var Ib={Alt:[18,i=>!!i.altKey],Control:[17,i=>!!i.ctrlKey],Shift:[16,i=>!!i.shiftKey],Meta:[91,i=>!!i.metaKey]},Nb={style:"cursor: crosshair"};function wp(i={}){let[e,t]=Ib[i.key||"Alt"],n=re.fromClass(class{constructor(r){this.view=r,this.isDown=!1}set(r){this.isDown!=r&&(this.isDown=r,this.view.update([]))}},{eventObservers:{keydown(r){this.set(r.keyCode==e||t(r))},keyup(r){(r.keyCode==e||!t(r))&&this.set(!1)},mousemove(r){this.set(t(r))}}});return[n,E.contentAttributes.of(r=>{var s;return!((s=r.plugin(n))===null||s===void 0)&&s.isDown?Nb:null})]}var Hn="-10000px",oo=class{constructor(e,t,n,r){this.facet=t,this.createTooltipView=n,this.removeTooltipView=r,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let s=null;this.tooltipViews=this.tooltips.map(o=>s=n(o,s))}update(e,t){var n;let r=e.state.facet(this.facet),s=r.filter(l=>l);if(r===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;lt[h]=l),t.length=a.length),this.input=r,this.tooltips=s,this.tooltipViews=o,!0}};function jb(i){let{win:e}=i;return{top:0,left:0,bottom:e.innerHeight,right:e.innerWidth}}var Cl=A.define({combine:i=>{var e,t,n;return{position:Q.ios?"absolute":((e=i.find(r=>r.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=i.find(r=>r.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((n=i.find(r=>r.tooltipSpace))===null||n===void 0?void 0:n.tooltipSpace)||jb}}}),od=new WeakMap,kh=re.fromClass(class{constructor(i){this.view=i,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=i.state.facet(Cl);this.position=e.position,this.parent=e.parent,this.classes=i.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new oo(i,gr,(t,n)=>this.createTooltip(t,n),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),i.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let i of this.manager.tooltipViews)this.intersectionObserver.observe(i.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(i){i.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(i,this.above);e&&this.observeIntersection();let t=e||i.geometryChanged,n=i.state.facet(Cl);if(n.position!=this.position&&!this.madeAbsolute){this.position=n.position;for(let r of this.manager.tooltipViews)r.dom.style.position=this.position;t=!0}if(n.parent!=this.parent){this.parent&&this.container.remove(),this.parent=n.parent,this.createContainer();for(let r of this.manager.tooltipViews)this.container.appendChild(r.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(i,e){let t=i.create(this.view),n=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),i.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let r=document.createElement("div");r.className="cm-tooltip-arrow",t.dom.appendChild(r)}return t.dom.style.position=this.position,t.dom.style.top=Hn,t.dom.style.left="0px",this.container.insertBefore(t.dom,n),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var i,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let n of this.manager.tooltipViews)n.dom.remove(),(i=n.destroy)===null||i===void 0||i.call(n);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let i=this.view.dom.getBoundingClientRect(),e=1,t=1,n=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(Q.gecko)n=r.offsetParent!=this.container.ownerDocument.body;else if(r.style.top==Hn&&r.style.left=="0px"){let s=r.getBoundingClientRect();n=Math.abs(s.top+1e4)>1||Math.abs(s.left)>1}}if(n||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(e=r.width/this.parent.offsetWidth,t=r.height/this.parent.offsetHeight)}else({scaleX:e,scaleY:t}=this.view.viewState);return{editor:i,parent:this.parent?this.container.getBoundingClientRect():i,pos:this.manager.tooltips.map((r,s)=>{let o=this.manager.tooltipViews[s];return o.getCoords?o.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Cl).tooltipSpace(this.view),scaleX:e,scaleY:t,makeAbsolute:n}}writeMeasure(i){var e;if(i.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{editor:t,space:n,scaleX:r,scaleY:s}=i,o=[];for(let a=0;a=Math.min(t.bottom,n.bottom)||f.rightMath.min(t.right,n.right)+.1){c.style.top=Hn;continue}let d=l.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,m=d?7:0,p=u.right-u.left,g=(e=od.get(h))!==null&&e!==void 0?e:u.bottom-u.top,O=h.offset||Ub,y=this.view.textDirection==H.LTR,v=u.width>n.right-n.left?y?n.left:n.right-u.width:y?Math.min(f.left-(d?14:0)+O.x,n.right-p):Math.max(n.left,f.left-p+(d?14:0)-O.x),x=this.above[a];!l.strictSide&&(x?f.top-(u.bottom-u.top)-O.yn.bottom)&&x==n.bottom-f.bottom>f.top-n.top&&(x=this.above[a]=!x);let w=(x?f.top-n.top:n.bottom-f.bottom)-m;if(wv&&D.topP&&(P=x?D.top-g-2-m:D.bottom+m+2);if(this.position=="absolute"?(c.style.top=(P-i.parent.top)/s+"px",c.style.left=(v-i.parent.left)/r+"px"):(c.style.top=P/s+"px",c.style.left=v/r+"px"),d){let D=f.left+(y?O.x:-O.x)-(v+14-7);d.style.left=D/r+"px"}h.overlap!==!0&&o.push({left:v,top:P,right:C,bottom:P+g}),c.classList.toggle("cm-tooltip-above",x),c.classList.toggle("cm-tooltip-below",!x),h.positioned&&h.positioned(i.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let i of this.manager.tooltipViews)i.dom.style.top=Hn}},{eventObservers:{scroll(){this.maybeMeasure()}}}),zb=E.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),Ub={x:0,y:0},gr=A.define({enables:[kh,zb]}),ao=A.define({combine:i=>i.reduce((e,t)=>e.concat(t),[])}),lo=class i{static create(e){return new i(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new oo(e,ao,(t,n)=>this.createHostedView(t,n),t=>t.dom.remove())}createHostedView(e,t){let n=e.create(this.view);return n.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(n.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&n.mount&&n.mount(this.view),n}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let n of this.manager.tooltipViews){let r=n[e];if(r!==void 0){if(t===void 0)t=r;else if(t!==r)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}},Fb=gr.compute([ao],i=>{let e=i.facet(ao);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var n;return(n=t.end)!==null&&n!==void 0?n:t.pos})),create:lo.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),ph=class{constructor(e,t,n,r,s){this.view=e,this.source=t,this.field=n,this.setHover=r,this.hoverTime=s,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;ea.bottom||t.xa.right+e.defaultCharacterWidth)return;let l=e.bidiSpans(e.state.doc.lineAt(r)).find(c=>c.from<=r&&c.to>=r),h=l&&l.dir==H.RTL?-1:1;s=t.x{this.pending==a&&(this.pending=null,l&&!(Array.isArray(l)&&!l.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(l)?l:[l])}))},l=>we(e.state,l,"hover tooltip"))}else o&&!(Array.isArray(o)&&!o.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(o)?o:[o])})}get tooltip(){let e=this.view.plugin(kh),t=e?e.manager.tooltips.findIndex(n=>n.create==lo.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,n;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:r,tooltip:s}=this;if(r.length&&s&&!Hb(s.dom,e)||this.pending){let{pos:o}=r[0]||this.pending,a=(n=(t=r[0])===null||t===void 0?void 0:t.end)!==null&&n!==void 0?n:o;(o==a?this.view.posAtCoords(this.lastMove)!=o:!Gb(this.view,o,a,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length){let{tooltip:n}=this;n&&n.dom.contains(e.relatedTarget)?this.watchTooltipLeave(n.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=n=>{e.removeEventListener("mouseleave",t),this.active.length&&!this.view.dom.contains(n.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}},Ns=4;function Hb(i,e){let t=i.getBoundingClientRect();return e.clientX>=t.left-Ns&&e.clientX<=t.right+Ns&&e.clientY>=t.top-Ns&&e.clientY<=t.bottom+Ns}function Gb(i,e,t,n,r,s){let o=i.scrollDOM.getBoundingClientRect(),a=i.documentTop+i.documentPadding.top+i.contentHeight;if(o.left>n||o.rightr||Math.min(o.bottom,a)=e&&l<=t}function vp(i,e={}){let t=_.define(),n=te.define({create(){return[]},update(r,s){if(r.length&&(e.hideOnChange&&(s.docChanged||s.selection)?r=[]:e.hideOn&&(r=r.filter(o=>!e.hideOn(s,o))),s.docChanged)){let o=[];for(let a of r){let l=s.changes.mapPos(a.pos,-1,ge.TrackDel);if(l!=null){let h=Object.assign(Object.create(null),a);h.pos=l,h.end!=null&&(h.end=s.changes.mapPos(h.end)),o.push(h)}}r=o}for(let o of s.effects)o.is(t)&&(r=o.value),o.is(Yb)&&(r=[]);return r},provide:r=>ao.from(r)});return[n,re.define(r=>new ph(r,i,n,t,e.hoverTime||300)),Fb]}function Sh(i,e){let t=i.plugin(kh);if(!t)return null;let n=t.manager.tooltips.indexOf(e);return n<0?null:t.manager.tooltipViews[n]}var Yb=_.define();var ad=A.define({combine(i){let e,t;for(let n of i)e=e||n.topContainer,t=t||n.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Pi(i,e){let t=i.plugin(xp),n=t?t.specs.indexOf(e):-1;return n>-1?t.panels[n]:null}var xp=re.fromClass(class{constructor(i){this.input=i.state.facet(Ti),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(i));let e=i.state.facet(ad);this.top=new sn(i,!0,e.topContainer),this.bottom=new sn(i,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(i){let e=i.state.facet(ad);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new sn(i.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new sn(i.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=i.state.facet(Ti);if(t!=this.input){let n=t.filter(l=>l),r=[],s=[],o=[],a=[];for(let l of n){let h=this.specs.indexOf(l),c;h<0?(c=l(i.view),a.push(c)):(c=this.panels[h],c.update&&c.update(i)),r.push(c),(c.top?s:o).push(c)}this.specs=n,this.panels=r,this.top.sync(s),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let n of this.panels)n.update&&n.update(i)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:i=>E.scrollMargins.of(e=>{let t=e.plugin(i);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})}),sn=class{constructor(e,t,n){this.view=e,this.top=t,this.container=n,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=ld(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=ld(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}};function ld(i){let e=i.nextSibling;return i.remove(),e}var Ti=A.define({enables:xp}),ze=class extends at{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};ze.prototype.elementClass="";ze.prototype.toDOM=void 0;ze.prototype.mapMode=ge.TrackBefore;ze.prototype.startSide=ze.prototype.endSide=-1;ze.prototype.point=!0;var Gs=A.define(),Zb={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>j.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},sr=A.define();function Th(i){return[kp(),sr.of(Object.assign(Object.assign({},Zb),i))]}var mh=A.define({combine:i=>i.some(e=>e)});function kp(i){let e=[Jb];return i&&i.fixed===!1&&e.push(mh.of(!0)),e}var Jb=re.fromClass(class{constructor(i){this.view=i,this.prevViewport=i.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=i.state.facet(sr).map(e=>new ho(i,e));for(let e of this.gutters)this.dom.appendChild(e.dom);this.fixed=!i.state.facet(mh),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),i.scrollDOM.insertBefore(this.dom,i.contentDOM)}update(i){if(this.updateGutters(i)){let e=this.prevViewport,t=i.view.viewport,n=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(n<(t.to-t.from)*.8)}i.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px"),this.view.state.facet(mh)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=i.view.viewport}syncGutters(i){let e=this.dom.nextSibling;i&&this.dom.remove();let t=j.iter(this.view.state.facet(Gs),this.view.viewport.from),n=[],r=this.gutters.map(s=>new Oh(s,this.view.viewport,-this.view.documentPadding.top));for(let s of this.view.viewportLineBlocks)if(n.length&&(n=[]),Array.isArray(s.type)){let o=!0;for(let a of s.type)if(a.type==_e.Text&&o){gh(t,n,a.from);for(let l of r)l.line(this.view,a,n);o=!1}else if(a.widget)for(let l of r)l.widget(this.view,a)}else if(s.type==_e.Text){gh(t,n,s.from);for(let o of r)o.line(this.view,s,n)}else if(s.widget)for(let o of r)o.widget(this.view,s);for(let s of r)s.finish();i&&this.view.scrollDOM.insertBefore(this.dom,e)}updateGutters(i){let e=i.startState.facet(sr),t=i.state.facet(sr),n=i.docChanged||i.heightChanged||i.viewportChanged||!j.eq(i.startState.facet(Gs),i.state.facet(Gs),i.view.viewport.from,i.view.viewport.to);if(e==t)for(let r of this.gutters)r.update(i)&&(n=!0);else{n=!0;let r=[];for(let s of t){let o=e.indexOf(s);o<0?r.push(new ho(this.view,s)):(this.gutters[o].update(i),r.push(this.gutters[o]))}for(let s of this.gutters)s.dom.remove(),r.indexOf(s)<0&&s.destroy();for(let s of r)this.dom.appendChild(s.dom);this.gutters=r}return n}destroy(){for(let i of this.gutters)i.destroy();this.dom.remove()}},{provide:i=>E.scrollMargins.of(e=>{let t=e.plugin(i);return!t||t.gutters.length==0||!t.fixed?null:e.textDirection==H.LTR?{left:t.dom.offsetWidth*e.scaleX}:{right:t.dom.offsetWidth*e.scaleX}})});function hd(i){return Array.isArray(i)?i:[i]}function gh(i,e,t){for(;i.value&&i.from<=t;)i.from==t&&e.push(i.value),i.next()}var Oh=class{constructor(e,t,n){this.gutter=e,this.height=n,this.i=0,this.cursor=j.iter(e.markers,t.from)}addElement(e,t,n){let{gutter:r}=this,s=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==r.elements.length){let a=new co(e,o,s,n);r.elements.push(a),r.dom.appendChild(a.dom)}else r.elements[this.i].update(e,o,s,n);this.height=t.bottom,this.i++}line(e,t,n){let r=[];gh(this.cursor,r,t.from),n.length&&(r=r.concat(n));let s=this.gutter.config.lineMarker(e,t,r);s&&r.unshift(s);let o=this.gutter;r.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,r)}widget(e,t){let n=this.gutter.config.widgetMarker(e,t.widget,t);n&&this.addElement(e,t,[n])}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},ho=class{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let n in t.domEventHandlers)this.dom.addEventListener(n,r=>{let s=r.target,o;if(s!=this.dom&&this.dom.contains(s)){for(;s.parentNode!=this.dom;)s=s.parentNode;let l=s.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=r.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[n](e,a,r)&&r.preventDefault()});this.markers=hd(t.markers(e)),t.initialSpacer&&(this.spacer=new co(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=hd(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let r=this.config.updateSpacer(this.spacer.markers[0],e);r!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[r])}let n=e.view.viewport;return!j.eq(this.markers,t,n.from,n.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},co=class{constructor(e,t,n,r){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,n,r)}update(e,t,n,r){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=n&&(this.dom.style.marginTop=(this.above=n)?n+"px":""),Kb(this.markers,r)||this.setMarkers(e,r)}setMarkers(e,t){let n="cm-gutterElement",r=this.dom.firstChild;for(let s=0,o=0;;){let a=o,l=ss(a,l,h)||o(a,l,h):o}return n}})}}),or=class extends ze{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function Rl(i,e){return i.state.facet(on).formatNumber(e,i.state)}var tw=sr.compute([on],i=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(ew)},lineMarker(e,t,n){return n.some(r=>r.toDOM)?null:new or(Rl(e,e.state.doc.lineAt(t.from).number))},widgetMarker:()=>null,lineMarkerChange:e=>e.startState.facet(on)!=e.state.facet(on),initialSpacer(e){return new or(Rl(e,cd(e.state.doc.lines)))},updateSpacer(e,t){let n=Rl(t.view,cd(t.view.state.doc.lines));return n==e.number?e:new or(n)},domEventHandlers:i.facet(on).domEventHandlers}));function Sp(i={}){return[on.of(i),kp(),tw]}function cd(i){let e=9;for(;e{let e=[],t=-1;for(let n of i.selection.ranges){let r=i.doc.lineAt(n.head).from;r>t&&(t=r,e.push(iw.range(r)))}return j.of(e)});function Tp(){return nw}var rw=0,Or=class{constructor(e,t){this.from=e,this.to=t}},$=class{constructor(e={}){this.id=rw++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Pe.match(e)),t=>{let n=e(t);return n===void 0?null:[this,n]}}};$.closedBy=new $({deserialize:i=>i.split(" ")});$.openedBy=new $({deserialize:i=>i.split(" ")});$.group=new $({deserialize:i=>i.split(" ")});$.isolate=new $({deserialize:i=>{if(i&&i!="rtl"&&i!="ltr"&&i!="auto")throw new RangeError("Invalid value for isolate: "+i);return i||"auto"}});$.contextHash=new $({perNode:!0});$.lookAhead=new $({perNode:!0});$.mounted=new $({perNode:!0});var ln=class{constructor(e,t,n){this.tree=e,this.overlay=t,this.parser=n}static get(e){return e&&e.props&&e.props[$.mounted.id]}},sw=Object.create(null),Pe=class i{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):sw,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),r=new i(e.name||"",t,e.id,n);if(e.props){for(let s of e.props)if(Array.isArray(s)||(s=s(r)),s){if(s[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[s[0].id]=s[1]}}return r}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop($.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return n=>{for(let r=n.prop($.group),s=-1;s<(r?r.length:0);s++){let o=t[s<0?n.name:r[s]];if(o)return o}}}};Pe.none=new Pe("",Object.create(null),0,8);var yr=class i{constructor(e){this.types=e;for(let t=0;t0;for(let l=this.cursor(o|oe.IncludeAnonymous);;){let h=!1;if(l.from<=s&&l.to>=r&&(!a&&l.type.isAnonymous||t(l)!==!1)){if(l.firstChild())continue;h=!0}for(;h&&n&&(a||!l.type.isAnonymous)&&n(l),!l.nextSibling();){if(!l.parent())return;h=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Mh(Pe.none,this.children,this.positions,0,this.children.length,0,this.length,(t,n,r)=>new i(this.type,t,n,r,this.propValues),e.makeTree||((t,n,r)=>new i(Pe.none,t,n,r)))}static build(e){return aw(e)}};le.empty=new le(Pe.none,[],[],0);var Ph=class i{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new i(this.buffer,this.index)}},ei=class i{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return Pe.none}toString(){let e=[];for(let t=0;t0));l=o[l+3]);return a}slice(e,t,n){let r=this.buffer,s=new Uint16Array(t-e),o=0;for(let a=e,l=0;a=e&&te;case 1:return t<=e&&n>e;case 2:return n>e;case 4:return!0}}function br(i,e,t,n){for(var r;i.from==i.to||(t<1?i.from>=e:i.from>e)||(t>-1?i.to<=e:i.to0?a.length:-1;e!=h;e+=t){let c=a[e],f=l[e]+o.from;if(Ep(r,n,f,f+c.length)){if(c instanceof ei){if(s&oe.ExcludeBuffers)continue;let u=c.findChild(0,c.buffer.length,t,n-f,r);if(u>-1)return new Ci(new Rh(o,c,e,f),null,u)}else if(s&oe.IncludeAnonymous||!c.type.isAnonymous||Qh(c)){let u;if(!(s&oe.IgnoreMounts)&&(u=ln.get(c))&&!u.overlay)return new i(u.tree,f,e,o);let d=new i(c,f,e,o);return s&oe.IncludeAnonymous||!d.type.isAnonymous?d:d.nextChild(t<0?c.children.length-1:0,t,n,r)}}}if(s&oe.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,n=0){let r;if(!(n&oe.IgnoreOverlays)&&(r=ln.get(this._tree))&&r.overlay){let s=e-this.from;for(let{from:o,to:a}of r.overlay)if((t>0?o<=s:o=s:a>s))return new i(r.tree,r.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,n)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Cp(i,e,t,n){let r=i.cursor(),s=[];if(!r.firstChild())return s;if(t!=null){for(let o=!1;!o;)if(o=r.type.is(t),!r.nextSibling())return s}for(;;){if(n!=null&&r.type.is(n))return s;if(r.type.is(e)&&s.push(r.node),!r.nextSibling())return n==null?s:[]}}function Ch(i,e,t=e.length-1){for(let n=i.parent;t>=0;n=n.parent){if(!n)return!1;if(!n.type.isAnonymous){if(e[t]&&e[t]!=n.name)return!1;t--}}return!0}var Rh=class{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}},Ci=class i extends mo{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,n){super(),this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(e,t,n){let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return s<0?null:new i(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n=0){if(n&oe.ExcludeBuffers)return null;let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return s<0?null:new i(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new i(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new i(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,s=n.buffer[this.index+3];if(s>r){let o=n.buffer[this.index+1];e.push(n.slice(r,s,o)),t.push(0)}return new le(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function Ap(i){if(!i.length)return null;let e=0,t=i[0];for(let s=1;st.from||o.to=e){let a=new nt(o.tree,o.overlay[0].from+s.from,-1,s);(r||(r=[n])).push(br(a,e,t,!1))}}return r?Ap(r):n}var wr=class{get name(){return this.type.name}constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof nt)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let n=e._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return e?e instanceof nt?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return s<0?!1:(this.stack.push(this.index),this.yieldBuf(s))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=this.mode){return this.buffer?n&oe.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&oe.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&oe.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let r=n<0?0:this.stack[n]+4;if(this.index!=r)return this.yieldBuf(t.findChild(r,this.index,-1,0,4))}else{let r=t.buffer[this.index+3];if(r<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(r)}return n<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let s=t+e,o=e<0?-1:n._tree.children.length;s!=o;s+=e){let a=n._tree.children[s];if(this.mode&oe.IncludeAnonymous||a instanceof ei||!a.type.isAnonymous||Qh(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==r){if(r==this.index)return o;t=o,n=s+1;break e}r=this.stack[--s]}for(let r=n;r=0;s--){if(s<0)return Ch(this.node,e,r);let o=n[t.buffer[this.stack[s]]];if(!o.isAnonymous){if(e[r]&&e[r]!=o.name)return!1;r--}}return!0}};function Qh(i){return i.children.some(e=>e instanceof ei||!e.type.isAnonymous||Qh(e))}function aw(i){var e;let{buffer:t,nodeSet:n,maxBufferLength:r=1024,reused:s=[],minRepeatType:o=n.types.length}=i,a=Array.isArray(t)?new Ph(t,t.length):t,l=n.types,h=0,c=0;function f(w,P,C,D,B,V){let{id:X,start:q,end:G,size:I}=a,ie=c;for(;I<0;)if(a.next(),I==-1){let pe=s[X];C.push(pe),D.push(q-w);return}else if(I==-3){h=X;return}else if(I==-4){c=X;return}else throw new RangeError(`Unrecognized record size: ${I}`);let De=l[X],$e,We,Ye=q-w;if(G-q<=r&&(We=g(a.pos-P,B))){let pe=new Uint16Array(We.size-We.skip),Ze=a.pos-We.size,dt=pe.length;for(;a.pos>Ze;)dt=O(We.start,pe,dt);$e=new ei(pe,G-We.start,n),Ye=We.start-w}else{let pe=a.pos-I;a.next();let Ze=[],dt=[],hi=X>=o?X:-1,qi=0,Hr=G;for(;a.pos>pe;)hi>=0&&a.id==hi&&a.size>=0?(a.end<=Hr-r&&(m(Ze,dt,q,qi,a.end,Hr,hi,ie),qi=Ze.length,Hr=a.end),a.next()):V>2500?u(q,pe,Ze,dt):f(q,pe,Ze,dt,hi,V+1);if(hi>=0&&qi>0&&qi-1&&qi>0){let of=d(De);$e=Mh(De,Ze,dt,0,Ze.length,0,G-q,of,of)}else $e=p(De,Ze,dt,G-q,ie-G)}C.push($e),D.push(Ye)}function u(w,P,C,D){let B=[],V=0,X=-1;for(;a.pos>P;){let{id:q,start:G,end:I,size:ie}=a;if(ie>4)a.next();else{if(X>-1&&G=0;I-=3)q[ie++]=B[I],q[ie++]=B[I+1]-G,q[ie++]=B[I+2]-G,q[ie++]=ie;C.push(new ei(q,B[2]-G,n)),D.push(G-w)}}function d(w){return(P,C,D)=>{let B=0,V=P.length-1,X,q;if(V>=0&&(X=P[V])instanceof le){if(!V&&X.type==w&&X.length==D)return X;(q=X.prop($.lookAhead))&&(B=C[V]+X.length+q)}return p(w,P,C,D,B)}}function m(w,P,C,D,B,V,X,q){let G=[],I=[];for(;w.length>D;)G.push(w.pop()),I.push(P.pop()+C-B);w.push(p(n.types[X],G,I,V-B,q-V)),P.push(B-C)}function p(w,P,C,D,B=0,V){if(h){let X=[$.contextHash,h];V=V?[X].concat(V):[X]}if(B>25){let X=[$.lookAhead,B];V=V?[X].concat(V):[X]}return new le(w,P,C,D,V)}function g(w,P){let C=a.fork(),D=0,B=0,V=0,X=C.end-r,q={size:0,start:0,skip:0};e:for(let G=C.pos-w;C.pos>G;){let I=C.size;if(C.id==P&&I>=0){q.size=D,q.start=B,q.skip=V,V+=4,D+=4,C.next();continue}let ie=C.pos-I;if(I<0||ie=o?4:0,$e=C.start;for(C.next();C.pos>ie;){if(C.size<0)if(C.size==-3)De+=4;else break e;else C.id>=o&&(De+=4);C.next()}B=$e,D+=I,V+=De}return(P<0||D==w)&&(q.size=D,q.start=B,q.skip=V),q.size>4?q:void 0}function O(w,P,C){let{id:D,start:B,end:V,size:X}=a;if(a.next(),X>=0&&D4){let G=a.pos-(X-4);for(;a.pos>G;)C=O(w,P,C)}P[--C]=q,P[--C]=V-w,P[--C]=B-w,P[--C]=D}else X==-3?h=D:X==-4&&(c=D);return C}let y=[],v=[];for(;a.pos>0;)f(i.start||0,i.bufferStart||0,y,v,-1,0);let x=(e=i.length)!==null&&e!==void 0?e:y.length?v[0]+y[0].length:0;return new le(l[i.topID],y.reverse(),v.reverse(),x)}var Rp=new WeakMap;function po(i,e){if(!i.isAnonymous||e instanceof ei||e.type!=i)return 1;let t=Rp.get(e);if(t==null){t=1;for(let n of e.children){if(n.type!=i||!(n instanceof le)){t=1;break}t+=po(i,n)}Rp.set(e,t)}return t}function Mh(i,e,t,n,r,s,o,a,l){let h=0;for(let m=n;m=c)break;P+=C}if(v==x+1){if(P>c){let C=m[x];d(C.children,C.positions,0,C.children.length,p[x]+y);continue}f.push(m[x])}else{let C=p[v-1]+m[v-1].length-w;f.push(Mh(i,m,p,x,v,w,C,null,l))}u.push(w+y-s)}}return d(e,t,n,r,0),(a||l)(f,u,o)}var go=class{constructor(){this.map=new WeakMap}setBuffer(e,t,n){let r=this.map.get(e);r||this.map.set(e,r=new Map),r.set(t,n)}getBuffer(e,t){let n=this.map.get(e);return n&&n.get(t)}set(e,t){e instanceof Ci?this.setBuffer(e.context.buffer,e.index,t):e instanceof nt&&this.map.set(e.tree,t)}get(e){return e instanceof Ci?this.getBuffer(e.context.buffer,e.index):e instanceof nt?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}},Ri=class i{constructor(e,t,n,r,s=!1,o=!1){this.from=e,this.to=t,this.tree=n,this.offset=r,this.open=(s?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],n=!1){let r=[new i(0,e.length,e,0,!1,n)];for(let s of t)s.to>e.length&&r.push(s);return r}static applyChanges(e,t,n=128){if(!t.length)return e;let r=[],s=1,o=e.length?e[0]:null;for(let a=0,l=0,h=0;;a++){let c=a=n)for(;o&&o.from=u.from||f<=u.to||h){let d=Math.max(u.from,l)-h,m=Math.min(u.to,f)-h;u=d>=m?null:new i(d,m,u.tree,u.offset+h,a>0,!!c)}if(u&&r.push(u),o.to>f)break;o=snew Or(r.from,r.to)):[new Or(0,0)]:[new Or(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let s=r.advance();if(s)return s}}},Ah=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var pT=new $({perNode:!0});var lw=0,Tt=class i{constructor(e,t,n){this.set=e,this.base=t,this.modified=n,this.id=lw++}static define(e){if(e?.base)throw new Error("Can not derive from a modified tag");let t=new i([],null,[]);if(t.set.push(t),e)for(let n of e.set)t.set.push(n);return t}static defineModifier(){let e=new wo;return t=>t.modified.indexOf(e)>-1?t:wo.get(t.base||t,t.modified.concat(e).sort((n,r)=>n.id-r.id))}},hw=0,wo=class i{constructor(){this.instances=[],this.id=hw++}static get(e,t){if(!t.length)return e;let n=t[0].instances.find(a=>a.base==e&&cw(t,a.modified));if(n)return n;let r=[],s=new Tt(r,e,t);for(let a of t)a.instances.push(s);let o=fw(t);for(let a of e.set)if(!a.modified.length)for(let l of o)r.push(i.get(a,l));return s}};function cw(i,e){return i.length==e.length&&i.every((t,n)=>t==e[n])}function fw(i){let e=[[]];for(let t=0;tn.length-t.length)}function fn(i){let e=Object.create(null);for(let t in i){let n=i[t];Array.isArray(n)||(n=[n]);for(let r of t.split(" "))if(r){let s=[],o=2,a=r;for(let f=0;;){if(a=="..."&&f>0&&f+3==r.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!u)throw new RangeError("Invalid path: "+r);if(s.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),f+=u[0].length,f==r.length)break;let d=r[f++];if(f==r.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+r);a=r.slice(f)}let l=s.length-1,h=s[l];if(!h)throw new RangeError("Invalid path: "+r);let c=new cn(n,o,l>0?s.slice(0,l):null);e[h]=c.sort(e[h])}}return _p.add(e)}var _p=new $,cn=class{constructor(e,t,n,r){this.tags=e,this.mode=t,this.context=n,this.next=r}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=r;for(let a of s)for(let l of a.set){let h=t[l.id];if(h){o=o?o+" "+h:h;break}}return o},scope:n}}function uw(i,e){let t=null;for(let n of i){let r=n.style(e);r&&(t=t?t+" "+r:r)}return t}function Vh(i,e,t,n=0,r=i.length){let s=new Dh(n,Array.isArray(e)?e:[e],t);s.highlightRange(i.cursor(),n,r,"",s.highlighters),s.flush(r)}function Lh(i,e,t,n,r,s=0,o=i.length){let a=s;function l(h,c){if(!(h<=a)){for(let f=i.slice(a,h),u=0;;){let d=f.indexOf(` +`,u),m=d<0?f.length:d;if(m>u&&n(f.slice(u,m),c),d<0)break;r(),u=d+1}a=h}}Vh(e,t,(h,c,f)=>{l(h,""),l(c,f)},s,o),l(o,"")}var Dh=class{constructor(e,t,n){this.at=e,this.highlighters=t,this.span=n,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,n,r,s){let{type:o,from:a,to:l}=e;if(a>=n||l<=t)return;o.isTop&&(s=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=r,c=dw(e)||cn.empty,f=uw(s,c.tags);if(f&&(h&&(h+=" "),h+=f,c.mode==1&&(r+=(r?" ":"")+f)),this.startSpan(Math.max(t,a),h),c.opaque)return;let u=e.tree&&e.tree.prop($.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+a,1),m=this.highlighters.filter(g=>!g.scope||g.scope(u.tree.type)),p=e.firstChild();for(let g=0,O=a;;g++){let y=g=v||!e.nextSibling())););if(!y||v>n)break;O=y.to+a,O>t&&(this.highlightRange(d.cursor(),Math.max(t,y.from+a),Math.min(n,O),"",m),this.startSpan(Math.min(n,O),h))}p&&e.parent()}else if(e.firstChild()){u&&(r="");do if(!(e.to<=t)){if(e.from>=n)break;this.highlightRange(e,t,n,r,s),this.startSpan(Math.min(n,e.to),h)}while(e.nextSibling());e.parent()}}};function dw(i){let e=i.type.prop(_p);for(;e&&e.context&&!i.matchContext(e.context);)e=e.next;return e||null}var R=Tt.define,Oo=R(),ti=R(),Qp=R(ti),Mp=R(ti),ii=R(),yo=R(ii),_h=R(ii),St=R(),Ei=R(St),xt=R(),kt=R(),$h=R(),vr=R($h),bo=R(),b={comment:Oo,lineComment:R(Oo),blockComment:R(Oo),docComment:R(Oo),name:ti,variableName:R(ti),typeName:Qp,tagName:R(Qp),propertyName:Mp,attributeName:R(Mp),className:R(ti),labelName:R(ti),namespace:R(ti),macroName:R(ti),literal:ii,string:yo,docString:R(yo),character:R(yo),attributeValue:R(yo),number:_h,integer:R(_h),float:R(_h),bool:R(ii),regexp:R(ii),escape:R(ii),color:R(ii),url:R(ii),keyword:xt,self:R(xt),null:R(xt),atom:R(xt),unit:R(xt),modifier:R(xt),operatorKeyword:R(xt),controlKeyword:R(xt),definitionKeyword:R(xt),moduleKeyword:R(xt),operator:kt,derefOperator:R(kt),arithmeticOperator:R(kt),logicOperator:R(kt),bitwiseOperator:R(kt),compareOperator:R(kt),updateOperator:R(kt),definitionOperator:R(kt),typeOperator:R(kt),controlOperator:R(kt),punctuation:$h,separator:R($h),bracket:vr,angleBracket:R(vr),squareBracket:R(vr),paren:R(vr),brace:R(vr),content:St,heading:Ei,heading1:R(Ei),heading2:R(Ei),heading3:R(Ei),heading4:R(Ei),heading5:R(Ei),heading6:R(Ei),contentSeparator:R(St),list:R(St),quote:R(St),emphasis:R(St),strong:R(St),link:R(St),monospace:R(St),strikethrough:R(St),inserted:R(),deleted:R(),changed:R(),invalid:R(),meta:bo,documentMeta:R(bo),annotation:R(bo),processingInstruction:R(bo),definition:Tt.defineModifier(),constant:Tt.defineModifier(),function:Tt.defineModifier(),standard:Tt.defineModifier(),local:Tt.defineModifier(),special:Tt.defineModifier()},OT=xr([{tag:b.link,class:"tok-link"},{tag:b.heading,class:"tok-heading"},{tag:b.emphasis,class:"tok-emphasis"},{tag:b.strong,class:"tok-strong"},{tag:b.keyword,class:"tok-keyword"},{tag:b.atom,class:"tok-atom"},{tag:b.bool,class:"tok-bool"},{tag:b.url,class:"tok-url"},{tag:b.labelName,class:"tok-labelName"},{tag:b.inserted,class:"tok-inserted"},{tag:b.deleted,class:"tok-deleted"},{tag:b.literal,class:"tok-literal"},{tag:b.string,class:"tok-string"},{tag:b.number,class:"tok-number"},{tag:[b.regexp,b.escape,b.special(b.string)],class:"tok-string2"},{tag:b.variableName,class:"tok-variableName"},{tag:b.local(b.variableName),class:"tok-variableName tok-local"},{tag:b.definition(b.variableName),class:"tok-variableName tok-definition"},{tag:b.special(b.variableName),class:"tok-variableName2"},{tag:b.definition(b.propertyName),class:"tok-propertyName tok-definition"},{tag:b.typeName,class:"tok-typeName"},{tag:b.namespace,class:"tok-namespace"},{tag:b.className,class:"tok-className"},{tag:b.macroName,class:"tok-macroName"},{tag:b.propertyName,class:"tok-propertyName"},{tag:b.operator,class:"tok-operator"},{tag:b.comment,class:"tok-comment"},{tag:b.meta,class:"tok-meta"},{tag:b.invalid,class:"tok-invalid"},{tag:b.punctuation,class:"tok-punctuation"}]);var qh,un=new $;function pw(i){return A.define({combine:i?e=>e.concat(i):void 0})}var mw=new $,Ue=class{constructor(e,t,n=[],r=""){this.data=e,this.name=r,N.prototype.hasOwnProperty("tree")||Object.defineProperty(N.prototype,"tree",{get(){return he(this)}}),this.parser=t,this.extension=[ni.of(this),N.languageData.of((s,o,a)=>{let l=Dp(s,o,a),h=l.type.prop(un);if(!h)return[];let c=s.facet(h),f=l.type.prop(mw);if(f){let u=l.resolve(o-l.from,a);for(let d of f)if(d.test(u,s)){let m=s.facet(d.facet);return d.type=="replace"?m:m.concat(c)}}return c})].concat(n)}isActiveAt(e,t,n=-1){return Dp(e,t,n).type.prop(un)==this.data}findRegions(e){let t=e.facet(ni);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let n=[],r=(s,o)=>{if(s.prop(un)==this.data){n.push({from:o,to:o+s.length});return}let a=s.prop($.mounted);if(a){if(a.tree.prop(un)==this.data){if(a.overlay)for(let l of a.overlay)n.push({from:l.from+o,to:l.to+o});else n.push({from:o,to:o+s.length});return}else if(a.overlay){let l=n.length;if(r(a.tree,a.overlay[0].from+o),n.length>l)return}}for(let l=0;ln.isTop?t:void 0)]}),e.name)}configure(e,t){return new i(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function he(i){let e=i.field(Ue.state,!1);return e?e.tree:le.empty}var Ih=class{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let n=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-n,t-n)}},kr=null,Nh=class i{constructor(e,t,n=[],r,s,o,a,l){this.parser=e,this.state=t,this.fragments=n,this.tree=r,this.treeLen=s,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,n){return new i(e,t,[],le.empty,0,n,[],null)}startParse(){return this.parser.startParse(new Ih(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=le.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var n;if(typeof e=="number"){let r=Date.now()+e;e=()=>Date.now()>r}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Ri.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=kr;kr=this;try{return e()}finally{kr=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=$p(e,t.from,t.to);return e}changes(e,t){let{fragments:n,tree:r,treeLen:s,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((h,c,f,u)=>l.push({fromA:h,toA:c,fromB:f,toB:u})),n=Ri.applyChanges(n,l),r=le.empty,s=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),f=e.mapPos(h.to,-1);ce.from&&(this.fragments=$p(this.fragments,r,s),this.skipped.splice(n--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends hn{createParse(t,n,r){let s=r[0].from,o=r[r.length-1].to;return{parsedPos:s,advance(){let l=kr;if(l){for(let h of r)l.tempSkipped.push(h);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new le(Pe.none,[],[],o-s)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return kr}};function $p(i,e,t){return Ri.applyChanges(i,[{fromA:e,toA:t,fromB:e,toB:t}])}var Tr=class i{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),n=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,n)||t.takeTree(),new i(t)}static init(e){let t=Math.min(3e3,e.doc.length),n=Nh.create(e.facet(ni).parser,e,{from:0,to:t});return n.work(20,t)||n.takeTree(),new i(n)}};Ue.state=te.define({create:Tr.init,update(i,e){for(let t of e.effects)if(t.is(Ue.setState))return t.value;return e.startState.facet(ni)!=e.state.facet(ni)?Tr.init(e.state):i.apply(e)}});var Xp=i=>{let e=setTimeout(()=>i(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Xp=i=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(i,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var Bh=typeof navigator<"u"&&(!((qh=navigator.scheduling)===null||qh===void 0)&&qh.isInputPending)?()=>navigator.scheduling.isInputPending():null,gw=re.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Ue.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Ue.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Xp(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEndr+1e3,l=s.context.work(()=>Bh&&Bh()||Date.now()>o,r+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(s.context.takeTree(),this.view.dispatch({effects:Ue.setState.of(new Tr(s.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(s.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>we(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),ni=A.define({combine(i){return i.length?i[0]:null},enables:i=>[Ue.state,gw,E.contentAttributes.compute([i],e=>{let t=e.facet(i);return t&&t.name?{"data-language":t.name}:{}})]}),pn=class{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}};var Ow=A.define(),mn=A.define({combine:i=>{if(!i.length)return" ";let e=i[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(i[0]));return e}});function Pr(i){let e=i.facet(mn);return e.charCodeAt(0)==9?i.tabSize*e.length:e.length}function gn(i,e){let t="",n=i.tabSize,r=i.facet(mn)[0];if(r==" "){for(;e>=n;)t+=" ",e-=n;r=" "}for(let s=0;s=e?yw(i,t,e):null}var Ai=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=Pr(e)}lineAt(e,t=1){let n=this.state.doc.lineAt(e),{simulateBreak:r,simulateDoubleBreak:s}=this.options;return r!=null&&r>=n.from&&r<=n.to?s&&r==e?{text:"",from:e}:(t<0?r-1&&(s+=o-this.countColumn(n,n.search(/\S|$/))),s}countColumn(e,t=e.length){return $t(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:n,from:r}=this.lineAt(e,t),s=this.options.overrideIndentation;if(s){let o=s(r);if(o>-1)return o}return this.countColumn(n,n.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},Cr=new $;function yw(i,e,t){let n=e.resolveStack(t),r=n.node.enterUnfinishedNodesBefore(t);if(r!=n.node){let s=[];for(let o=r;o!=n.node;o=o.parent)s.push(o);for(let o=s.length-1;o>=0;o--)n={node:s[o],next:n}}return Wp(n,i,t)}function Wp(i,e,t){for(let n=i;n;n=n.next){let r=ww(n.node);if(r)return r(jh.create(e,t,n))}return 0}function bw(i){return i.pos==i.options.simulateBreak&&i.options.simulateDoubleBreak}function ww(i){let e=i.type.prop(Cr);if(e)return e;let t=i.firstChild,n;if(t&&(n=t.type.prop($.closedBy))){let r=i.lastChild,s=r&&n.indexOf(r.name)>-1;return o=>Ip(o,!0,1,void 0,s&&!bw(o)?r.from:void 0)}return i.parent==null?vw:null}function vw(){return 0}var jh=class i extends Ai{constructor(e,t,n){super(e.state,e.options),this.base=e,this.pos=t,this.context=n}get node(){return this.context.node}static create(e,t,n){return new i(e,t,n)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let n=e.resolve(t.from);for(;n.parent&&n.parent.from==n.from;)n=n.parent;if(xw(n,e))break;t=this.state.doc.lineAt(n.from)}return this.lineIndent(t.from)}continue(){return Wp(this.context.next,this.base,this.pos)}};function xw(i,e){for(let t=e;t;t=t.parent)if(i==t)return!0;return!1}function kw(i){let e=i.node,t=e.childAfter(e.from),n=e.lastChild;if(!t)return null;let r=i.options.simulateBreak,s=i.state.doc.lineAt(t.from),o=r==null||r<=s.from?s.to:Math.min(s.to,r);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==n)return null;if(!l.type.isSkipped)return l.fromIp(n,e,t,i)}function Ip(i,e,t,n,r){let s=i.textAfter,o=s.match(/^\s*/)[0].length,a=n&&s.slice(o,o+n.length)==n||r==i.pos+o,l=e?kw(i):null;return l?a?i.column(l.from):i.column(l.to):i.baseIndent+(a?0:i.unit*t)}var Sw=200;function Np(){return N.transactionFilter.of(i=>{if(!i.docChanged||!i.isUserEvent("input.type")&&!i.isUserEvent("input.complete"))return i;let e=i.startState.languageDataAt("indentOnInput",i.startState.selection.main.head);if(!e.length)return i;let t=i.newDoc,{head:n}=i.newSelection.main,r=t.lineAt(n);if(n>r.from+Sw)return i;let s=t.sliceString(r.from,n);if(!e.some(h=>h.test(s)))return i;let{state:o}=i,a=-1,l=[];for(let{head:h}of o.selection.ranges){let c=o.doc.lineAt(h);if(c.from==a)continue;a=c.from;let f=So(o,c.from);if(f==null)continue;let u=/^\s*/.exec(c.text)[0],d=gn(o,f);u!=d&&l.push({from:c.from,to:c.from+u.length,insert:d})}return l.length?[i,{changes:l,sequential:!0}]:i})}var Tw=A.define(),Rr=new $;function To(i){let e=i.firstChild,t=i.lastChild;return e&&e.tot)continue;if(s&&a.from=e&&h.to>t&&(s=h)}}return s}function Cw(i){let e=i.lastChild;return e&&e.to==i.to&&e.type.isError}function vo(i,e,t){for(let n of i.facet(Tw)){let r=n(i,e,t);if(r)return r}return Pw(i,e,t)}function jp(i,e){let t=e.mapPos(i.from,1),n=e.mapPos(i.to,-1);return t>=n?void 0:{from:t,to:n}}var Po=_.define({map:jp}),Er=_.define({map:jp});function zp(i){let e=[];for(let{head:t}of i.state.selection.ranges)e.some(n=>n.from<=t&&n.to>=t)||e.push(i.lineBlockAt(t));return e}var Qi=te.define({create(){return M.none},update(i,e){i=i.map(e.changes);for(let t of e.effects)if(t.is(Po)&&!Rw(i,t.value.from,t.value.to)){let{preparePlaceholder:n}=e.state.facet(Yh),r=n?M.replace({widget:new zh(n(e.state,t.value))}):Vp;i=i.update({add:[r.range(t.value.from,t.value.to)]})}else t.is(Er)&&(i=i.update({filter:(n,r)=>t.value.from!=n||t.value.to!=r,filterFrom:t.value.from,filterTo:t.value.to}));if(e.selection){let t=!1,{head:n}=e.selection.main;i.between(n,n,(r,s)=>{rn&&(t=!0)}),t&&(i=i.update({filterFrom:n,filterTo:n,filter:(r,s)=>s<=n||r>=n}))}return i},provide:i=>E.decorations.from(i),toJSON(i,e){let t=[];return i.between(0,e.doc.length,(n,r)=>{t.push(n,r)}),t},fromJSON(i){if(!Array.isArray(i)||i.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{(!r||r.from>s)&&(r={from:s,to:o})}),r}function Rw(i,e,t){let n=!1;return i.between(e,e,(r,s)=>{r==e&&s==t&&(n=!0)}),n}function Up(i,e){return i.field(Qi,!1)?e:e.concat(_.appendConfig.of(Gp()))}var Ew=i=>{for(let e of zp(i)){let t=vo(i.state,e.from,e.to);if(t)return i.dispatch({effects:Up(i.state,[Po.of(t),Fp(i,t)])}),!0}return!1},Aw=i=>{if(!i.state.field(Qi,!1))return!1;let e=[];for(let t of zp(i)){let n=xo(i.state,t.from,t.to);n&&e.push(Er.of(n),Fp(i,n,!1))}return e.length&&i.dispatch({effects:e}),e.length>0};function Fp(i,e,t=!0){let n=i.state.doc.lineAt(e.from).number,r=i.state.doc.lineAt(e.to).number;return E.announce.of(`${i.state.phrase(t?"Folded lines":"Unfolded lines")} ${n} ${i.state.phrase("to")} ${r}.`)}var Qw=i=>{let{state:e}=i,t=[];for(let n=0;n{let e=i.state.field(Qi,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,i.state.doc.length,(n,r)=>{t.push(Er.of({from:n,to:r}))}),i.dispatch({effects:t}),!0};var Hp=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:Ew},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:Aw},{key:"Ctrl-Alt-[",run:Qw},{key:"Ctrl-Alt-]",run:Mw}],_w={placeholderDOM:null,preparePlaceholder:null,placeholderText:"\u2026"},Yh=A.define({combine(i){return Te(i,_w)}});function Gp(i){let e=[Qi,$w];return i&&e.push(Yh.of(i)),e}function Yp(i,e){let{state:t}=i,n=t.facet(Yh),r=o=>{let a=i.lineBlockAt(i.posAtDOM(o.target)),l=xo(i.state,a.from,a.to);l&&i.dispatch({effects:Er.of(l)}),o.preventDefault()};if(n.placeholderDOM)return n.placeholderDOM(i,r,e);let s=document.createElement("span");return s.textContent=n.placeholderText,s.setAttribute("aria-label",t.phrase("folded code")),s.title=t.phrase("unfold"),s.className="cm-foldPlaceholder",s.onclick=r,s}var Vp=M.replace({widget:new class extends Be{toDOM(i){return Yp(i,null)}}}),zh=class extends Be{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return Yp(e,this.value)}},Dw={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},Sr=class extends ze{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}};function Zp(i={}){let e=Object.assign(Object.assign({},Dw),i),t=new Sr(e,!0),n=new Sr(e,!1),r=re.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(ni)!=o.state.facet(ni)||o.startState.field(Qi,!1)!=o.state.field(Qi,!1)||he(o.startState)!=he(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let a=new lt;for(let l of o.viewportLineBlocks){let h=xo(o.state,l.from,l.to)?n:vo(o.state,l.from,l.to)?t:null;h&&a.add(l.from,l.from,h)}return a.finish()}}),{domEventHandlers:s}=e;return[r,Th({class:"cm-foldGutter",markers(o){var a;return((a=o.plugin(r))===null||a===void 0?void 0:a.markers)||j.empty},initialSpacer(){return new Sr(e,!1)},domEventHandlers:Object.assign(Object.assign({},s),{click:(o,a,l)=>{if(s.click&&s.click(o,a,l))return!0;let h=xo(o.state,a.from,a.to);if(h)return o.dispatch({effects:Er.of(h)}),!0;let c=vo(o.state,a.from,a.to);return c?(o.dispatch({effects:Po.of(c)}),!0):!1}})}),Gp()]}var $w=E.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}}),ko=class i{constructor(e,t){this.specs=e;let n;function r(a){let l=et.newName();return(n||(n=Object.create(null)))["."+l]=a,l}let s=typeof t.all=="string"?t.all:t.all?r(t.all):void 0,o=t.scope;this.scope=o instanceof Ue?a=>a.prop(un)==o.data:o?a=>a==o:void 0,this.style=xr(e.map(a=>({tag:a.tag,class:a.class||r(Object.assign({},a,{tag:null}))})),{all:s}).style,this.module=n?new et(n):null,this.themeType=t.themeType}static define(e,t){return new i(e,t||{})}},Uh=A.define(),Jp=A.define({combine(i){return i.length?[i[0]]:null}});function Xh(i){let e=i.facet(Uh);return e.length?e:i.facet(Jp)}function Ar(i,e){let t=[Vw],n;return i instanceof ko&&(i.module&&t.push(E.styleModule.of(i.module)),n=i.themeType),e?.fallback?t.push(Jp.of(i)):n?t.push(Uh.computeN([E.darkTheme],r=>r.facet(E.darkTheme)==(n=="dark")?[i]:[])):t.push(Uh.of(i)),t}var Fh=class{constructor(e){this.markCache=Object.create(null),this.tree=he(e.state),this.decorations=this.buildDeco(e,Xh(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=he(e.state),n=Xh(e.state),r=n!=Xh(e.startState),{viewport:s}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=s.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||r)&&(this.tree=t,this.decorations=this.buildDeco(e.view,n),this.decoratedTo=s.to)}buildDeco(e,t){if(!t||!this.tree.length)return M.none;let n=new lt;for(let{from:r,to:s}of e.visibleRanges)Vh(this.tree,t,(o,a,l)=>{n.add(o,a,this.markCache[l]||(this.markCache[l]=M.mark({class:l})))},r,s);return n.finish()}},Vw=Qe.high(re.fromClass(Fh,{decorations:i=>i.decorations})),Kp=ko.define([{tag:b.meta,color:"#404740"},{tag:b.link,textDecoration:"underline"},{tag:b.heading,textDecoration:"underline",fontWeight:"bold"},{tag:b.emphasis,fontStyle:"italic"},{tag:b.strong,fontWeight:"bold"},{tag:b.strikethrough,textDecoration:"line-through"},{tag:b.keyword,color:"#708"},{tag:[b.atom,b.bool,b.url,b.contentSeparator,b.labelName],color:"#219"},{tag:[b.literal,b.inserted],color:"#164"},{tag:[b.string,b.deleted],color:"#a11"},{tag:[b.regexp,b.escape,b.special(b.string)],color:"#e40"},{tag:b.definition(b.variableName),color:"#00f"},{tag:b.local(b.variableName),color:"#30a"},{tag:[b.typeName,b.namespace],color:"#085"},{tag:b.className,color:"#167"},{tag:[b.special(b.variableName),b.macroName],color:"#256"},{tag:b.definition(b.propertyName),color:"#00c"},{tag:b.comment,color:"#940"},{tag:b.invalid,color:"#f00"}]),Lw=E.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),em=1e4,tm="()[]{}",im=A.define({combine(i){return Te(i,{afterCursor:!0,brackets:tm,maxScanDistance:em,renderMatch:Xw})}}),qw=M.mark({class:"cm-matchingBracket"}),Bw=M.mark({class:"cm-nonmatchingBracket"});function Xw(i){let e=[],t=i.matched?qw:Bw;return e.push(t.range(i.start.from,i.start.to)),i.end&&e.push(t.range(i.end.from,i.end.to)),e}var Ww=te.define({create(){return M.none},update(i,e){if(!e.docChanged&&!e.selection)return i;let t=[],n=e.state.facet(im);for(let r of e.state.selection.ranges){if(!r.empty)continue;let s=ct(e.state,r.head,-1,n)||r.head>0&&ct(e.state,r.head-1,1,n)||n.afterCursor&&(ct(e.state,r.head,1,n)||r.headE.decorations.from(i)}),Iw=[Ww,Lw];function nm(i={}){return[im.of(i),Iw]}var Nw=new $;function Hh(i,e,t){let n=i.prop(e<0?$.openedBy:$.closedBy);if(n)return n;if(i.name.length==1){let r=t.indexOf(i.name);if(r>-1&&r%2==(e<0?1:0))return[t[r+e]]}return null}function Gh(i){let e=i.type.prop(Nw);return e?e(i.node):i}function ct(i,e,t,n={}){let r=n.maxScanDistance||em,s=n.brackets||tm,o=he(i),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let h=Hh(l.type,t,s);if(h&&l.from0?e>=c.from&&ec.from&&e<=c.to))return jw(i,e,t,l,c,h,s)}}return zw(i,e,t,o,a.type,r,s)}function jw(i,e,t,n,r,s,o){let a=n.parent,l={from:r.from,to:r.to},h=0,c=a?.cursor();if(c&&(t<0?c.childBefore(n.from):c.childAfter(n.to)))do if(t<0?c.to<=n.from:c.from>=n.to){if(h==0&&s.indexOf(c.type.name)>-1&&c.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=i.doc.iterRange(e,t>0?i.doc.length:0),f=0;for(let u=0;!c.next().done&&u<=s;){let d=c.value;t<0&&(u+=d.length);let m=e+u*t;for(let p=t>0?0:d.length-1,g=t>0?d.length:-1;p!=g;p+=t){let O=o.indexOf(d[p]);if(!(O<0||n.resolveInner(m+p,1).type!=r))if(O%2==0==t>0)f++;else{if(f==1)return{start:h,end:{from:m+p,to:m+p+1},matched:O>>1==l>>1};f--}}t>0&&(u+=d.length)}return c.done?{start:h,matched:!1}:null}var Uw=Object.create(null),Lp=[Pe.none];var qp=[],Bp=Object.create(null),Fw=Object.create(null);for(let[i,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])Fw[i]=Hw(Uw,e);function Wh(i,e){qp.indexOf(i)>-1||(qp.push(i),console.warn(e))}function Hw(i,e){let t=[];for(let a of e.split(" ")){let l=[];for(let h of a.split(".")){let c=i[h]||b[h];c?typeof c=="function"?l.length?l=l.map(c):Wh(h,`Modifier ${h} used at start of tag`):l.length?Wh(h,`Tag ${h} used as modifier`):l=Array.isArray(c)?c:[c]:Wh(h,`Unknown highlighting tag ${h}`)}for(let h of l)t.push(h)}if(!t.length)return 0;let n=e.replace(/ /g,"_"),r=n+" "+t.map(a=>a.id),s=Bp[r];if(s)return s.id;let o=Bp[r]=Pe.define({id:Lp.length,name:n,props:[fn({[n]:t})]});return Lp.push(o),o.id}var TT={rtl:M.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:H.RTL}),ltr:M.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:H.LTR}),auto:M.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};var Gw=i=>{let{state:e}=i,t=e.doc.lineAt(e.selection.main.from),n=nc(i.state,t.from);return n.line?Yw(i):n.block?Jw(i):!1};function ic(i,e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=i(e,t);return r?(n(t.update(r)),!0):!1}}var Yw=ic(tv,0);var Zw=ic(fm,0);var Jw=ic((i,e)=>fm(i,e,ev(e)),0);function nc(i,e){let t=i.languageDataAt("commentTokens",e);return t.length?t[0]:{}}var Qr=50;function Kw(i,{open:e,close:t},n,r){let s=i.sliceDoc(n-Qr,n),o=i.sliceDoc(r,r+Qr),a=/\s*$/.exec(s)[0].length,l=/^\s*/.exec(o)[0].length,h=s.length-a;if(s.slice(h-e.length,h)==e&&o.slice(l,l+t.length)==t)return{open:{pos:n-a,margin:a&&1},close:{pos:r+l,margin:l&&1}};let c,f;r-n<=2*Qr?c=f=i.sliceDoc(n,r):(c=i.sliceDoc(n,n+Qr),f=i.sliceDoc(r-Qr,r));let u=/^\s*/.exec(c)[0].length,d=/\s*$/.exec(f)[0].length,m=f.length-d-t.length;return c.slice(u,u+e.length)==e&&f.slice(m,m+t.length)==t?{open:{pos:n+u+e.length,margin:/\s/.test(c.charAt(u+e.length))?1:0},close:{pos:r-d-t.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function ev(i){let e=[];for(let t of i.selection.ranges){let n=i.doc.lineAt(t.from),r=t.to<=n.to?n:i.doc.lineAt(t.to),s=e.length-1;s>=0&&e[s].to>n.from?e[s].to=r.to:e.push({from:n.from+/^\s*/.exec(n.text)[0].length,to:r.to})}return e}function fm(i,e,t=e.selection.ranges){let n=t.map(s=>nc(e,s.from).block);if(!n.every(s=>s))return null;let r=t.map((s,o)=>Kw(e,n[o],s.from,s.to));if(i!=2&&!r.every(s=>s))return{changes:e.changes(t.map((s,o)=>r[o]?[]:[{from:s.from,insert:n[o].open+" "},{from:s.to,insert:" "+n[o].close}]))};if(i!=1&&r.some(s=>s)){let s=[];for(let o=0,a;or&&(s==o||o>f.from)){r=f.from;let u=/^\s*/.exec(f.text)[0].length,d=u==f.length,m=f.text.slice(u,u+h.length)==h?u:-1;us.comment<0&&(!s.empty||s.single))){let s=[];for(let{line:a,token:l,indent:h,empty:c,single:f}of n)(f||!c)&&s.push({from:a.from+h,insert:l+" "});let o=e.changes(s);return{changes:o,selection:e.selection.map(o,1)}}else if(i!=1&&n.some(s=>s.comment>=0)){let s=[];for(let{line:o,comment:a,token:l}of n)if(a>=0){let h=o.from+a,c=h+l.length;o.text[c-o.from]==" "&&c++,s.push({from:h,to:c})}return{changes:s}}return null}var Jh=Le.define(),iv=Le.define(),nv=A.define(),um=A.define({combine(i){return Te(i,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(n,r)=>e(n,r)||t(n,r)})}}),dm=te.define({create(){return _i.empty},update(i,e){let t=e.state.facet(um),n=e.annotation(Jh);if(n){let l=ft.fromTransaction(e,n.selection),h=n.side,c=h==0?i.undone:i.done;return l?c=Ro(c,c.length,t.minDepth,l):c=Om(c,e.startState.selection),new _i(h==0?n.rest:c,h==0?c:n.rest)}let r=e.annotation(iv);if((r=="full"||r=="before")&&(i=i.isolate()),e.annotation(fe.addToHistory)===!1)return e.changes.empty?i:i.addMapping(e.changes.desc);let s=ft.fromTransaction(e),o=e.annotation(fe.time),a=e.annotation(fe.userEvent);return s?i=i.addChanges(s,o,a,t,e):e.selection&&(i=i.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(r=="full"||r=="after")&&(i=i.isolate()),i},toJSON(i){return{done:i.done.map(e=>e.toJSON()),undone:i.undone.map(e=>e.toJSON())}},fromJSON(i){return new _i(i.done.map(ft.fromJSON),i.undone.map(ft.fromJSON))}});function pm(i={}){return[dm,um.of(i),E.domEventHandlers({beforeinput(e,t){let n=e.inputType=="historyUndo"?mm:e.inputType=="historyRedo"?Kh:null;return n?(e.preventDefault(),n(t)):!1}})]}function Eo(i,e){return function({state:t,dispatch:n}){if(!e&&t.readOnly)return!1;let r=t.field(dm,!1);if(!r)return!1;let s=r.pop(i,t,e);return s?(n(s),!0):!1}}var mm=Eo(0,!1),Kh=Eo(1,!1),rv=Eo(0,!0),sv=Eo(1,!0);var ft=class i{constructor(e,t,n,r,s){this.changes=e,this.effects=t,this.mapped=n,this.startSelection=r,this.selectionsAfter=s}setSelAfter(e){return new i(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,n;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(n=this.startSelection)===null||n===void 0?void 0:n.toJSON(),selectionsAfter:this.selectionsAfter.map(r=>r.toJSON())}}static fromJSON(e){return new i(e.changes&&Ae.fromJSON(e.changes),[],e.mapped&&_t.fromJSON(e.mapped),e.startSelection&&S.fromJSON(e.startSelection),e.selectionsAfter.map(S.fromJSON))}static fromTransaction(e,t){let n=rt;for(let r of e.startState.facet(nv)){let s=r(e);s.length&&(n=n.concat(s))}return!n.length&&e.changes.empty?null:new i(e.changes.invert(e.startState.doc),n,void 0,t||e.startState.selection,rt)}static selection(e){return new i(void 0,rt,void 0,void 0,e)}};function Ro(i,e,t,n){let r=e+1>t+20?e-t-1:0,s=i.slice(r,e);return s.push(n),s}function ov(i,e){let t=[],n=!1;return i.iterChangedRanges((r,s)=>t.push(r,s)),e.iterChangedRanges((r,s,o,a)=>{for(let l=0;l=h&&o<=c&&(n=!0)}}),n}function av(i,e){return i.ranges.length==e.ranges.length&&i.ranges.filter((t,n)=>t.empty!=e.ranges[n].empty).length===0}function gm(i,e){return i.length?e.length?i.concat(e):i:e}var rt=[],lv=200;function Om(i,e){if(i.length){let t=i[i.length-1],n=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-lv));return n.length&&n[n.length-1].eq(e)?i:(n.push(e),Ro(i,i.length-1,1e9,t.setSelAfter(n)))}else return[ft.selection([e])]}function hv(i){let e=i[i.length-1],t=i.slice();return t[i.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function Zh(i,e){if(!i.length)return i;let t=i.length,n=rt;for(;t;){let r=cv(i[t-1],e,n);if(r.changes&&!r.changes.empty||r.effects.length){let s=i.slice(0,t);return s[t-1]=r,s}else e=r.mapped,t--,n=r.selectionsAfter}return n.length?[ft.selection(n)]:rt}function cv(i,e,t){let n=gm(i.selectionsAfter.length?i.selectionsAfter.map(a=>a.map(e)):rt,t);if(!i.changes)return ft.selection(n);let r=i.changes.map(e),s=e.mapDesc(i.changes,!0),o=i.mapped?i.mapped.composeDesc(s):s;return new ft(r,_.mapEffects(i.effects,e),o,i.startSelection.map(s),n)}var fv=/^(input\.type|delete)($|\.)/,_i=class i{constructor(e,t,n=0,r=void 0){this.done=e,this.undone=t,this.prevTime=n,this.prevUserEvent=r}isolate(){return this.prevTime?new i(this.done,this.undone):this}addChanges(e,t,n,r,s){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!n||fv.test(n))&&(!a.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?i.moveByChar(t,e):Ao(t,e))}function Ce(i){return i.textDirectionAt(i.state.selection.main.head)==H.LTR}var wm=i=>bm(i,!Ce(i)),vm=i=>bm(i,Ce(i));function xm(i,e){return ut(i,t=>t.empty?i.moveByGroup(t,e):Ao(t,e))}var uv=i=>xm(i,!Ce(i)),dv=i=>xm(i,Ce(i));var DT=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function pv(i,e,t){if(e.type.prop(t))return!0;let n=e.to-e.from;return n&&(n>2||/[^\s,.;:]/.test(i.sliceDoc(e.from,e.to)))||e.firstChild}function Qo(i,e,t){let n=he(i).resolveInner(e.head),r=t?$.closedBy:$.openedBy;for(let l=e.head;;){let h=t?n.childAfter(l):n.childBefore(l);if(!h)break;pv(i,h,r)?n=h:l=t?h.to:h.from}let s=n.type.prop(r),o,a;return s&&(o=t?ct(i,n.from,1):ct(i,n.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?n.to:n.from,S.cursor(a,t?-1:1)}var mv=i=>ut(i,e=>Qo(i.state,e,!Ce(i))),gv=i=>ut(i,e=>Qo(i.state,e,Ce(i)));function km(i,e){return ut(i,t=>{if(!t.empty)return Ao(t,e);let n=i.moveVertically(t,e);return n.head!=t.head?n:i.moveToLineBoundary(t,e)})}var Sm=i=>km(i,!1),Tm=i=>km(i,!0);function Pm(i){let e=i.scrollDOM.clientHeighto.empty?i.moveVertically(o,e,t.height):Ao(o,e));if(r.eq(n.selection))return!1;let s;if(t.selfScroll){let o=i.coordsAtPos(n.selection.main.head),a=i.scrollDOM.getBoundingClientRect(),l=a.top+t.marginTop,h=a.bottom-t.marginBottom;o&&o.top>l&&o.bottomCm(i,!1),ec=i=>Cm(i,!0);function ri(i,e,t){let n=i.lineBlockAt(e.head),r=i.moveToLineBoundary(e,t);if(r.head==e.head&&r.head!=(t?n.to:n.from)&&(r=i.moveToLineBoundary(e,t,!1)),!t&&r.head==n.from&&n.length){let s=/^\s*/.exec(i.state.sliceDoc(n.from,Math.min(n.from+100,n.to)))[0].length;s&&e.head!=n.from+s&&(r=S.cursor(n.from+s))}return r}var Ov=i=>ut(i,e=>ri(i,e,!0)),yv=i=>ut(i,e=>ri(i,e,!1)),bv=i=>ut(i,e=>ri(i,e,!Ce(i))),wv=i=>ut(i,e=>ri(i,e,Ce(i))),vv=i=>ut(i,e=>S.cursor(i.lineBlockAt(e.head).from,1)),xv=i=>ut(i,e=>S.cursor(i.lineBlockAt(e.head).to,-1));function kv(i,e,t){let n=!1,r=On(i.selection,s=>{let o=ct(i,s.head,-1)||ct(i,s.head,1)||s.head>0&&ct(i,s.head-1,1)||s.headkv(i,e,!1);function st(i,e){let t=On(i.state.selection,n=>{let r=e(n);return S.range(n.anchor,r.head,r.goalColumn,r.bidiLevel||void 0)});return t.eq(i.state.selection)?!1:(i.dispatch(Pt(i.state,t)),!0)}function Rm(i,e){return st(i,t=>i.moveByChar(t,e))}var Em=i=>Rm(i,!Ce(i)),Am=i=>Rm(i,Ce(i));function Qm(i,e){return st(i,t=>i.moveByGroup(t,e))}var Tv=i=>Qm(i,!Ce(i)),Pv=i=>Qm(i,Ce(i));var Cv=i=>st(i,e=>Qo(i.state,e,!Ce(i))),Rv=i=>st(i,e=>Qo(i.state,e,Ce(i)));function Mm(i,e){return st(i,t=>i.moveVertically(t,e))}var _m=i=>Mm(i,!1),Dm=i=>Mm(i,!0);function $m(i,e){return st(i,t=>i.moveVertically(t,e,Pm(i).height))}var sm=i=>$m(i,!1),om=i=>$m(i,!0),Ev=i=>st(i,e=>ri(i,e,!0)),Av=i=>st(i,e=>ri(i,e,!1)),Qv=i=>st(i,e=>ri(i,e,!Ce(i))),Mv=i=>st(i,e=>ri(i,e,Ce(i))),_v=i=>st(i,e=>S.cursor(i.lineBlockAt(e.head).from)),Dv=i=>st(i,e=>S.cursor(i.lineBlockAt(e.head).to)),am=({state:i,dispatch:e})=>(e(Pt(i,{anchor:0})),!0),lm=({state:i,dispatch:e})=>(e(Pt(i,{anchor:i.doc.length})),!0),hm=({state:i,dispatch:e})=>(e(Pt(i,{anchor:i.selection.main.anchor,head:0})),!0),cm=({state:i,dispatch:e})=>(e(Pt(i,{anchor:i.selection.main.anchor,head:i.doc.length})),!0),$v=({state:i,dispatch:e})=>(e(i.update({selection:{anchor:0,head:i.doc.length},userEvent:"select"})),!0),Vv=({state:i,dispatch:e})=>{let t=Mo(i).map(({from:n,to:r})=>S.range(n,Math.min(r+1,i.doc.length)));return e(i.update({selection:S.create(t),userEvent:"select"})),!0},Lv=({state:i,dispatch:e})=>{let t=On(i.selection,n=>{var r;let s=he(i).resolveStack(n.from,1);for(let o=s;o;o=o.next){let{node:a}=o;if((a.from=n.to||a.to>n.to&&a.from<=n.from)&&(!((r=a.parent)===null||r===void 0)&&r.parent))return S.range(a.to,a.from)}return n});return e(Pt(i,t)),!0},qv=({state:i,dispatch:e})=>{let t=i.selection,n=null;return t.ranges.length>1?n=S.create([t.main]):t.main.empty||(n=S.create([S.cursor(t.main.head)])),n?(e(Pt(i,n)),!0):!1};function Mr(i,e){if(i.state.readOnly)return!1;let t="delete.selection",{state:n}=i,r=n.changeByRange(s=>{let{from:o,to:a}=s;if(o==a){let l=e(s);lo&&(t="delete.forward",l=Co(i,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=Co(i,o,!1),a=Co(i,a,!0);return o==a?{range:s}:{changes:{from:o,to:a},range:S.cursor(o,or(i)))n.between(e,e,(r,s)=>{re&&(e=t?s:r)});return e}var Vm=(i,e,t)=>Mr(i,n=>{let r=n.from,{state:s}=i,o=s.doc.lineAt(r),a,l;if(t&&!e&&r>o.from&&rVm(i,!1,!0);var Lm=i=>Vm(i,!0,!1),qm=(i,e)=>Mr(i,t=>{let n=t.head,{state:r}=i,s=r.doc.lineAt(n),o=r.charCategorizer(n);for(let a=null;;){if(n==(e?s.to:s.from)){n==t.head&&s.number!=(e?r.doc.lines:1)&&(n+=e?1:-1);break}let l=ue(s.text,n-s.from,e)+s.from,h=s.text.slice(Math.min(n,l)-s.from,Math.max(n,l)-s.from),c=o(h);if(a!=null&&c!=a)break;(h!=" "||n!=t.head)&&(a=c),n=l}return n}),Bm=i=>qm(i,!1),Bv=i=>qm(i,!0),Xv=i=>Mr(i,e=>{let t=i.lineBlockAt(e.head).to;return e.headMr(i,e=>{let t=i.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),Iv=i=>Mr(i,e=>{let t=i.moveToLineBoundary(e,!0).head;return e.head{if(i.readOnly)return!1;let t=i.changeByRange(n=>({changes:{from:n.from,to:n.to,insert:W.of(["",""])},range:S.cursor(n.from)}));return e(i.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},jv=({state:i,dispatch:e})=>{if(i.readOnly)return!1;let t=i.changeByRange(n=>{if(!n.empty||n.from==0||n.from==i.doc.length)return{range:n};let r=n.from,s=i.doc.lineAt(r),o=r==s.from?r-1:ue(s.text,r-s.from,!1)+s.from,a=r==s.to?r+1:ue(s.text,r-s.from,!0)+s.from;return{changes:{from:o,to:a,insert:i.doc.slice(r,a).append(i.doc.slice(o,r))},range:S.cursor(a)}});return t.changes.empty?!1:(e(i.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Mo(i){let e=[],t=-1;for(let n of i.selection.ranges){let r=i.doc.lineAt(n.from),s=i.doc.lineAt(n.to);if(!n.empty&&n.to==s.from&&(s=i.doc.lineAt(n.to-1)),t>=r.number){let o=e[e.length-1];o.to=s.to,o.ranges.push(n)}else e.push({from:r.from,to:s.to,ranges:[n]});t=s.number+1}return e}function Xm(i,e,t){if(i.readOnly)return!1;let n=[],r=[];for(let s of Mo(i)){if(t?s.to==i.doc.length:s.from==0)continue;let o=i.doc.lineAt(t?s.to+1:s.from-1),a=o.length+1;if(t){n.push({from:s.to,to:o.to},{from:s.from,insert:o.text+i.lineBreak});for(let l of s.ranges)r.push(S.range(Math.min(i.doc.length,l.anchor+a),Math.min(i.doc.length,l.head+a)))}else{n.push({from:o.from,to:s.from},{from:s.to,insert:i.lineBreak+o.text});for(let l of s.ranges)r.push(S.range(l.anchor-a,l.head-a))}}return n.length?(e(i.update({changes:n,scrollIntoView:!0,selection:S.create(r,i.selection.mainIndex),userEvent:"move.line"})),!0):!1}var zv=({state:i,dispatch:e})=>Xm(i,e,!1),Uv=({state:i,dispatch:e})=>Xm(i,e,!0);function Wm(i,e,t){if(i.readOnly)return!1;let n=[];for(let r of Mo(i))t?n.push({from:r.from,insert:i.doc.slice(r.from,r.to)+i.lineBreak}):n.push({from:r.to,insert:i.lineBreak+i.doc.slice(r.from,r.to)});return e(i.update({changes:n,scrollIntoView:!0,userEvent:"input.copyline"})),!0}var Fv=({state:i,dispatch:e})=>Wm(i,e,!1),Hv=({state:i,dispatch:e})=>Wm(i,e,!0),Gv=i=>{if(i.state.readOnly)return!1;let{state:e}=i,t=e.changes(Mo(e).map(({from:r,to:s})=>(r>0?r--:s{let s;if(i.lineWrapping){let o=i.lineBlockAt(r.head),a=i.coordsAtPos(r.head,r.assoc||1);a&&(s=o.bottom+i.documentTop-a.bottom+i.defaultLineHeight/2)}return i.moveVertically(r,!0,s)}).map(t);return i.dispatch({changes:t,selection:n,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Yv(i,e){if(/\(\)|\[\]|\{\}/.test(i.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=he(i).resolveInner(e),n=t.childBefore(e),r=t.childAfter(e),s;return n&&r&&n.to<=e&&r.from>=e&&(s=n.type.prop($.closedBy))&&s.indexOf(r.name)>-1&&i.doc.lineAt(n.to).from==i.doc.lineAt(r.from).from&&!/\S/.test(i.sliceDoc(n.to,r.from))?{from:n.to,to:r.from}:null}var Zv=Im(!1),Jv=Im(!0);function Im(i){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>{let{from:s,to:o}=r,a=e.doc.lineAt(s),l=!i&&s==o&&Yv(e,s);i&&(s=o=(o<=a.to?a:e.doc.lineAt(o)).to);let h=new Ai(e,{simulateBreak:s,simulateDoubleBreak:!!l}),c=So(h,s);for(c==null&&(c=$t(/^\s*/.exec(e.doc.lineAt(s).text)[0],e.tabSize));oa.from&&s{let r=[];for(let o=n.from;o<=n.to;){let a=i.doc.lineAt(o);a.number>t&&(n.empty||n.to>a.from)&&(e(a,r,n),t=a.number),o=a.to+1}let s=i.changes(r);return{changes:r,range:S.range(s.mapPos(n.anchor,1),s.mapPos(n.head,1))}})}var Kv=({state:i,dispatch:e})=>{if(i.readOnly)return!1;let t=Object.create(null),n=new Ai(i,{overrideIndentation:s=>{let o=t[s];return o??-1}}),r=rc(i,(s,o,a)=>{let l=So(n,s.from);if(l==null)return;/\S/.test(s.text)||(l=0);let h=/^\s*/.exec(s.text)[0],c=gn(i,l);(h!=c||a.fromi.readOnly?!1:(e(i.update(rc(i,(t,n)=>{n.push({from:t.from,insert:i.facet(mn)})}),{userEvent:"input.indent"})),!0),tx=({state:i,dispatch:e})=>i.readOnly?!1:(e(i.update(rc(i,(t,n)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let s=$t(r,i.tabSize),o=0,a=gn(i,Math.max(0,s-Pr(i)));for(;o(i.setTabFocusMode(),!0);var nx=[{key:"Ctrl-b",run:wm,shift:Em,preventDefault:!0},{key:"Ctrl-f",run:vm,shift:Am},{key:"Ctrl-p",run:Sm,shift:_m},{key:"Ctrl-n",run:Tm,shift:Dm},{key:"Ctrl-a",run:vv,shift:_v},{key:"Ctrl-e",run:xv,shift:Dv},{key:"Ctrl-d",run:Lm},{key:"Ctrl-h",run:tc},{key:"Ctrl-k",run:Xv},{key:"Ctrl-Alt-h",run:Bm},{key:"Ctrl-o",run:Nv},{key:"Ctrl-t",run:jv},{key:"Ctrl-v",run:ec}],rx=[{key:"ArrowLeft",run:wm,shift:Em,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:uv,shift:Tv,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:bv,shift:Qv,preventDefault:!0},{key:"ArrowRight",run:vm,shift:Am,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:dv,shift:Pv,preventDefault:!0},{mac:"Cmd-ArrowRight",run:wv,shift:Mv,preventDefault:!0},{key:"ArrowUp",run:Sm,shift:_m,preventDefault:!0},{mac:"Cmd-ArrowUp",run:am,shift:hm},{mac:"Ctrl-ArrowUp",run:rm,shift:sm},{key:"ArrowDown",run:Tm,shift:Dm,preventDefault:!0},{mac:"Cmd-ArrowDown",run:lm,shift:cm},{mac:"Ctrl-ArrowDown",run:ec,shift:om},{key:"PageUp",run:rm,shift:sm},{key:"PageDown",run:ec,shift:om},{key:"Home",run:yv,shift:Av,preventDefault:!0},{key:"Mod-Home",run:am,shift:hm},{key:"End",run:Ov,shift:Ev,preventDefault:!0},{key:"Mod-End",run:lm,shift:cm},{key:"Enter",run:Zv},{key:"Mod-a",run:$v},{key:"Backspace",run:tc,shift:tc},{key:"Delete",run:Lm},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Bm},{key:"Mod-Delete",mac:"Alt-Delete",run:Bv},{mac:"Mod-Backspace",run:Wv},{mac:"Mod-Delete",run:Iv}].concat(nx.map(i=>({mac:i.key,run:i.run,shift:i.shift}))),Nm=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:mv,shift:Cv},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:gv,shift:Rv},{key:"Alt-ArrowUp",run:zv},{key:"Shift-Alt-ArrowUp",run:Fv},{key:"Alt-ArrowDown",run:Uv},{key:"Shift-Alt-ArrowDown",run:Hv},{key:"Escape",run:qv},{key:"Mod-Enter",run:Jv},{key:"Alt-l",mac:"Ctrl-l",run:Vv},{key:"Mod-i",run:Lv,preventDefault:!0},{key:"Mod-[",run:tx},{key:"Mod-]",run:ex},{key:"Mod-Alt-\\",run:Kv},{key:"Shift-Mod-k",run:Gv},{key:"Shift-Mod-\\",run:Sv},{key:"Mod-/",run:Gw},{key:"Alt-A",run:Zw},{key:"Ctrl-m",mac:"Shift-Alt-m",run:ix}].concat(rx);function U(){var i=arguments[0];typeof i=="string"&&(i=document.createElement(i));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var r=t[n];typeof r=="string"?i.setAttribute(n,r):r!=null&&(i[n]=r)}e++}for(;ei.normalize("NFKD"):i=>i,oi=class{constructor(e,t,n=0,r=e.length,s,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(n,r),this.bufferStart=n,this.normalize=s?a=>s(zm(a)):zm,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return ce(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=Fn(e),n=this.bufferStart+this.bufferPos;this.bufferPos+=Ee(e);let r=this.normalize(t);for(let s=0,o=n;;s++){let a=r.charCodeAt(s),l=this.match(a,o,this.bufferPos+this.bufferStart);if(s==r.length-1){if(l)return this.value=l,this;break}o==n&&sthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let n=this.curLineStart+t.index,r=n+t[0].length;if(this.matchPos=qo(this.text,r+(n==r?1:0)),n==this.curLineStart+this.curLine.length&&this.nextLine(),(nthis.value.to)&&(!this.test||this.test(n,r,t)))return this.value={from:n,to:r,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=n||r.to<=t){let a=new i(t,e.sliceString(t,n));return sc.set(e,a),a}if(r.from==t&&r.to==n)return r;let{text:s,from:o}=r;return o>t&&(s=e.sliceString(t,o)+s,o=t),r.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let n=this.flat.from+t.index,r=n+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(n,r,t)))return this.value={from:n,to:r,match:t},this.matchPos=qo(this.text,r+(n==r?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Vo.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<"u"&&($o.prototype[Symbol.iterator]=Lo.prototype[Symbol.iterator]=function(){return this});function sx(i){try{return new RegExp(i,fc),!0}catch{return!1}}function qo(i,e){if(e>=i.length)return e;let t=i.lineAt(e),n;for(;e=56320&&n<57344;)e++;return e}function oc(i){let e=String(i.state.doc.lineAt(i.state.selection.main.head).number),t=U("input",{class:"cm-textfield",name:"line",value:e}),n=U("form",{class:"cm-gotoLine",onkeydown:s=>{s.keyCode==27?(s.preventDefault(),i.dispatch({effects:Bo.of(!1)}),i.focus()):s.keyCode==13&&(s.preventDefault(),r())},onsubmit:s=>{s.preventDefault(),r()}},U("label",i.state.phrase("Go to line"),": ",t)," ",U("button",{class:"cm-button",type:"submit"},i.state.phrase("go")));function r(){let s=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(t.value);if(!s)return;let{state:o}=i,a=o.doc.lineAt(o.selection.main.head),[,l,h,c,f]=s,u=c?+c.slice(1):0,d=h?+h:a.number;if(h&&f){let g=d/100;l&&(g=g*(l=="-"?-1:1)+a.number/o.doc.lines),d=Math.round(o.doc.lines*g)}else h&&l&&(d=d*(l=="-"?-1:1)+a.number);let m=o.doc.line(Math.max(1,Math.min(o.doc.lines,d))),p=S.cursor(m.from+Math.max(0,Math.min(u,m.length)));i.dispatch({effects:[Bo.of(!1),E.scrollIntoView(p.from,{y:"center"})],selection:p}),i.focus()}return{dom:n}}var Bo=_.define(),Um=te.define({create(){return!0},update(i,e){for(let t of e.effects)t.is(Bo)&&(i=t.value);return i},provide:i=>Ti.from(i,e=>e?oc:null)}),ox=i=>{let e=Pi(i,oc);if(!e){let t=[Bo.of(!0)];i.state.field(Um,!1)==null&&t.push(_.appendConfig.of([Um,ax])),i.dispatch({effects:t}),e=Pi(i,oc)}return e&&e.dom.querySelector("input").select(),!0},ax=E.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),lx={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Ym=A.define({combine(i){return Te(i,lx,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function Zm(i){let e=[dx,ux];return i&&e.push(Ym.of(i)),e}var hx=M.mark({class:"cm-selectionMatch"}),cx=M.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function Fm(i,e,t,n){return(t==0||i(e.sliceDoc(t-1,t))!=F.Word)&&(n==e.doc.length||i(e.sliceDoc(n,n+1))!=F.Word)}function fx(i,e,t,n){return i(e.sliceDoc(t,t+1))==F.Word&&i(e.sliceDoc(n-1,n))==F.Word}var ux=re.fromClass(class{constructor(i){this.decorations=this.getDeco(i)}update(i){(i.selectionSet||i.docChanged||i.viewportChanged)&&(this.decorations=this.getDeco(i.view))}getDeco(i){let e=i.state.facet(Ym),{state:t}=i,n=t.selection;if(n.ranges.length>1)return M.none;let r=n.main,s,o=null;if(r.empty){if(!e.highlightWordAroundCursor)return M.none;let l=t.wordAt(r.head);if(!l)return M.none;o=t.charCategorizer(r.head),s=t.sliceDoc(l.from,l.to)}else{let l=r.to-r.from;if(l200)return M.none;if(e.wholeWords){if(s=t.sliceDoc(r.from,r.to),o=t.charCategorizer(r.head),!(Fm(o,t,r.from,r.to)&&fx(o,t,r.from,r.to)))return M.none}else if(s=t.sliceDoc(r.from,r.to),!s)return M.none}let a=[];for(let l of i.visibleRanges){let h=new oi(t.doc,s,l.from,l.to);for(;!h.next().done;){let{from:c,to:f}=h.value;if((!o||Fm(o,t,c,f))&&(r.empty&&c<=r.from&&f>=r.to?a.push(cx.range(c,f)):(c>=r.to||f<=r.from)&&a.push(hx.range(c,f)),a.length>e.maxMatches))return M.none}}return M.set(a)}},{decorations:i=>i.decorations}),dx=E.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),px=({state:i,dispatch:e})=>{let{selection:t}=i,n=S.create(t.ranges.map(r=>i.wordAt(r.head)||S.cursor(r.head)),t.mainIndex);return n.eq(t)?!1:(e(i.update({selection:n})),!0)};function mx(i,e){let{main:t,ranges:n}=i.selection,r=i.wordAt(t.head),s=r&&r.from==t.from&&r.to==t.to;for(let o=!1,a=new oi(i.doc,e,n[n.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new oi(i.doc,e,0,Math.max(0,n[n.length-1].from-1)),o=!0}else{if(o&&n.some(l=>l.from==a.value.from))continue;if(s){let l=i.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}var gx=({state:i,dispatch:e})=>{let{ranges:t}=i.selection;if(t.some(s=>s.from===s.to))return px({state:i,dispatch:e});let n=i.sliceDoc(t[0].from,t[0].to);if(i.selection.ranges.some(s=>i.sliceDoc(s.from,s.to)!=n))return!1;let r=mx(i,n);return r?(e(i.update({selection:i.selection.addRange(S.range(r.from,r.to),!1),effects:E.scrollIntoView(r.to)})),!0):!1},wn=A.define({combine(i){return Te(i,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new cc(e),scrollToMatch:e=>E.scrollIntoView(e)})}});var Xo=class{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||sx(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,n)=>n=="n"?` +`:n=="r"?"\r":n=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new lc(this):new ac(this)}getCursor(e,t=0,n){let r=e.doc?e:N.create({doc:e});return n==null&&(n=r.doc.length),this.regexp?bn(this,r,t,n):yn(this,r,t,n)}},Wo=class{constructor(e){this.spec=e}};function yn(i,e,t,n){return new oi(e.doc,i.unquoted,t,n,i.caseSensitive?void 0:r=>r.toLowerCase(),i.wholeWord?Ox(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function Ox(i,e){return(t,n,r,s)=>((s>t||s+r.length=t)return null;r.push(n.value)}return r}highlight(e,t,n,r){let s=yn(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(n+this.spec.unquoted.length,e.doc.length));for(;!s.next().done;)r(s.value.from,s.value.to)}};function bn(i,e,t,n){return new $o(e.doc,i.search,{ignoreCase:!i.caseSensitive,test:i.wholeWord?yx(e.charCategorizer(e.selection.main.head)):void 0},t,n)}function Io(i,e){return i.slice(ue(i,e,!1),e)}function No(i,e){return i.slice(e,ue(i,e))}function yx(i){return(e,t,n)=>!n[0].length||(i(Io(n.input,n.index))!=F.Word||i(No(n.input,n.index))!=F.Word)&&(i(No(n.input,n.index+n[0].length))!=F.Word||i(Io(n.input,n.index+n[0].length))!=F.Word)}var lc=class extends Wo{nextMatch(e,t,n){let r=bn(this.spec,e,n,e.doc.length).next();return r.done&&(r=bn(this.spec,e,0,t).next()),r.done?null:r.value}prevMatchInRange(e,t,n){for(let r=1;;r++){let s=Math.max(t,n-r*1e4),o=bn(this.spec,e,s,n),a=null;for(;!o.next().done;)a=o.value;if(a&&(s==t||a.from>s+10))return a;if(s==t)return null}}prevMatch(e,t,n){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,n,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g,(t,n)=>n=="$"?"$":n=="&"?e.match[0]:n!="0"&&+n=t)return null;r.push(n.value)}return r}highlight(e,t,n,r){let s=bn(this.spec,e,Math.max(0,t-250),Math.min(n+250,e.doc.length));for(;!s.next().done;)r(s.value.from,s.value.to)}},Dr=_.define(),uc=_.define(),si=te.define({create(i){return new _r(hc(i).create(),null)},update(i,e){for(let t of e.effects)t.is(Dr)?i=new _r(t.value.create(),i.panel):t.is(uc)&&(i=new _r(i.query,t.value?dc:null));return i},provide:i=>Ti.from(i,e=>e.panel)});var _r=class{constructor(e,t){this.query=e,this.panel=t}},bx=M.mark({class:"cm-searchMatch"}),wx=M.mark({class:"cm-searchMatch cm-searchMatch-selected"}),vx=re.fromClass(class{constructor(i){this.view=i,this.decorations=this.highlight(i.state.field(si))}update(i){let e=i.state.field(si);(e!=i.startState.field(si)||i.docChanged||i.selectionSet||i.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:i,panel:e}){if(!e||!i.spec.valid)return M.none;let{view:t}=this,n=new lt;for(let r=0,s=t.visibleRanges,o=s.length;rs[r+1].from-2*250;)l=s[++r].to;i.highlight(t.state,a,l,(h,c)=>{let f=t.state.selection.ranges.some(u=>u.from==h&&u.to==c);n.add(h,c,f?wx:bx)})}return n.finish()}},{decorations:i=>i.decorations});function $r(i){return e=>{let t=e.state.field(si,!1);return t&&t.query.spec.valid?i(e,t):eg(e)}}var jo=$r((i,{query:e})=>{let{to:t}=i.state.selection.main,n=e.nextMatch(i.state,t,t);if(!n)return!1;let r=S.single(n.from,n.to),s=i.state.facet(wn);return i.dispatch({selection:r,effects:[pc(i,n),s.scrollToMatch(r.main,i)],userEvent:"select.search"}),Km(i),!0}),zo=$r((i,{query:e})=>{let{state:t}=i,{from:n}=t.selection.main,r=e.prevMatch(t,n,n);if(!r)return!1;let s=S.single(r.from,r.to),o=i.state.facet(wn);return i.dispatch({selection:s,effects:[pc(i,r),o.scrollToMatch(s.main,i)],userEvent:"select.search"}),Km(i),!0}),xx=$r((i,{query:e})=>{let t=e.matchAll(i.state,1e3);return!t||!t.length?!1:(i.dispatch({selection:S.create(t.map(n=>S.range(n.from,n.to))),userEvent:"select.search.matches"}),!0)}),kx=({state:i,dispatch:e})=>{let t=i.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:n,to:r}=t.main,s=[],o=0;for(let a=new oi(i.doc,i.sliceDoc(n,r));!a.next().done;){if(s.length>1e3)return!1;a.value.from==n&&(o=s.length),s.push(S.range(a.value.from,a.value.to))}return e(i.update({selection:S.create(s,o),userEvent:"select.search.matches"})),!0},Hm=$r((i,{query:e})=>{let{state:t}=i,{from:n,to:r}=t.selection.main;if(t.readOnly)return!1;let s=e.nextMatch(t,n,n);if(!s)return!1;let o=[],a,l,h=[];if(s.from==n&&s.to==r&&(l=t.toText(e.getReplacement(s)),o.push({from:s.from,to:s.to,insert:l}),s=e.nextMatch(t,s.from,s.to),h.push(E.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(n).number)+"."))),s){let c=o.length==0||o[0].from>=s.to?0:s.to-s.from-l.length;a=S.single(s.from-c,s.to-c),h.push(pc(i,s)),h.push(t.facet(wn).scrollToMatch(a.main,i))}return i.dispatch({changes:o,selection:a,effects:h,userEvent:"input.replace"}),!0}),Sx=$r((i,{query:e})=>{if(i.state.readOnly)return!1;let t=e.matchAll(i.state,1e9).map(r=>{let{from:s,to:o}=r;return{from:s,to:o,insert:e.getReplacement(r)}});if(!t.length)return!1;let n=i.state.phrase("replaced $ matches",t.length)+".";return i.dispatch({changes:t,effects:E.announce.of(n),userEvent:"input.replace.all"}),!0});function dc(i){return i.state.facet(wn).createPanel(i)}function hc(i,e){var t,n,r,s,o;let a=i.selection.main,l=a.empty||a.to>a.from+100?"":i.sliceDoc(a.from,a.to);if(e&&!l)return e;let h=i.facet(wn);return new Xo({search:((t=e?.literal)!==null&&t!==void 0?t:h.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(n=e?.caseSensitive)!==null&&n!==void 0?n:h.caseSensitive,literal:(r=e?.literal)!==null&&r!==void 0?r:h.literal,regexp:(s=e?.regexp)!==null&&s!==void 0?s:h.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:h.wholeWord})}function Jm(i){let e=Pi(i,dc);return e&&e.dom.querySelector("[main-field]")}function Km(i){let e=Jm(i);e&&e==i.root.activeElement&&e.select()}var eg=i=>{let e=i.state.field(si,!1);if(e&&e.panel){let t=Jm(i);if(t&&t!=i.root.activeElement){let n=hc(i.state,e.query.spec);n.valid&&i.dispatch({effects:Dr.of(n)}),t.focus(),t.select()}}else i.dispatch({effects:[uc.of(!0),e?Dr.of(hc(i.state,e.query.spec)):_.appendConfig.of(Px)]});return!0},tg=i=>{let e=i.state.field(si,!1);if(!e||!e.panel)return!1;let t=Pi(i,dc);return t&&t.dom.contains(i.root.activeElement)&&i.focus(),i.dispatch({effects:uc.of(!1)}),!0},ig=[{key:"Mod-f",run:eg,scope:"editor search-panel"},{key:"F3",run:jo,shift:zo,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:jo,shift:zo,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:tg,scope:"editor search-panel"},{key:"Mod-Shift-l",run:kx},{key:"Mod-Alt-g",run:ox},{key:"Mod-d",run:gx,preventDefault:!0}],cc=class{constructor(e){this.view=e;let t=this.query=e.state.field(si).query.spec;this.commit=this.commit.bind(this),this.searchField=U("input",{value:t.search,placeholder:Fe(e,"Find"),"aria-label":Fe(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=U("input",{value:t.replace,placeholder:Fe(e,"Replace"),"aria-label":Fe(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=U("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=U("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=U("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function n(r,s,o){return U("button",{class:"cm-button",name:r,onclick:s,type:"button"},o)}this.dom=U("div",{onkeydown:r=>this.keydown(r),class:"cm-search"},[this.searchField,n("next",()=>jo(e),[Fe(e,"next")]),n("prev",()=>zo(e),[Fe(e,"previous")]),n("select",()=>xx(e),[Fe(e,"all")]),U("label",null,[this.caseField,Fe(e,"match case")]),U("label",null,[this.reField,Fe(e,"regexp")]),U("label",null,[this.wordField,Fe(e,"by word")]),...e.state.readOnly?[]:[U("br"),this.replaceField,n("replace",()=>Hm(e),[Fe(e,"replace")]),n("replaceAll",()=>Sx(e),[Fe(e,"replace all")])],U("button",{name:"close",onclick:()=>tg(e),"aria-label":Fe(e,"close"),type:"button"},["\xD7"])])}commit(){let e=new Xo({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:Dr.of(e)}))}keydown(e){lp(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?zo:jo)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),Hm(this.view))}update(e){for(let t of e.transactions)for(let n of t.effects)n.is(Dr)&&!n.value.eq(this.query)&&this.setQuery(n.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(wn).top}};function Fe(i,e){return i.state.phrase(e)}var _o=30,Do=/[\s\.,:;?!]/;function pc(i,{from:e,to:t}){let n=i.state.doc.lineAt(e),r=i.state.doc.lineAt(t).to,s=Math.max(n.from,e-_o),o=Math.min(r,t+_o),a=i.state.sliceDoc(s,o);if(s!=n.from){for(let l=0;l<_o;l++)if(!Do.test(a[l+1])&&Do.test(a[l])){a=a.slice(l);break}}if(o!=r){for(let l=a.length-1;l>a.length-_o;l--)if(!Do.test(a[l-1])&&Do.test(a[l])){a=a.slice(0,l);break}}return E.announce.of(`${i.state.phrase("current match")}. ${a} ${i.state.phrase("on line")} ${n.number}.`)}var Tx=E.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),Px=[si,Qe.low(vx),Tx];var Fo=class{constructor(e,t,n){this.state=e,this.pos=t,this.explicit=n,this.abortListeners=[]}tokenBefore(e){let t=he(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),n=Math.max(t.from,this.pos-250),r=t.text.slice(n-t.from,this.pos-t.from),s=r.search(ug(e,!1));return s<0?null:{from:n+s,to:this.pos,text:r.slice(s)}}get aborted(){return this.abortListeners==null}addEventListener(e,t){e=="abort"&&this.abortListeners&&this.abortListeners.push(t)}};function ng(i){let e=Object.keys(i).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Cx(i){let e=Object.create(null),t=Object.create(null);for(let{label:r}of i){e[r[0]]=!0;for(let s=1;stypeof r=="string"?{label:r}:r),[t,n]=e.every(r=>/^\w+$/.test(r.label))?[/\w*$/,/\w+$/]:Cx(e);return r=>{let s=r.matchBefore(n);return s||r.explicit?{from:s?s.from:r.pos,options:e,validFor:t}:null}}function fg(i,e){return t=>{for(let n=he(t.state).resolveInner(t.pos,-1);n;n=n.parent){if(i.indexOf(n.name)>-1)return null;if(n.type.isTop)break}return e(t)}}var Ho=class{constructor(e,t,n,r){this.completion=e,this.source=t,this.match=n,this.score=r}};function ai(i){return i.selection.main.from}function ug(i,e){var t;let{source:n}=i,r=e&&n[0]!="^",s=n[n.length-1]!="$";return!r&&!s?i:new RegExp(`${r?"^":""}(?:${n})${s?"$":""}`,(t=i.flags)!==null&&t!==void 0?t:i.ignoreCase?"i":"")}var Rc=Le.define();function Rx(i,e,t,n){let{main:r}=i.selection,s=t-r.from,o=n-r.from;return Object.assign(Object.assign({},i.changeByRange(a=>a!=r&&t!=n&&i.sliceDoc(a.from+s,a.from+o)!=i.sliceDoc(t,n)?{range:a}:{changes:{from:a.from+s,to:n==r.from?a.to:a.from+o,insert:e},range:S.cursor(a.from+s+e.length)})),{scrollIntoView:!0,userEvent:"input.complete"})}var rg=new WeakMap;function Ex(i){if(!Array.isArray(i))return i;let e=rg.get(i);return e||rg.set(i,e=Cc(i)),e}var Go=_.define(),Vr=_.define(),Oc=class{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t=48&&w<=57||w>=97&&w<=122?2:w>=65&&w<=90?1:0:(P=Fn(w))!=P.toLowerCase()?1:P!=P.toUpperCase()?2:0;(!y||C==1&&g||x==0&&C!=0)&&(t[f]==w||n[f]==w&&(u=!0)?o[f++]=y:o.length&&(O=!1)),x=C,y+=Ee(w)}return f==l&&o[0]==0&&O?this.result(-100+(u?-200:0),o,e):d==l&&m==0?this.ret(-200-e.length+(p==e.length?0:-100),[0,p]):a>-1?this.ret(-700-e.length,[a,a+this.pattern.length]):d==l?this.ret(-900-e.length,[m,p]):f==l?this.result(-100+(u?-200:0)+-700+(O?0:-1100),o,e):t.length==2?null:this.result((r[0]?-700:0)+-200+-1100,r,e)}result(e,t,n){let r=[],s=0;for(let o of t){let a=o+(this.astral?Ee(ce(n,o)):1);s&&r[s-1]==o?r[s-1]=a:(r[s++]=o,r[s++]=a)}return this.ret(e-n.length,r)}},yc=class{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:Ax,filterStrict:!1,compareCompletions:(e,t)=>e.label.localeCompare(t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>n=>sg(e(n),t(n)),optionClass:(e,t)=>n=>sg(e(n),t(n)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function sg(i,e){return i?e?i+" "+e:i:e}function Ax(i,e,t,n,r,s){let o=i.textDirection==H.RTL,a=o,l=!1,h="top",c,f,u=e.left-r.left,d=r.right-e.right,m=n.right-n.left,p=n.bottom-n.top;if(a&&u=p||y>e.top?c=t.bottom-e.top:(h="bottom",c=e.bottom-t.top)}let g=(e.bottom-e.top)/s.offsetHeight,O=(e.right-e.left)/s.offsetWidth;return{style:`${h}: ${c/g}px; max-width: ${f/O}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":a?"left":"right")}}function Qx(i){let e=i.addToOptions.slice();return i.icons&&e.push({render(t){let n=document.createElement("div");return n.classList.add("cm-completionIcon"),t.type&&n.classList.add(...t.type.split(/\s+/g).map(r=>"cm-completionIcon-"+r)),n.setAttribute("aria-hidden","true"),n},position:20}),e.push({render(t,n,r,s){let o=document.createElement("span");o.className="cm-completionLabel";let a=t.displayLabel||t.label,l=0;for(let h=0;hl&&o.appendChild(document.createTextNode(a.slice(l,c)));let u=o.appendChild(document.createElement("span"));u.appendChild(document.createTextNode(a.slice(c,f))),u.className="cm-completionMatchedText",l=f}return lt.position-n.position).map(t=>t.render)}function mc(i,e,t){if(i<=t)return{from:0,to:i};if(e<0&&(e=0),e<=i>>1){let r=Math.floor(e/t);return{from:r*t,to:(r+1)*t}}let n=Math.floor((i-e)/t);return{from:i-(n+1)*t,to:i-n*t}}var bc=class{constructor(e,t,n){this.view=e,this.stateField=t,this.applyCompletion=n,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let r=e.state.field(t),{options:s,selected:o}=r.open,a=e.state.facet(ve);this.optionContent=Qx(a),this.optionClass=a.optionClass,this.tooltipClass=a.tooltipClass,this.range=mc(s.length,o,a.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",l=>{let{options:h}=e.state.field(t).open;for(let c=l.target,f;c&&c!=this.dom;c=c.parentNode)if(c.nodeName=="LI"&&(f=/-(\d+)$/.exec(c.id))&&+f[1]{let h=e.state.field(this.stateField,!1);h&&h.tooltip&&e.state.facet(ve).closeOnBlur&&l.relatedTarget!=e.contentDOM&&e.dispatch({effects:Vr.of(null)})}),this.showOptions(s,r.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let n=e.state.field(this.stateField),r=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),n!=r){let{options:s,selected:o,disabled:a}=n.open;(!r.open||r.open.options!=s)&&(this.range=mc(s.length,o,e.state.facet(ve).maxRenderedOptions),this.showOptions(s,n.id)),this.updateSel(),a!=((t=r.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let n of this.currentClass.split(" "))n&&this.dom.classList.remove(n);for(let n of t.split(" "))n&&this.dom.classList.add(n);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;if((t.selected>-1&&t.selected=this.range.to)&&(this.range=mc(t.options.length,t.selected,this.view.state.facet(ve).maxRenderedOptions),this.showOptions(t.options,e.id)),this.updateSelectedOption(t.selected)){this.destroyInfo();let{completion:n}=t.options[t.selected],{info:r}=n;if(!r)return;let s=typeof r=="string"?document.createTextNode(r):r(n);if(!s)return;"then"in s?s.then(o=>{o&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(o,n)}).catch(o=>we(this.view.state,o,"completion info")):this.addInfoPane(s,n)}}addInfoPane(e,t){this.destroyInfo();let n=this.info=document.createElement("div");if(n.className="cm-tooltip cm-completionInfo",e.nodeType!=null)n.appendChild(e),this.infoDestroy=null;else{let{dom:r,destroy:s}=e;n.appendChild(r),this.infoDestroy=s||null}this.dom.appendChild(n),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let n=this.list.firstChild,r=this.range.from;n;n=n.nextSibling,r++)n.nodeName!="LI"||!n.id?r--:r==e?n.hasAttribute("aria-selected")||(n.setAttribute("aria-selected","true"),t=n):n.hasAttribute("aria-selected")&&n.removeAttribute("aria-selected");return t&&_x(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),n=this.info.getBoundingClientRect(),r=e.getBoundingClientRect(),s=this.space;if(!s){let o=this.dom.ownerDocument.defaultView||window;s={left:0,top:0,right:o.innerWidth,bottom:o.innerHeight}}return r.top>Math.min(s.bottom,t.bottom)-10||r.bottomn.from||n.from==0))if(s=u,typeof h!="string"&&h.header)r.appendChild(h.header(h));else{let d=r.appendChild(document.createElement("completion-section"));d.textContent=u}}let c=r.appendChild(document.createElement("li"));c.id=t+"-"+o,c.setAttribute("role","option");let f=this.optionClass(a);f&&(c.className=f);for(let u of this.optionContent){let d=u(a,this.view.state,this.view,l);d&&c.appendChild(d)}}return n.from&&r.classList.add("cm-completionListIncompleteTop"),n.tonew bc(t,i,e)}function _x(i,e){let t=i.getBoundingClientRect(),n=e.getBoundingClientRect(),r=t.height/i.offsetHeight;n.topt.bottom&&(i.scrollTop+=(n.bottom-t.bottom)/r)}function og(i){return(i.boost||0)*100+(i.apply?10:0)+(i.info?5:0)+(i.type?1:0)}function Dx(i,e){let t=[],n=null,r=h=>{t.push(h);let{section:c}=h.completion;if(c){n||(n=[]);let f=typeof c=="string"?c:c.name;n.some(u=>u.name==f)||n.push(typeof c=="string"?{name:f}:c)}},s=e.facet(ve);for(let h of i)if(h.hasResult()){let c=h.result.getMatch;if(h.result.filter===!1)for(let f of h.result.options)r(new Ho(f,h.source,c?c(f):[],1e9-t.length));else{let f=e.sliceDoc(h.from,h.to),u,d=s.filterStrict?new yc(f):new Oc(f);for(let m of h.result.options)if(u=d.match(m.label)){let p=m.displayLabel?c?c(m,u.matched):[]:u.matched;r(new Ho(m,h.source,p,u.score+(m.boost||0)))}}}if(n){let h=Object.create(null),c=0,f=(u,d)=>{var m,p;return((m=u.rank)!==null&&m!==void 0?m:1e9)-((p=d.rank)!==null&&p!==void 0?p:1e9)||(u.namef.score-c.score||l(c.completion,f.completion))){let c=h.completion;!a||a.label!=c.label||a.detail!=c.detail||a.type!=null&&c.type!=null&&a.type!=c.type||a.apply!=c.apply||a.boost!=c.boost?o.push(h):og(h.completion)>og(a)&&(o[o.length-1]=h),a=h.completion}return o}var wc=class i{constructor(e,t,n,r,s,o){this.options=e,this.attrs=t,this.tooltip=n,this.timestamp=r,this.selected=s,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new i(this.options,ag(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,n,r,s){let o=Dx(e,t);if(!o.length)return r&&e.some(l=>l.state==1)?new i(r.options,r.attrs,r.tooltip,r.timestamp,r.selected,!0):null;let a=t.facet(ve).selectOnOpen?0:-1;if(r&&r.selected!=a&&r.selected!=-1){let l=r.options[r.selected].completion;for(let h=0;hh.hasResult()?Math.min(l,h.from):l,1e8),create:Xx,above:s.aboveCursor},r?r.timestamp:Date.now(),a,!1)}map(e){return new i(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:e.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}},vc=class i{constructor(e,t,n){this.active=e,this.id=t,this.open=n}static start(){return new i(qx,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,n=t.facet(ve),s=(n.override||t.languageDataAt("autocomplete",ai(t)).map(Ex)).map(a=>(this.active.find(h=>h.source==a)||new Ct(a,this.active.some(h=>h.state!=0)?1:0)).update(e,n));s.length==this.active.length&&s.every((a,l)=>a==this.active[l])&&(s=this.active);let o=this.open;o&&e.docChanged&&(o=o.map(e.changes)),e.selection||s.some(a=>a.hasResult()&&e.changes.touchesRange(a.from,a.to))||!$x(s,this.active)?o=wc.build(s,t,this.id,o,n):o&&o.disabled&&!s.some(a=>a.state==1)&&(o=null),!o&&s.every(a=>a.state!=1)&&s.some(a=>a.hasResult())&&(s=s.map(a=>a.hasResult()?new Ct(a.source,0):a));for(let a of e.effects)a.is(pg)&&(o=o&&o.setSelected(a.value,this.id));return s==this.active&&o==this.open?this:new i(s,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Vx:Lx}};function $x(i,e){if(i==e)return!0;for(let t=0,n=0;;){for(;t-1&&(t["aria-activedescendant"]=i+"-"+e),t}var qx=[];function xc(i,e){if(i.isUserEvent("input.complete")){let t=i.annotation(Rc);if(t&&e.activateOnCompletion(t))return"input"}return i.isUserEvent("input.type")?"input":i.isUserEvent("delete.backward")?"delete":null}var Ct=class i{constructor(e,t,n=-1){this.source=e,this.state=t,this.explicitPos=n}hasResult(){return!1}update(e,t){let n=xc(e,t),r=this;n?r=r.handleUserEvent(e,n,t):e.docChanged?r=r.handleChange(e):e.selection&&r.state!=0&&(r=new i(r.source,0));for(let s of e.effects)if(s.is(Go))r=new i(r.source,1,s.value?ai(e.state):-1);else if(s.is(Vr))r=new i(r.source,0);else if(s.is(dg))for(let o of s.value)o.source==r.source&&(r=o);return r}handleUserEvent(e,t,n){return t=="delete"||!n.activateOnTyping?this.map(e.changes):new i(this.source,1)}handleChange(e){return e.changes.touchesRange(ai(e.startState))?new i(this.source,0):this.map(e.changes)}map(e){return e.empty||this.explicitPos<0?this:new i(this.source,this.state,e.mapPos(this.explicitPos))}},Yo=class i extends Ct{constructor(e,t,n,r,s){super(e,2,t),this.result=n,this.from=r,this.to=s}hasResult(){return!0}handleUserEvent(e,t,n){var r;let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let o=e.changes.mapPos(this.from),a=e.changes.mapPos(this.to,1),l=ai(e.state);if((this.explicitPos<0?l<=o:la||!s||t=="delete"&&ai(e.startState)==this.from)return new Ct(this.source,t=="input"&&n.activateOnTyping?1:0);let h=this.explicitPos<0?-1:e.changes.mapPos(this.explicitPos);return Bx(s.validFor,e.state,o,a)?new i(this.source,h,s,o,a):s.update&&(s=s.update(s,o,a,new Fo(e.state,l,h>=0)))?new i(this.source,h,s,s.from,(r=s.to)!==null&&r!==void 0?r:ai(e.state)):new Ct(this.source,1,h)}handleChange(e){return e.changes.touchesRange(this.from,this.to)?new Ct(this.source,0):this.map(e.changes)}map(e){return e.empty?this:(this.result.map?this.result.map(this.result,e):this.result)?new i(this.source,this.explicitPos<0?-1:e.mapPos(this.explicitPos),this.result,e.mapPos(this.from),e.mapPos(this.to,1)):new Ct(this.source,0)}};function Bx(i,e,t,n){if(!i)return!1;let r=e.sliceDoc(t,n);return typeof i=="function"?i(r,t,n,e):ug(i,!0).test(r)}var dg=_.define({map(i,e){return i.map(t=>t.map(e))}}),pg=_.define(),Xe=te.define({create(){return vc.start()},update(i,e){return i.update(e)},provide:i=>[gr.from(i,e=>e.tooltip),E.contentAttributes.from(i,e=>e.attrs)]});function Ec(i,e){let t=e.completion.apply||e.completion.label,n=i.state.field(Xe).active.find(r=>r.source==e.source);return n instanceof Yo?(typeof t=="string"?i.dispatch(Object.assign(Object.assign({},Rx(i.state,t,n.from,n.to)),{annotations:Rc.of(e.completion)})):t(i,e.completion,n.from,n.to),!0):!1}var Xx=Mx(Xe,Ec);function Uo(i,e="option"){return t=>{let n=t.state.field(Xe,!1);if(!n||!n.open||n.open.disabled||Date.now()-n.open.timestamp-1?n.open.selected+r*(i?1:-1):i?0:o-1;return a<0?a=e=="page"?0:o-1:a>=o&&(a=e=="page"?o-1:0),t.dispatch({effects:pg.of(a)}),!0}}var Wx=i=>{let e=i.state.field(Xe,!1);return i.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestampi.state.field(Xe,!1)?(i.dispatch({effects:Go.of(!0)}),!0):!1,Nx=i=>{let e=i.state.field(Xe,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(i.dispatch({effects:Vr.of(null)}),!0)},kc=class{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}},jx=50,zx=1e3,Ux=re.fromClass(class{constructor(i){this.view=i,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of i.state.field(Xe).active)e.state==1&&this.startQuery(e)}update(i){let e=i.state.field(Xe),t=i.state.facet(ve);if(!i.selectionSet&&!i.docChanged&&i.startState.field(Xe)==e)return;let n=i.transactions.some(s=>(s.selection||s.docChanged)&&!xc(s,t));for(let s=0;sjx&&Date.now()-o.time>zx){for(let a of o.context.abortListeners)try{a()}catch(l){we(this.view.state,l)}o.context.abortListeners=null,this.running.splice(s--,1)}else o.updates.push(...i.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),i.transactions.some(s=>s.effects.some(o=>o.is(Go)))&&(this.pendingStart=!0);let r=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(s=>s.state==1&&!this.running.some(o=>o.active.source==s.source))?setTimeout(()=>this.startUpdate(),r):-1,this.composing!=0)for(let s of i.transactions)xc(s,t)=="input"?this.composing=2:this.composing==2&&s.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:i}=this.view,e=i.field(Xe);for(let t of e.active)t.state==1&&!this.running.some(n=>n.active.source==t.source)&&this.startQuery(t)}startQuery(i){let{state:e}=this.view,t=ai(e),n=new Fo(e,t,i.explicitPos==t),r=new kc(i,n);this.running.push(r),Promise.resolve(i.source(n)).then(s=>{r.context.aborted||(r.done=s||null,this.scheduleAccept())},s=>{this.view.dispatch({effects:Vr.of(null)}),we(this.view.state,s)})}scheduleAccept(){this.running.every(i=>i.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ve).updateSyncTime))}accept(){var i;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(ve);for(let n=0;no.source==r.active.source);if(s&&s.state==1)if(r.done==null){let o=new Ct(r.active.source,0);for(let a of r.updates)o=o.update(a,t);o.state!=1&&e.push(o)}else this.startQuery(s)}e.length&&this.view.dispatch({effects:dg.of(e)})}},{eventHandlers:{blur(i){let e=this.view.state.field(Xe,!1);if(e&&e.tooltip&&this.view.state.facet(ve).closeOnBlur){let t=e.open&&Sh(this.view,e.open.tooltip);(!t||!t.dom.contains(i.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Vr.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:Go.of(!1)}),20),this.composing=0}}}),Fx=typeof navigator=="object"&&/Win/.test(navigator.platform),Hx=Qe.highest(E.domEventHandlers({keydown(i,e){let t=e.state.field(Xe,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||i.key.length>1||i.ctrlKey&&!(Fx&&i.altKey)||i.metaKey)return!1;let n=t.open.options[t.open.selected],r=t.active.find(o=>o.source==n.source),s=n.completion.commitCharacters||r.result.commitCharacters;return s&&s.indexOf(i.key)>-1&&Ec(e,n),!1}})),mg=E.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),Sc=class{constructor(e,t,n,r){this.field=e,this.line=t,this.from=n,this.to=r}},Tc=class i{constructor(e,t,n){this.field=e,this.from=t,this.to=n}map(e){let t=e.mapPos(this.from,-1,ge.TrackDel),n=e.mapPos(this.to,1,ge.TrackDel);return t==null||n==null?null:new i(this.field,t,n)}},Pc=class i{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let n=[],r=[t],s=e.doc.lineAt(t),o=/^\s*/.exec(s.text)[0];for(let l of this.lines){if(n.length){let h=o,c=/^\t*/.exec(l)[0].length;for(let f=0;fnew Tc(l.field,r[l.line]+l.from,r[l.line]+l.to));return{text:n,ranges:a}}static parse(e){let t=[],n=[],r=[],s;for(let o of e.split(/\r\n?|\n/)){for(;s=/[#$]\{(?:(\d+)(?::([^}]*))?|((?:\\[{}]|[^}])*))\}/.exec(o);){let a=s[1]?+s[1]:null,l=s[2]||s[3]||"",h=-1,c=l.replace(/\\[{}]/g,f=>f[1]);for(let f=0;f=h&&u.field++}r.push(new Sc(h,n.length,s.index,s.index+c.length)),o=o.slice(0,s.index)+l+o.slice(s.index+s[0].length)}o=o.replace(/\\([{}])/g,(a,l,h)=>{for(let c of r)c.line==n.length&&c.from>h&&(c.from--,c.to--);return l}),n.push(o)}return new i(n,r)}},Gx=M.widget({widget:new class extends Be{toDOM(){let i=document.createElement("span");return i.className="cm-snippetFieldPosition",i}ignoreEvent(){return!1}}}),Yx=M.mark({class:"cm-snippetField"}),vn=class i{constructor(e,t){this.ranges=e,this.active=t,this.deco=M.set(e.map(n=>(n.from==n.to?Gx:Yx).range(n.from,n.to)))}map(e){let t=[];for(let n of this.ranges){let r=n.map(e);if(!r)return null;t.push(r)}return new i(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(n=>n.field==this.active&&n.from<=t.from&&n.to>=t.to))}},Br=_.define({map(i,e){return i&&i.map(e)}}),Zx=_.define(),Lr=te.define({create(){return null},update(i,e){for(let t of e.effects){if(t.is(Br))return t.value;if(t.is(Zx)&&i)return new vn(i.ranges,t.value)}return i&&e.docChanged&&(i=i.map(e.changes)),i&&e.selection&&!i.selectionInsideField(e.selection)&&(i=null),i},provide:i=>E.decorations.from(i,e=>e?e.deco:M.none)});function Ac(i,e){return S.create(i.filter(t=>t.field==e).map(t=>S.range(t.from,t.to)))}function Jx(i){let e=Pc.parse(i);return(t,n,r,s)=>{let{text:o,ranges:a}=e.instantiate(t.state,r),l={changes:{from:r,to:s,insert:W.of(o)},scrollIntoView:!0,annotations:n?[Rc.of(n),fe.userEvent.of("input.complete")]:void 0};if(a.length&&(l.selection=Ac(a,0)),a.some(h=>h.field>0)){let h=new vn(a,0),c=l.effects=[Br.of(h)];t.state.field(Lr,!1)===void 0&&c.push(_.appendConfig.of([Lr,n1,r1,mg]))}t.dispatch(t.state.update(l))}}function gg(i){return({state:e,dispatch:t})=>{let n=e.field(Lr,!1);if(!n||i<0&&n.active==0)return!1;let r=n.active+i,s=i>0&&!n.ranges.some(o=>o.field==r+i);return t(e.update({selection:Ac(n.ranges,r),effects:Br.of(s?null:new vn(n.ranges,r)),scrollIntoView:!0})),!0}}var Kx=({state:i,dispatch:e})=>i.field(Lr,!1)?(e(i.update({effects:Br.of(null)})),!0):!1,e1=gg(1),t1=gg(-1);var i1=[{key:"Tab",run:e1,shift:t1},{key:"Escape",run:Kx}],lg=A.define({combine(i){return i.length?i[0]:i1}}),n1=Qe.highest(qt.compute([lg],i=>i.facet(lg)));function Rt(i,e){return Object.assign(Object.assign({},e),{apply:Jx(i)})}var r1=E.domEventHandlers({mousedown(i,e){let t=e.state.field(Lr,!1),n;if(!t||(n=e.posAtCoords({x:i.clientX,y:i.clientY}))==null)return!1;let r=t.ranges.find(s=>s.from<=n&&s.to>=n);return!r||r.field==t.active?!1:(e.dispatch({selection:Ac(t.ranges,r.field),effects:Br.of(t.ranges.some(s=>s.field>r.field)?new vn(t.ranges,r.field):null),scrollIntoView:!0}),!0)}});var qr={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Di=_.define({map(i,e){let t=e.mapPos(i,-1,ge.TrackAfter);return t??void 0}}),Qc=new class extends at{};Qc.startSide=1;Qc.endSide=-1;var Og=te.define({create(){return j.empty},update(i,e){if(i=i.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);i=i.update({filter:n=>n>=t.from&&n<=t.to})}for(let t of e.effects)t.is(Di)&&(i=i.update({add:[Qc.range(t.value,t.value+1)]}));return i}});function yg(){return[o1,Og]}var gc="()[]{}<>";function bg(i){for(let e=0;e{if((s1?i.composing:i.compositionStarted)||i.state.readOnly)return!1;let r=i.state.selection.main;if(n.length>2||n.length==2&&Ee(ce(n,0))==1||e!=r.from||t!=r.to)return!1;let s=l1(i.state,n);return s?(i.dispatch(s),!0):!1}),a1=({state:i,dispatch:e})=>{if(i.readOnly)return!1;let n=wg(i,i.selection.main.head).brackets||qr.brackets,r=null,s=i.changeByRange(o=>{if(o.empty){let a=h1(i.doc,o.head);for(let l of n)if(l==a&&Zo(i.doc,o.head)==bg(ce(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:S.cursor(o.head-l.length)}}return{range:r=o}});return r||e(i.update(s,{scrollIntoView:!0,userEvent:"delete.backward"})),!r},vg=[{key:"Backspace",run:a1}];function l1(i,e){let t=wg(i,i.selection.main.head),n=t.brackets||qr.brackets;for(let r of n){let s=bg(ce(r,0));if(e==r)return s==r?u1(i,r,n.indexOf(r+r+r)>-1,t):c1(i,r,s,t.before||qr.before);if(e==s&&xg(i,i.selection.main.from))return f1(i,r,s)}return null}function xg(i,e){let t=!1;return i.field(Og).between(0,i.doc.length,n=>{n==e&&(t=!0)}),t}function Zo(i,e){let t=i.sliceString(e,e+2);return t.slice(0,Ee(ce(t,0)))}function h1(i,e){let t=i.sliceString(e-2,e);return Ee(ce(t,0))==t.length?t:t.slice(1)}function c1(i,e,t,n){let r=null,s=i.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:Di.of(o.to+e.length),range:S.range(o.anchor+e.length,o.head+e.length)};let a=Zo(i.doc,o.head);return!a||/\s/.test(a)||n.indexOf(a)>-1?{changes:{insert:e+t,from:o.head},effects:Di.of(o.head+e.length),range:S.cursor(o.head+e.length)}:{range:r=o}});return r?null:i.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function f1(i,e,t){let n=null,r=i.changeByRange(s=>s.empty&&Zo(i.doc,s.head)==t?{changes:{from:s.head,to:s.head+t.length,insert:t},range:S.cursor(s.head+t.length)}:n={range:s});return n?null:i.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function u1(i,e,t,n){let r=n.stringPrefixes||qr.stringPrefixes,s=null,o=i.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:e,from:a.to}],effects:Di.of(a.to+e.length),range:S.range(a.anchor+e.length,a.head+e.length)};let l=a.head,h=Zo(i.doc,l),c;if(h==e){if(hg(i,l))return{changes:{insert:e+e,from:l},effects:Di.of(l+e.length),range:S.cursor(l+e.length)};if(xg(i,l)){let u=t&&i.sliceDoc(l,l+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:l,to:l+u.length,insert:u},range:S.cursor(l+u.length)}}}else{if(t&&i.sliceDoc(l-2*e.length,l)==e+e&&(c=cg(i,l-2*e.length,r))>-1&&hg(i,c))return{changes:{insert:e+e+e+e,from:l},effects:Di.of(l+e.length),range:S.cursor(l+e.length)};if(i.charCategorizer(l)(h)!=F.Word&&cg(i,l,r)>-1&&!d1(i,l,e,r))return{changes:{insert:e+e,from:l},effects:Di.of(l+e.length),range:S.cursor(l+e.length)}}return{range:s=a}});return s?null:i.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function hg(i,e){let t=he(i).resolveInner(e+1);return t.parent&&t.from==e}function d1(i,e,t,n){let r=he(i).resolveInner(e,-1),s=n.reduce((o,a)=>Math.max(o,a.length),0);for(let o=0;o<5;o++){let a=i.sliceDoc(r.from,Math.min(r.to,r.from+t.length+s)),l=a.indexOf(t);if(!l||l>-1&&n.indexOf(a.slice(0,l))>-1){let c=r.firstChild;for(;c&&c.from==r.from&&c.to-c.from>t.length+l;){if(i.sliceDoc(c.to-t.length,c.to)==t)return!1;c=c.firstChild}return!0}let h=r.to==e&&r.parent;if(!h)break;r=h}return!1}function cg(i,e,t){let n=i.charCategorizer(e);if(n(i.sliceDoc(e-1,e))!=F.Word)return e;for(let r of t){let s=e-r.length;if(i.sliceDoc(s,e)==r&&n(i.sliceDoc(s-1,s))!=F.Word)return s}return-1}function Xr(i={}){return[Hx,Xe,ve.of(i),Ux,p1,mg]}var Mc=[{key:"Ctrl-Space",run:Ix},{key:"Escape",run:Nx},{key:"ArrowDown",run:Uo(!0)},{key:"ArrowUp",run:Uo(!1)},{key:"PageDown",run:Uo(!0,"page")},{key:"PageUp",run:Uo(!1,"page")},{key:"Enter",run:Wx}],p1=Qe.highest(qt.computeN([ve],i=>i.facet(ve).defaultKeymap?[Mc]:[]));var _c=class{constructor(e,t,n){this.from=e,this.to=t,this.diagnostic=n}},$i=class i{constructor(e,t,n){this.diagnostics=e,this.panel=t,this.selected=n}static init(e,t,n){let r=e,s=n.facet(Wr).markerFilter;s&&(r=s(r,n));let o=M.set(r.map(a=>a.from==a.to||a.from==a.to-1&&n.doc.lineAt(a.from).to==a.from?M.widget({widget:new Dc(a),diagnostic:a}).range(a.from):M.mark({attributes:{class:"cm-lintRange cm-lintRange-"+a.severity+(a.markClass?" "+a.markClass:"")},diagnostic:a}).range(a.from,a.to)),!0);return new i(o,t,xn(o))}};function xn(i,e=null,t=0){let n=null;return i.between(t,1e9,(r,s,{spec:o})=>{if(!(e&&o.diagnostic!=e))return n=new _c(r,s,o.diagnostic),!1}),n}function m1(i,e){let t=e.pos,n=e.end||t,r=i.state.facet(Wr).hideOn(i,t,n);if(r!=null)return r;let s=i.startState.doc.lineAt(e.pos);return!!(i.effects.some(o=>o.is(Sg))||i.changes.touchesRange(s.from,Math.max(s.to,n)))}function g1(i,e){return i.field(He,!1)?e:e.concat(_.appendConfig.of(S1))}var Sg=_.define(),$c=_.define(),Tg=_.define(),He=te.define({create(){return new $i(M.none,null,null)},update(i,e){if(e.docChanged&&i.diagnostics.size){let t=i.diagnostics.map(e.changes),n=null,r=i.panel;if(i.selected){let s=e.changes.mapPos(i.selected.from,1);n=xn(t,i.selected.diagnostic,s)||xn(t,null,s)}!t.size&&r&&e.state.facet(Wr).autoPanel&&(r=null),i=new $i(t,r,n)}for(let t of e.effects)if(t.is(Sg)){let n=e.state.facet(Wr).autoPanel?t.value.length?Ir.open:null:i.panel;i=$i.init(t.value,n,e.state)}else t.is($c)?i=new $i(i.diagnostics,t.value?Ir.open:null,i.selected):t.is(Tg)&&(i=new $i(i.diagnostics,i.panel,t.value));return i},provide:i=>[Ti.from(i,e=>e.panel),E.decorations.from(i,e=>e.diagnostics)]});var O1=M.mark({class:"cm-lintRange cm-lintRange-active"});function y1(i,e,t){let{diagnostics:n}=i.state.field(He),r=[],s=2e8,o=0;n.between(e-(t<0?1:0),e+(t>0?1:0),(l,h,{spec:c})=>{e>=l&&e<=h&&(l==h||(e>l||t>0)&&(eRg(i,t,!1)))}var w1=i=>{let e=i.state.field(He,!1);(!e||!e.panel)&&i.dispatch({effects:g1(i.state,[$c.of(!0)])});let t=Pi(i,Ir.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},kg=i=>{let e=i.state.field(He,!1);return!e||!e.panel?!1:(i.dispatch({effects:$c.of(!1)}),!0)},v1=i=>{let e=i.state.field(He,!1);if(!e)return!1;let t=i.state.selection.main,n=e.diagnostics.iter(t.to+1);return!n.value&&(n=e.diagnostics.iter(0),!n.value||n.from==t.from&&n.to==t.to)?!1:(i.dispatch({selection:{anchor:n.from,head:n.to},scrollIntoView:!0}),!0)};var Pg=[{key:"Mod-Shift-m",run:w1,preventDefault:!0},{key:"F8",run:v1}];var Wr=A.define({combine(i){return Object.assign({sources:i.map(e=>e.source).filter(e=>e!=null)},Te(i.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{needsRefresh:(e,t)=>e?t?n=>e(n)||t(n):e:t}))}});function Cg(i){let e=[];if(i)e:for(let{name:t}of i){for(let n=0;ns.toLowerCase()==r.toLowerCase())){e.push(r);continue e}}e.push("")}return e}function Rg(i,e,t){var n;let r=t?Cg(e.actions):[];return U("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},U("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(i):e.message),(n=e.actions)===null||n===void 0?void 0:n.map((s,o)=>{let a=!1,l=u=>{if(u.preventDefault(),a)return;a=!0;let d=xn(i.state.field(He).diagnostics,e);d&&s.apply(i,d.from,d.to)},{name:h}=s,c=r[o]?h.indexOf(r[o]):-1,f=c<0?h:[h.slice(0,c),U("u",h.slice(c,c+1)),h.slice(c+1)];return U("button",{type:"button",class:"cm-diagnosticAction",onclick:l,onmousedown:l,"aria-label":` Action: ${h}${c<0?"":` (access key "${r[o]})"`}.`},f)}),e.source&&U("div",{class:"cm-diagnosticSource"},e.source))}var Dc=class extends Be{constructor(e){super(),this.diagnostic=e}eq(e){return e.diagnostic==this.diagnostic}toDOM(){return U("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}},Ko=class{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Rg(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}},Ir=class i{constructor(e){this.view=e,this.items=[];let t=r=>{if(r.keyCode==27)kg(this.view),this.view.focus();else if(r.keyCode==38||r.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(r.keyCode==40||r.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(r.keyCode==36)this.moveSelection(0);else if(r.keyCode==35)this.moveSelection(this.items.length-1);else if(r.keyCode==13)this.view.focus();else if(r.keyCode>=65&&r.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:s}=this.items[this.selectedIndex],o=Cg(s.actions);for(let a=0;a{for(let s=0;skg(this.view)},"\xD7")),this.update()}get selectedIndex(){let e=this.view.state.field(He).selected;if(!e)return-1;for(let t=0;t{let h=-1,c;for(let f=n;fn&&(this.items.splice(n,h-n),r=!0)),t&&c.diagnostic==t.diagnostic?c.dom.hasAttribute("aria-selected")||(c.dom.setAttribute("aria-selected","true"),s=c):c.dom.hasAttribute("aria-selected")&&c.dom.removeAttribute("aria-selected"),n++});n({sel:s.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:o,panel:a})=>{let l=a.height/this.list.offsetHeight;o.topa.bottom&&(this.list.scrollTop+=(o.bottom-a.bottom)/l)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),r&&this.sync()}sync(){let e=this.list.firstChild;function t(){let n=e;e=n.nextSibling,n.remove()}for(let n of this.items)if(n.dom.parentNode==this.list){for(;e!=n.dom;)t();e=n.dom.nextSibling}else this.list.insertBefore(n.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(He),n=xn(t.diagnostics,this.items[e].diagnostic);n&&this.view.dispatch({selection:{anchor:n.from,head:n.to},scrollIntoView:!0,effects:Tg.of(n)})}static open(e){return new i(e)}};function x1(i,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(i)}')`}function Jo(i){return x1(``,'width="6" height="3"')}var k1=E.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Jo("#d11")},".cm-lintRange-warning":{backgroundImage:Jo("orange")},".cm-lintRange-info":{backgroundImage:Jo("#999")},".cm-lintRange-hint":{backgroundImage:Jo("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});var S1=[He,E.decorations.compute([He],i=>{let{selected:e,panel:t}=i.field(He);return!e||!t||e.from==e.to?M.none:M.set([O1.range(e.from,e.to)])}),vp(y1,{hideOn:m1}),k1];var Eg=[Sp(),Tp(),Op(),pm(),Zp(),dp(),gp(),N.allowMultipleSelections.of(!0),Np(),Ar(Kp,{fallback:!0}),nm(),yg(),Xr(),bp(),wp(),yp(),Zm(),qt.of([...vg,...Nm,...ig,...ym,...Hp,...Mc,...Pg])];var qc=class i{constructor(e,t,n,r,s,o,a,l,h,c=0,f){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=s,this.score=o,this.buffer=a,this.bufferBase=l,this.curContext=h,this.lookAhead=c,this.parent=f}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new i(e,[],t,n,n,0,[],0,r?new ea(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let n=e>>19,r=e&65535,{parser:s}=this.p;this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[r])===null||t===void 0)&&t.isAnonymous)&&(l==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=h):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(r,l)}storeNode(e,t,n,r=4,s=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&o.buffer[a-4]==0&&o.buffer[a-1]>-1){if(t==n)return;if(o.buffer[a-2]>=t){o.buffer[a-2]=n;return}}}if(!s||this.pos==n)this.buffer.push(e,t,n,r);else{let o=this.buffer.length;if(o>0&&this.buffer[o-4]!=0)for(;o>0&&this.buffer[o-2]>n;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,r>4&&(r-=4);this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=n,this.buffer[o+3]=r}}shift(e,t,n,r){if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=r,this.shiftContext(t,n),t<=this.p.parser.maxNode&&this.buffer.push(t,n,r,4);else{let s=e,{parser:o}=this.p;(r>this.pos||t<=o.maxNode)&&(this.pos=r,o.stateFlag(s,1)||(this.reducePos=r)),this.pushState(s,n),this.shiftContext(t,n),t<=o.maxNode&&this.buffer.push(t,n,r,4)}}apply(e,t,n,r){e&65536?this.reduce(e):this.shift(e,t,n,r)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new i(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new Bc(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(n==0)return!1;if(!(n&65536))return!0;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let r=[];for(let s=0,o;sl&1&&a==o)||r.push(t[s],o)}t=r}let n=[];for(let r=0;r>19,r=t&65535,s=this.stack.length-n*3;if(s<0||e.getGoto(this.stack[s],r,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],n=(r,s)=>{if(!t.includes(r))return t.push(r),e.allActions(r,o=>{if(!(o&393216))if(o&65536){let a=(o>>19)-s;if(a>1){let l=o&65535,h=this.stack.length-a*3;if(h>=0&&e.getGoto(this.stack[h],l,!1)>=0)return a<<19|65536|l}}else{let a=n(o,s+1);if(a!=null)return a}})};return n(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},ea=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},Bc=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,n=e>>19;n==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(n-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}},Xc=class i{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new i(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new i(this.stack,this.pos,this.index)}};function Nr(i,e=Uint16Array){if(typeof i!="string")return i;let t=null;for(let n=0,r=0;n=92&&o--,o>=34&&o--;let l=o-32;if(l>=46&&(l-=46,a=!0),s+=l,a)break;s*=46}t?t[r++]=s:t=new e(s)}return t}var kn=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},Ag=new kn,Wc=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=Ag,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,s=this.pos+e;for(;sn.to:s>=n.to;){if(r==this.ranges.length-1)return null;let o=this.ranges[++r];s+=o.from-n.to,n=o}return s}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,n,r;if(t>=0&&t=this.chunk2Pos&&na.to&&(this.chunk2=this.chunk2.slice(0,a.to-n)),r=this.chunk2.charCodeAt(0)}}return n>=this.token.lookAhead&&(this.token.lookAhead=n+1),r}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(n==null||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Ag,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}},li=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:n}=t.p;$g(this.data,e,t,this.id,n.data,n.tokenPrecTable)}};li.prototype.contextual=li.prototype.fallback=li.prototype.extend=!1;var Ic=class{constructor(e,t,n){this.precTable=t,this.elseToken=n,this.data=typeof e=="string"?Nr(e):e}token(e,t){let n=e.pos,r=0;for(;;){let s=e.next<0,o=e.resolveOffset(1,1);if($g(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(s||r++,o==null)break;e.reset(o,e.token)}r&&(e.reset(n,e.token),e.acceptToken(this.elseToken,r))}};Ic.prototype.contextual=li.prototype.fallback=li.prototype.extend=!1;var Vi=class{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}};function $g(i,e,t,n,r,s){let o=0,a=1<0){let m=i[d];if(l.allows(m)&&(e.token.value==-1||e.token.value==m||P1(m,e.token.value,r,s))){e.acceptToken(m);break}}let c=e.next,f=0,u=i[o+2];if(e.next<0&&u>f&&i[h+u*3-3]==65535){o=i[h+u*3-1];continue e}for(;f>1,m=h+d+(d<<1),p=i[m],g=i[m+1]||65536;if(c=g)f=d+1;else{o=i[m+2],e.advance();continue e}}break}}function Qg(i,e,t){for(let n=e,r;(r=i[n])!=65535;n++)if(r==t)return n-e;return-1}function P1(i,e,t,n){let r=Qg(t,n,e);return r<0||Qg(t,n,i)e)&&!n.type.isError)return t<0?Math.max(0,Math.min(n.to-1,e-25)):Math.min(i.length,Math.max(n.from+1,e+25));if(t<0?n.prevSibling():n.nextSibling())break;if(!n.parent())return t<0?0:i.length}}var Nc=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Mg(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Mg(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(s instanceof le){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(s),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+s.length}}},jc=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(n=>new kn)}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:s}=r,o=r.stateSlot(e.state,3),a=e.curContext?e.curContext.hash:0,l=0;for(let h=0;hf.end+25&&(l=Math.max(f.lookAhead,l)),f.value!=0)){let u=t;if(f.extended>-1&&(t=this.addActions(e,f.extended,f.end,t)),t=this.addActions(e,f.value,f.end,t),!c.extend&&(n=f,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return l&&e.setLookAhead(l),!n&&e.pos==this.stream.end&&(n=new kn,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new kn,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){let r=this.stream.clipPos(n.pos);if(t.token(this.stream.reset(r,e),n),e.value>-1){let{parser:s}=n.p;for(let o=0;o=0&&n.p.parser.dialect.allows(a>>1)){a&1?e.extended=a>>1:e.value=a>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,n,r){for(let s=0;se.bufferLength*4?new Nc(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,n=this.stacks=[],r,s;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)n.push(a);else{if(this.advanceStack(a,n,e))continue;{r||(r=[],s=[]),r.push(a);let l=this.tokens.getMainToken(a);s.push(l.value,l.end)}}break}}if(!n.length){let o=r&&C1(r);if(o)return Ge&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw Ge&&r&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&r){let o=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,s,n);if(o)return Ge&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(n.length>o)for(n.sort((a,l)=>l.score-a.score);n.length>o;)n.pop();n.some(a=>a.reducePos>t)&&this.recovering--}else if(n.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((a.score-h.score||a.buffer.length-h.buffer.length)>0)n.splice(l--,1);else{n.splice(o--,1);continue e}}}n.length>12&&n.splice(12,n.length-12)}this.minStackPos=n[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.curContext&&e.curContext.tracker.strict,c=h?e.curContext.hash:0;for(let f=this.fragments.nodeAt(r);f;){let u=this.parser.nodeSet.types[f.type.id]==f.type?s.getGoto(e.state,f.type.id):-1;if(u>-1&&f.length&&(!h||(f.prop($.contextHash)||0)==c))return e.useNode(f,u),Ge&&console.log(o+this.stackID(e)+` (via reuse of ${s.getName(f.type.id)})`),!0;if(!(f instanceof le)||f.children.length==0||f.positions[0]>0)break;let d=f.children[0];if(d instanceof le&&f.positions[0]==0)f=d;else break}}let a=s.stateSlot(e.state,4);if(a>0)return e.reduce(a),Ge&&console.log(o+this.stackID(e)+` (via always-reduce ${s.getName(a&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let h=0;hr?t.push(m):n.push(m)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return _g(e,t),!0}}runRecovery(e,t,n){let r=null,s=!1;for(let o=0;o ":"";if(a.deadEnd&&(s||(s=!0,a.restart(),Ge&&console.log(c+this.stackID(a)+" (restarted)"),this.advanceFully(a,n))))continue;let f=a.split(),u=c;for(let d=0;f.forceReduce()&&d<10&&(Ge&&console.log(u+this.stackID(f)+" (via force-reduce)"),!this.advanceFully(f,n));d++)Ge&&(u=this.stackID(f)+" -> ");for(let d of a.recoverByInsert(l))Ge&&console.log(c+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,n);this.stream.end>a.pos?(h==a.pos&&(h++,l=0),a.recoverByDelete(l,h),Ge&&console.log(c+this.stackID(a)+` (via recover-delete ${this.parser.getName(l)})`),_g(a,n)):(!r||r.scorei,ta=class{constructor(e){this.start=e.start,this.shift=e.shift||Lc,this.reduce=e.reduce||Lc,this.reuse=e.reuse||Lc,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}},Sn=class i extends hn{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let a=0;ae.topRules[a][1]),r=[];for(let a=0;a=0)s(c,l,a[h++]);else{let f=a[h+-c];for(let u=-c;u>0;u--)s(a[h++],l,f);h++}}}this.nodeSet=new yr(t.map((a,l)=>Pe.define({name:l>=this.minRepeatTerm?void 0:a,id:l,props:r[l],top:n.indexOf(l)>-1,error:l==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(l)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=Nr(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let a=0;atypeof a=="number"?new li(o,a):a),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new zc(this,e,t,n);for(let s of this.wrappers)r=s(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let s=r[t+1];;){let o=r[s++],a=o&1,l=r[s++];if(a&&n)return l;for(let h=s+(o>>1);s0}validAction(e,t){return!!this.allActions(e,n=>n==t?!0:null)}allActions(e,t){let n=this.stateSlot(e,4),r=n?t(n):void 0;for(let s=this.stateSlot(e,1);r==null;s+=3){if(this.data[s]==65535)if(this.data[s+1]==1)s=Bt(this.data,s+2);else break;r=t(Bt(this.data,s+1))}return r}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(this.data[n]==65535)if(this.data[n+1]==1)n=Bt(this.data,n+2);else break;if(!(this.data[n+2]&1)){let r=this.data[n+1];t.some((s,o)=>o&1&&s==r)||t.push(this.data[n],r)}}return t}configure(e){let t=Object.assign(Object.create(i.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let n=this.topRules[e.top];if(!n)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=n}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(n=>{let r=e.tokenizers.find(s=>s.from==n);return r?r.to:n})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((n,r)=>{let s=e.specializers.find(a=>a.from==n.external);if(!s)return n;let o=Object.assign(Object.assign({},n),{external:s.to});return t.specializers[r]=Dg(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map(()=>!1);if(e)for(let s of e.split(" ")){let o=t.indexOf(s);o>=0&&(n[o]=!0)}let r=null;for(let s=0;sn)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scorei.external(t,n)<<1|e}return i.get}var R1=fn({"repeat while for if else return break next in":b.controlKeyword,"Logical!":b.bool,function:b.definitionKeyword,"FunctionCall/Identifier FunctionCall/String":b.function(b.variableName),"NamedArg!":b.function(b.attributeName),Comment:b.lineComment,"Numeric Integer Complex Inf":b.number,"SpecialConstant!":b.literal,String:b.string,"ArithOp MatrixOp":b.arithmeticOperator,BitOp:b.bitwiseOperator,CompareOp:b.compareOperator,"ExtractionOp NamespaceOp":b.operator,AssignmentOperator:b.definitionOperator,"...":b.punctuation,"( )":b.paren,"[ ]":b.squareBracket,"{ }":b.brace,$:b.derefOperator,", ;":b.separator}),E1={__proto__:null,TRUE:12,T:14,FALSE:18,F:20,NULL:30,NA:34,Inf:38,NaN:42,function:46,"...":50,return:60,break:64,next:68,if:80,else:82,repeat:86,while:90,for:94,in:96},ia=Sn.deserialize({version:14,states:"7dOYQPOOOOQO'#Dx'#DxOOQO'#Dw'#DwO$aQPO'#DwOOQO'#Dy'#DyO(]QPO'#DvOOQO'#Dv'#DvOOQO'#Cx'#CxO*UQPO'#CwO,YQPO'#DmO/rQPO'#DaO1kQPO'#D`OOQO'#Dz'#DzOOQO'#Du'#DuQYQPOOOOQO'#Ca'#CaOOQO'#Cd'#CdOOQO'#Cj'#CjOOQO'#Cl'#ClOOQO'#Cn'#CnOOQO'#Cp'#CpO1|QPO'#CrO2RQPO'#DTO!bQPO'#DWO2WQPO'#DYO2]QPO'#D[O3oQPO'#DROOQO,59l,59lO3yQPO'#DoOOQO'#Do'#DoO*UQPO,59cOOQO'#DP'#DPOOQO,59c,59cO5fQPO'#CyO5kQPO'#C{O7XQPO'#C}O8uQPO,59yO:ZQQO,59yOOQO'#Dd'#DdOOQO'#De'#DeOOQO'#Df'#DfOOQO'#Dg'#DgOOQO'#Dh'#DhOOQO'#Di'#DiOOQO'#Dj'#DjOOQO'#Dk'#DkOOQO'#Dl'#DlOYQPO,59}OYQPO,59}OYQPO,59}OYQPO,59}OYQPO,59}OYQPO,59}OYQPO,59}OYQPO,59}OYQPO,59}OOQO'#Db'#DbOYQPO,59zOOQO-E7k-E7kO:bQPO'#CtO!bQPO,59^OYQPO,59oOOQO,59r,59rOYQPO,59tOYQPO,59vO:mQPO'#DwO:tQPO'#DvO:{QPO'#ESO;VQPO'#ESO;aQPO,59mO;fQPO'#ESOOQO-E7m-E7mOOQO1G.}1G.}O;nQPO,59eO;uQPO,59gO;zQPO,59iOkQQO'#DvO@gQQO'#EUO@qQQO1G/eO@vQQO'#DaODcQPO1G/iODmQPO1G/iOH`QPO1G/iOHgQPO1G/iOLSQPO1G/iOL^QPO1G/iO! aQPO1G/iO!!WQPO1G/iO!$tQPO1G/iO!(dQPO1G/fO!*]QPO'#D}OYQPO'#D}O!*hQPO,59`O!*`QPO'#D}OOQO1G.x1G.xO!*mQPO1G/ZO!*tQPO1G/`O!*{QPO1G/bOOQO,59n,59nO!+SQPO'#DpO!+ZQPO,5:nO!+cQPO,5:nOOQO1G/X1G/XO!+mQPO1G/POOQO1G/P1G/POOQO1G/R1G/ROOQO1G/T1G/TOYQPO'#DqO!+tQPO,5:pOOQO7+%P7+%PO!+|QQO,5:pOOQO,59b,59bO!,UQPO'#DnO!,^QPO,5:iO!,fQPO,5:iOOQO1G.z1G.zO!bQPO7+$uO!bQPO7+$zOYQPO7+$|O!,pQPO,5:[O!,zQPO,5:[OOQO,5:[,5:[OOQO-E7n-E7nO!-UQPO1G0YOOQO7+$k7+$kO!-^QPO,5:]OOQO-E7o-E7oO!-hQQO,5:]O!/fQQO1G/iO!/pQQO1G/iO!1qQQO1G/iO!1xQQO1G/iO!3sQQO1G/iO!3}QQO1G/iO!5`QQO1G/iO!6VQQO1G/iO!6|QQO1G/iO!7TQQO1G/fO!7[QPO,5:YOYQPO,5:YOOQO,5:Y,5:YOOQO-E7l-E7lO!7gQPO1G0TO!9iQPO<SO!;}QQO<YO!s$lO!{!xX~P*fO!{#dO~O!{!nX~P-lO!pjOR!ViS!ViU!ViV!ViX!ViY!ViZ!Vi[!Vi]!Vi_!Via!Vic!Vie!Vig!Vix!Vi{!Vi}!Vi!P!Vi!f!Vi!u!Vi!w!Vi!z!Vi#S!Vi#T!Vi#U!Vi#V!Vi#W!Vi#X!Vi#Y!Vi#Z!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#a!Vi#b!Vi#c!Vi#d!Vi#e!Vi#f!Vi#g!Vi#h!Vin!Vip!Vir!Vi!t!Vi!o!Vi!s!Vi!y!Vi!Q!Vi~O#Q!Vi#R!Vi~P@}O#QvO#RvO~P@}O!pjO#QvO#RvO#SwO#TwOR!ViS!ViU!ViV!ViX!ViY!ViZ!Vi[!Vi]!Vi_!Via!Vic!Vie!Vig!Vix!Vi{!Vi}!Vi!P!Vi!f!Vi!u!Vi!w!Vi!z!Vi#V!Vi#W!Vi#X!Vi#Y!Vi#Z!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#a!Vi#b!Vi#c!Vi#d!Vi#e!Vi#f!Vi#g!Vi#h!Vin!Vip!Vir!Vi!t!Vi!o!Vi!s!Vi!y!Vi!Q!Vi~O#U!Vi~PDwO#UxO~PDwO!pjO#QvO#RvO#SwO#TwO#UxO#VyO#WyO#XyO#a|O#b|O#c|O#d|OR!ViS!ViU!ViV!ViX!ViY!ViZ!Vi[!Vi]!Vi_!Via!Vic!Vie!Vig!Vix!Vi{!Vi}!Vi!P!Vi!f!Vi!u!Vi!w!Vi!z!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#e!Vi#f!Vi#g!Vi#h!Vin!Vip!Vir!Vi!t!Vi!o!Vi!s!Vi!y!Vi!Q!Vi~O#Y!Vi#Z!Vi~PHnO#YzO#ZzO~PHnO!pjO#QvO#RvO#SwO#TwO#UxO#VyO#WyO#XyOR!ViS!ViU!ViV!ViX!ViY!ViZ!Vi[!Vi]!Vi_!Via!Vic!Vie!Vig!Vix!Vi{!Vi}!Vi!P!Vi!f!Vi!u!Vi!w!Vi!z!Vi#e!Vi#f!Vi#g!Vi#h!Vin!Vip!Vir!Vi!t!Vi!o!Vi!s!Vi!y!Vi!Q!Vi~O#Y!Vi#Z!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#a!Vi#b!Vi#c!Vi#d!Vi~PLhO#YzO#ZzO#[{O#]{O#^{O#_{O#`{O#a|O#b|O#c|O#d|O~PLhO!pjO#QvO#RvO#SwO#TwO#UxO#VyO#WyO#XyO#YzO#ZzO#[{O#]{O#^{O#_{O#`{O#a|O#b|O#c|O#d|O#e}O#f}O!w!Vi!z!Vi#g!Vi#h!Vi!s!Vi~OR!ViS!ViU!ViV!ViX!ViY!ViZ!Vi[!Vi]!Vi_!Via!Vic!Vie!Vig!Vix!Vi{!Vi}!Vi!P!Vi!f!Vi!u!Vin!Vip!Vir!Vi!t!Vi!o!Vi!y!Vi!Q!Vi~P!!}O!pjO!w!Si!z!Si#Q!Si#R!Si#S!Si#T!Si#U!Si#V!Si#W!Si#X!Si#Y!Si#Z!Si#[!Si#]!Si#^!Si#_!Si#`!Si#a!Si#b!Si#c!Si#d!Si#e!Si#f!Si#g!Si#h!Si!s!Si~OR!SiS!SiU!SiV!SiX!SiY!SiZ!Si[!Si]!Si_!Sia!Sic!Sie!Sig!Six!Si{!Si}!Si!P!Si!f!Si!u!Sin!Sip!Sir!Si!t!Si!o!Si!y!Si!Q!Si~P!&mO!r#fO!s#gO!o!qX~O!o#jO~O!o#kO~P*fO!o#lO~P*fO!Q#mO~P*fOi#pO~P2bO!s#YO!o!va~O!s#YO!o!va~P*fO!o#sO~P*fO!s#bO!y!xa~O!s$lO!{!xa~OR$ROi$TO~O!s#gO!o!qa~O!s#gO!o!qa~P*fO!o!da!s!da~P*fO!o!da!s!da~PYO!s#YO!o!vi~O!s!ea!y!ea~P*fO!s!ea!{!ea~P*fO!pjO!s!Vi!w!Vi!z!Vi!{!Vi#S!Vi#T!Vi#U!Vi#V!Vi#W!Vi#X!Vi#Y!Vi#Z!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#a!Vi#b!Vi#c!Vi#d!Vi#e!Vi#f!Vi#g!Vi#h!Vi~O#Q!Vi#R!Vi~P!-rO#QvO#RvO~P!-rO!pjO#QvO#RvO#SwO#TwO!s!Vi!w!Vi!z!Vi!{!Vi#V!Vi#W!Vi#X!Vi#Y!Vi#Z!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#a!Vi#b!Vi#c!Vi#d!Vi#e!Vi#f!Vi#g!Vi#h!Vi~O#U!Vi~P!/zO#UxO~P!/zO!pjO#QvO#RvO#SwO#TwO#UxO#VyO#WyO#XyO#a|O#b|O#c|O#d|O!s!Vi!w!Vi!z!Vi!{!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#e!Vi#f!Vi#g!Vi#h!Vi~O#Y!Vi#Z!Vi~P!2PO#YzO#ZzO~P!2PO!pjO#QvO#RvO#SwO#TwO#UxO#VyO#WyO#XyO!s!Vi!w!Vi!z!Vi!{!Vi#e!Vi#f!Vi#g!Vi#h!Vi~O#Y!Vi#Z!Vi#[!Vi#]!Vi#^!Vi#_!Vi#`!Vi#a!Vi#b!Vi#c!Vi#d!Vi~P!4XO#YzO#ZzO#[{O#]{O#^{O#_{O#`{O#a|O#b|O#c|O#d|O~P!4XO!{!Vi~P!!}O!{!Si~P!&mO!r#fO!o!ba!s!ba~O!s#gO!o!qi~Oy$]O!pwy!wwy!zwy#Qwy#Rwy#Swy#Twy#Uwy#Vwy#Wwy#Xwy#Ywy#Zwy#[wy#]wy#^wy#_wy#`wy#awy#bwy#cwy#dwy#ewy#fwy#gwy#hwy!swy~ORwySwyUwyVwyXwyYwyZwy[wy]wy_wyawycwyewygwyxwy{wy}wy!Pwy!fwy!uwynwypwyrwy!twy!owy!ywy!Qwy~P!7oO!o$^O~P*fO!o!di!s!di~P*fO!o!bi!s!bi~P*fO!{wy~P!7oO!o$mO~P*fO!p$pO~O",goto:"7}!yPPPPP!zPP!zPPPPP#vP#vP#vP#vP$rP%nP%q%w'Y(]P(]P(]P(a(g)e*b$rPP$rP$rP$rPP(g$r*h+f$r+l,d-Y-|.n/[/v0f1O1f1l1w1}2ZPPP2e4}5y6u5y4}PP7qPPPP7tP7w!sPOW^jntu!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$b$c$d$e$f$g$h$i$j$k$l$p!sSOW^jntu!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$b$c$d$e$f$g$h$i$j$k$l$p!s[OW^jntu!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$b$c$d$e$f$g$h$i$j$k$l$pR!^eQ#Q!]R$S#g!r[OW^jntu!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$b$c$d$e$f$g$h$i$j$k$l$pQ!`gQ#T!^Q$W#kQ$X#lQ$_$mQ$`$]R$a$^#RWOW^gjntu!P!Q!R!S!T!U!V!W!X!Z!^!_!a!b!f!k#Q#Y#b#k#l#m#o$S$]$^$b$c$d$e$f$g$h$i$j$k$l$m$pTmWnQpWR!jn!YYOW^jnt!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$pi!tu$b$c$d$e$f$g$h$i$j$k$l!ukRXl!c!e!n!p!r!u!v!w!x!y!z!{!|!}#O#U#V#W#[#^#i#n#t#v#w#x#y#z#{#|#}$O$P$Q$Y$Z$[$oQ!fjR#o#Y!YZOW^jnt!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$pi$nu$b$c$d$e$f$g$h$i$j$k$lQ!ZZR$k$n!Q!PXl!e!n!v!w!x!y!z!{!|!}#U#V#W#[#^#i#n#t$Y$Z$[$oe$b!r#v#x#y#z#{#|#}$O$P!O!QXl!e!n!w!x!y!z!{!|!}#U#V#W#[#^#i#n#t$Y$Z$[$oc$c!r#v#y#z#{#|#}$O$P|!RXl!e!n!x!y!z!{!|!}#U#V#W#[#^#i#n#t$Y$Z$[$oa$d!r#v#z#{#|#}$O$Pz!SXl!e!n!y!z!{!|!}#U#V#W#[#^#i#n#t$Y$Z$[$o_$e!r#v#{#|#}$O$Pv!TXl!e!n!z!|!}#U#V#W#[#^#i#n#t$Y$Z$[$oZ$f!r#v#|$O$Pt!UXl!e!n!|!}#U#V#W#[#^#i#n#t$Y$Z$[$oX$g!r#v$O$Px!VXl!e!n!y!z!|!}#U#V#W#[#^#i#n#t$Y$Z$[$o]$h!r#v#{#|$O$Pr!WXl!e!n!}#U#V#W#[#^#i#n#t$Y$Z$[$oV$i!r#v$Pp!XXl!e!n#U#V#W#[#^#i#n#t$Y$Z$[$oT$j!r#vQ^OR![^S#h#P#SS$U#h$VR$V#iQnWR!inU#Z!e!f!hS#q#Z#rR#r#[Q#c!nQ#e!rT#u#c#eSXO^SlWnQ!ejQ!ntQ!ruQ!u!PQ!v!QQ!w!RQ!x!SQ!y!TQ!z!UQ!{!VQ!|!WQ!}!XQ#O!ZQ#U!_Q#V!aQ#W!bQ#[!fQ#^!kQ#i#QQ#n#YQ#t#bQ#v$lQ#w$bQ#x$cQ#y$dQ#z$eQ#{$fQ#|$gQ#}$hQ$O$iQ$P$jQ$Q$kQ$Y#mQ$Z#oQ$[$SR$o$p!s]OW^jntu!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$b$c$d$e$f$g$h$i$j$k$l$p!sUOW^jntu!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$b$c$d$e$f$g$h$i$j$k$l$p!sQOW^jntu!P!Q!R!S!T!U!V!W!X!Z!_!a!b!f!k#Q#Y#b#m#o$S$b$c$d$e$f$g$h$i$j$k$l$pR#R!]R!gjQ!otR!su",nodeNames:"\u26A0 Comment Script Identifier Integer True TRUE T False FALSE F Numeric String Complex Null NULL NA NA Inf Inf NaN NaN FunctionDeclaration function ParamList ... NamedArg Block BlockOpenBrace ReturnStatement return BreakStatement break NextStatement next BlockCloseBrace FunctionCall ArgList NamedArg IfStatement if else RepeatStatement repeat WhileStatement while ForStatement for in IndexStatement VariableAssignment Assignable AssignmentOperator BinaryStatement NamespaceOp ExtractionOp ArithOp ArithOp ArithOp CompareOp MatrixOp LogicOp LogicOp",maxTerm:116,nodeProps:[["group",-11,3,22,27,36,39,42,44,46,49,50,53,"Expression",-4,4,11,12,13,"Constant Expression",-2,5,8,"Constant Expression Logical",-4,14,16,18,20,"Expression SpecialConstant"]],propSources:[R1],skippedNodes:[0,1],repeatNodeCount:5,tokenData:"6[~RzX^#upq#uqr$jrs$ust%itu%tuv%yvw'twx(Rxy(pyz(uz{(z{|)P|})U}!O)Z!O!P)p!P!Q.b!Q!R.g!R![0^![!]2x!^!_3]!_!`4O!`!a4]!b!c4h!c!}*|!}#O4m#P#Q4z#Q#R5X#R#S*|#S#T5^#T#o*|#o#p5s#p#q5x#q#r6V#y#z#u$f$g#u#BY#BZ#u$IS$I_#u$I|$JO#u$JT$JU#u$KV$KW#u&FU&FV#u~#zY!h~X^#upq#u#y#z#u$f$g#u#BY#BZ#u$IS$I_#u$I|$JO#u$JT$JU#u$KV$KW#u&FU&FV#u~$mP!_!`$p~$uO#]~~$zU[~OY$uZr$urs%^s#O$u#O#P%c#P~$u~%cO[~~%fPO~$u~%nQP~OY%iZ~%i~%yO#S~~%|Uuv&`z{&e!P!Q&p#]#^&{#c#d'^#l#m'i~&eO#X~~&hPuv&k~&pO#b~~&sPuv&v~&{O#a~~'OP#b#c'R~'UPuv'X~'^O#`~~'aPuv'd~'iO#c~~'lPuv'o~'tO#d~~'yP#g~vw'|~(RO#h~~(WU[~OY(RZw(Rwx%^x#O(R#O#P(j#P~(R~(mPO~(R~(uO!p~~(zO!o~~)PO#V~~)UO#Y~~)ZO!s~~)`P#Z~!`!a)c~)hP!}~!`!a)k~)pO#P~~)uTR~!O!P*U!Q![+b!c!}*|#R#S*|#T#o*|~*ZZR~O!O*|!O!P*|!P!Q*|!Q![*|![!c*|!c!}*|!}#R*|#R#S*|#S#T*|#T#o*|#o~*|~+RTR~!O!P*|!Q![*|!c!}*|#R#S*|#T#o*|~+iZZ~R~!O!P*|!Q![+b!c!g*|!g!h,[!h!}*|#R#S*|#T#X*|#X#Y,[#Y#]*|#]#^-z#^#o*|~,aVR~{|,v}!O,v!O!P*|!Q![-^!c!}*|#R#S*|#T#o*|~,yP!Q![,|~-RQZ~!Q![,|#]#^-X~-^O]~~-eVZ~R~!O!P*|!Q![-^!c!}*|#R#S*|#T#]*|#]#^-z#^#o*|~.RT]~R~!O!P*|!Q![*|!c!}*|#R#S*|#T#o*|~.gO#W~~.lWZ~!O!P/U!Q![0^!g!h0u!n!o0X!z!{1g#X#Y0u#]#^-X#l#m1g~/ZTZ~!Q![/j!g!h/{!n!o0X#X#Y/{#]#^-X~/oSZ~!Q![/j!g!h/{#X#Y/{#]#^-X~0OR{|,v}!O,v!Q![,|~0^OS~~0cUZ~!O!P/U!Q![0^!g!h0u!n!o0X#X#Y0u#]#^-X~0xR{|1R}!O1R!Q![1X~1UP!Q![1X~1^RZ~!Q![1X!n!o0X#]#^-X~1jU!O!P1|!Q![2`!c!i2`!r!s/{#T#Z2`#d#e/{~2PT!Q![1|!c!i1|!r!s/{#T#Z1|#d#e/{~2cV!O!P1|!Q![2`!c!i2`!n!o0X!r!s/{#T#Z2`#d#e/{~2{P![!]3O~3TP#Q~![!]3W~3]O#R~~3`R}!O3i!^!_3n!_!`3y~3nO!|~~3qP}!O3t~3yO#O~~4OO#_~~4TP!r~!_!`4W~4]O#[~~4`P!_!`4c~4hO#^~~4mO#T~~4rP!w~!}#O4u~4zO!z~R5PP!yP#P#Q5SQ5XO!{Q~5^O#U~~5aQO#S5g#T~5g~5jRO#S5g#S#T%^#T~5g~5xO!u~~5}P#e~#p#q6Q~6VO#f~~6[O!t~",tokenizers:[0,1],topRules:{Script:[0,2]},specialized:[{term:3,get:i=>E1[i]||-1}],tokenPrec:0});var A1=1,Xg=194,Wg=195,Q1=196,Vg=197,M1=198,_1=199,D1=200,$1=2,Ig=3,Lg=201,V1=24,L1=25,q1=49,B1=50,X1=55,W1=56,I1=57,N1=59,j1=60,z1=61,U1=62,F1=63,H1=65,G1=238,Y1=71,Z1=241,J1=242,K1=243,ek=244,tk=245,ik=246,nk=247,rk=248,Ng=72,sk=249,ok=250,ak=251,lk=252,hk=253,ck=254,fk=255,uk=256,dk=73,pk=77,mk=263,gk=112,Ok=130,yk=151,bk=152,wk=155,Li=10,jr=13,Yc=32,sa=9,Zc=35,vk=40,xk=46,Gc=123,qg=125,jg=39,zg=34,kk=92,Sk=111,Tk=120,Pk=78,Ck=117,Rk=85,Ek=new Set([L1,q1,B1,mk,H1,Ok,W1,I1,G1,U1,F1,Ng,dk,pk,j1,z1,yk,bk,wk,gk]);function Fc(i){return i==Li||i==jr}function Hc(i){return i>=48&&i<=57||i>=65&&i<=70||i>=97&&i<=102}var Ak=new Vi((i,e)=>{let t;if(i.next<0)i.acceptToken(_1);else if(e.context.flags&na)Fc(i.next)&&i.acceptToken(M1,1);else if(((t=i.peek(-1))<0||Fc(t))&&e.canShift(Vg)){let n=0;for(;i.next==Yc||i.next==sa;)i.advance(),n++;(i.next==Li||i.next==jr||i.next==Zc)&&i.acceptToken(Vg,-n)}else Fc(i.next)&&i.acceptToken(Q1,1)},{contextual:!0}),Qk=new Vi((i,e)=>{let t=e.context;if(t.flags)return;let n=i.peek(-1);if(n==Li||n==jr){let r=0,s=0;for(;;){if(i.next==Yc)r++;else if(i.next==sa)r+=8-r%8;else break;i.advance(),s++}r!=t.indent&&i.next!=Li&&i.next!=jr&&i.next!=Zc&&(r[i,e|Ug])),Dk=new ta({start:Mk,reduce(i,e,t,n){return i.flags&na&&Ek.has(e)||(e==Y1||e==Ng)&&i.flags&Ug?i.parent:i},shift(i,e,t,n){return e==Xg?new ra(i,_k(n.read(n.pos,t.pos)),0):e==Wg?i.parent:e==V1||e==X1||e==N1||e==Ig?new ra(i,0,na):Bg.has(e)?new ra(i,0,Bg.get(e)|i.flags&na):i},hash(i){return i.hash}}),$k=new Vi(i=>{for(let e=0;e<5;e++){if(i.next!="print".charCodeAt(e))return;i.advance()}if(!/\w/.test(String.fromCharCode(i.next)))for(let e=0;;e++){let t=i.peek(e);if(!(t==Yc||t==sa)){t!=vk&&t!=xk&&t!=Li&&t!=jr&&t!=Zc&&i.acceptToken(A1);return}}}),Vk=new Vi((i,e)=>{let{flags:t}=e.context,n=t&Xt?zg:jg,r=(t&Wt)>0,s=!(t&It),o=(t&Nt)>0,a=i.pos;for(;!(i.next<0);)if(o&&i.next==Gc)if(i.peek(1)==Gc)i.advance(2);else{if(i.pos==a){i.acceptToken(Ig,1);return}break}else if(s&&i.next==kk){if(i.pos==a){i.advance();let l=i.next;l>=0&&(i.advance(),Lk(i,l)),i.acceptToken($1);return}break}else if(i.next==n&&(!r||i.peek(1)==n&&i.peek(2)==n)){if(i.pos==a){i.acceptToken(Lg,r?3:1);return}break}else if(i.next==Li){if(r)i.advance();else if(i.pos==a){i.acceptToken(Lg);return}break}else i.advance();i.pos>a&&i.acceptToken(D1)});function Lk(i,e){if(e==Sk)for(let t=0;t<2&&i.next>=48&&i.next<=55;t++)i.advance();else if(e==Tk)for(let t=0;t<2&&Hc(i.next);t++)i.advance();else if(e==Ck)for(let t=0;t<4&&Hc(i.next);t++)i.advance();else if(e==Rk)for(let t=0;t<8&&Hc(i.next);t++)i.advance();else if(e==Pk&&i.next==Gc){for(i.advance();i.next>=0&&i.next!=qg&&i.next!=jg&&i.next!=zg&&i.next!=Li;)i.advance();i.next==qg&&i.advance()}}var qk=fn({'async "*" "**" FormatConversion FormatSpec':b.modifier,"for while if elif else try except finally return raise break continue with pass assert await yield match case":b.controlKeyword,"in not and or is del":b.operatorKeyword,"from def class global nonlocal lambda":b.definitionKeyword,import:b.moduleKeyword,"with as print":b.keyword,Boolean:b.bool,None:b.null,VariableName:b.variableName,"CallExpression/VariableName":b.function(b.variableName),"FunctionDefinition/VariableName":b.function(b.definition(b.variableName)),"ClassDefinition/VariableName":b.definition(b.className),PropertyName:b.propertyName,"CallExpression/MemberExpression/PropertyName":b.function(b.propertyName),Comment:b.lineComment,Number:b.number,String:b.string,FormatString:b.special(b.string),Escape:b.escape,UpdateOp:b.updateOperator,"ArithOp!":b.arithmeticOperator,BitOp:b.bitwiseOperator,CompareOp:b.compareOperator,AssignOp:b.definitionOperator,Ellipsis:b.punctuation,At:b.meta,"( )":b.paren,"[ ]":b.squareBracket,"{ }":b.brace,".":b.derefOperator,", ;":b.separator}),Bk={__proto__:null,await:44,or:54,and:56,in:60,not:62,is:64,if:70,else:72,lambda:76,yield:94,from:96,async:102,for:104,None:162,True:164,False:164,del:178,pass:182,break:186,continue:190,return:194,raise:202,import:206,as:208,global:212,nonlocal:214,assert:218,type:223,elif:236,while:240,try:246,except:248,finally:250,with:254,def:258,class:268,match:279,case:285},oa=Sn.deserialize({version:14,states:"##jO`QeOOP$}OSOOO&WQtO'#HUOOQS'#Co'#CoOOQS'#Cp'#CpO'vQdO'#CnO*UQtO'#HTOOQS'#HU'#HUOOQS'#DU'#DUOOQS'#HT'#HTO*rQdO'#D_O+VQdO'#DfO+gQdO'#DjO+zOWO'#DuO,VOWO'#DvO.[QtO'#GuOOQS'#Gu'#GuO'vQdO'#GtO0ZQtO'#GtOOQS'#Eb'#EbO0rQdO'#EcOOQS'#Gs'#GsO0|QdO'#GrOOQV'#Gr'#GrO1XQdO'#FYOOQS'#G^'#G^O1^QdO'#FXOOQV'#IS'#ISOOQV'#Gq'#GqOOQV'#Fq'#FqQ`QeOOO'vQdO'#CqO1lQdO'#C}O1sQdO'#DRO2RQdO'#HYO2cQtO'#EVO'vQdO'#EWOOQS'#EY'#EYOOQS'#E['#E[OOQS'#E^'#E^O2wQdO'#E`O3_QdO'#EdO3rQdO'#EfO3zQtO'#EfO1XQdO'#EiO0rQdO'#ElO1XQdO'#EnO0rQdO'#EtO0rQdO'#EwO4VQdO'#EyO4^QdO'#FOO4iQdO'#EzO0rQdO'#FOO1XQdO'#FQO1XQdO'#FVO4nQdO'#F[P4uOdO'#GpPOOO)CBd)CBdOOQS'#Ce'#CeOOQS'#Cf'#CfOOQS'#Cg'#CgOOQS'#Ch'#ChOOQS'#Ci'#CiOOQS'#Cj'#CjOOQS'#Cl'#ClO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO5QQdO'#DoOOQS,5:Y,5:YO5eQdO'#HdOOQS,5:],5:]O5rQ!fO,5:]O5wQtO,59YO1lQdO,59bO1lQdO,59bO1lQdO,59bO8gQdO,59bO8lQdO,59bO8sQdO,59jO8zQdO'#HTO:QQdO'#HSOOQS'#HS'#HSOOQS'#D['#D[O:iQdO,59aO'vQdO,59aO:wQdO,59aOOQS,59y,59yO:|QdO,5:RO'vQdO,5:ROOQS,5:Q,5:QO;[QdO,5:QO;aQdO,5:XO'vQdO,5:XO'vQdO,5:VOOQS,5:U,5:UO;rQdO,5:UO;wQdO,5:WOOOW'#Fy'#FyO;|OWO,5:aOOQS,5:a,5:aOOOOQS'#Ds'#DsOOQS1G/w1G/wOOQS1G.|1G.|O!/RQtO1G.|O!/YQtO1G.|O1lQdO1G.|O!/uQdO1G/UOOQS'#DZ'#DZO0rQdO,59tOOQS1G.{1G.{O!/|QdO1G/eO!0^QdO1G/eO!0fQdO1G/fO'vQdO'#H[O!0kQdO'#H[O!0pQtO1G.{O!1QQdO,59iO!2WQdO,5=zO!2hQdO,5=zO!2pQdO1G/mO!2uQtO1G/mOOQS1G/l1G/lO!3VQdO,5=uO!3|QdO,5=uO0rQdO1G/qO!4kQdO1G/sO!4pQtO1G/sO!5QQtO1G/qOOQS1G/p1G/pOOQS1G/r1G/rOOOW-E9w-E9wOOQS1G/{1G/{O!5bQdO'#HxO0rQdO'#HxO!5sQdO,5>cOOOW-E9x-E9xOOQS1G/|1G/|OOQS-E9{-E9{O!6RQ#xO1G2zO!6rQtO1G2zO'vQdO,5kOOQS1G1`1G1`O!7xQdO1G1`OOQS'#DV'#DVO0rQdO,5=qOOQS,5=q,5=qO!7}QdO'#FrO!8YQdO,59oO!8bQdO1G/XO!8lQtO,5=uOOQS1G3`1G3`OOQS,5:m,5:mO!9]QdO'#GtOOQS,5jO!;QQdO,5>jO1XQdO,5>jO!;cQdO,5>iOOQS-E:R-E:RO!;hQdO1G0lO!;sQdO1G0lO!;xQdO,5>lO!lO!hO!<|QdO,5>hO!=_QdO'#EpO0rQdO1G0tO!=jQdO1G0tO!=oQgO1G0zO!AmQgO1G0}O!EhQdO,5>oO!ErQdO,5>oO!EzQtO,5>oO0rQdO1G1PO!FUQdO1G1PO4iQdO1G1UO!!sQdO1G1WOOQV,5;a,5;aO!FZQfO,5;aO!F`QgO1G1QO!JaQdO'#GZO4iQdO1G1QO4iQdO1G1QO!JqQdO,5>pO!KOQdO,5>pO1XQdO,5>pOOQV1G1U1G1UO!KWQdO'#FSO!KiQ!fO1G1WO!KqQdO1G1WOOQV1G1]1G1]O4iQdO1G1]O!KvQdO1G1]O!LOQdO'#F^OOQV1G1b1G1bO!#WQtO1G1bPOOO1G2v1G2vP!LTOSO1G2vOOQS,5=},5=}OOQS'#Dp'#DpO0rQdO,5=}O!LYQdO,5=|O!LmQdO,5=|OOQS1G/u1G/uO!LuQdO,5>PO!MVQdO,5>PO!M_QdO,5>PO!MrQdO,5>PO!NSQdO,5>POOQS1G3j1G3jOOQS7+$h7+$hO!8bQdO7+$pO# uQdO1G.|O# |QdO1G.|OOQS1G/`1G/`OOQS,5<`,5<`O'vQdO,5<`OOQS7+%P7+%PO#!TQdO7+%POOQS-E9r-E9rOOQS7+%Q7+%QO#!eQdO,5=vO'vQdO,5=vOOQS7+$g7+$gO#!jQdO7+%PO#!rQdO7+%QO#!wQdO1G3fOOQS7+%X7+%XO##XQdO1G3fO##aQdO7+%XOOQS,5<_,5<_O'vQdO,5<_O##fQdO1G3aOOQS-E9q-E9qO#$]QdO7+%]OOQS7+%_7+%_O#$kQdO1G3aO#%YQdO7+%_O#%_QdO1G3gO#%oQdO1G3gO#%wQdO7+%]O#%|QdO,5>dO#&gQdO,5>dO#&gQdO,5>dOOQS'#Dx'#DxO#&xO&jO'#DzO#'TO`O'#HyOOOW1G3}1G3}O#'YQdO1G3}O#'bQdO1G3}O#'mQ#xO7+(fO#(^QtO1G2UP#(wQdO'#GOOOQS,5bQdO,5gQdO1G4OOOQS-E9y-E9yO#?QQdO1G4OOe,5>eOOOW7+)i7+)iO#?nQdO7+)iO#?vQdO1G2zO#@aQdO1G2zP'vQdO'#FuO0rQdO<mO#AtQdO,5>mOOQS1G0v1G0vOOQS<rO#KZQdO,5>rOOQS,5>r,5>rO#KfQdO,5>qO#KwQdO,5>qOOQS1G1Y1G1YOOQS,5;p,5;pOOQV<VAN>VO$ WQdO<cAN>cO0rQdO1G1|O$ hQtO1G1|P$ rQdO'#FvOOQS1G2R1G2RP$!PQdO'#F{O$!^QdO7+)jO$!wQdO,5>gOOOO-E9z-E9zOOOW<tO$4dQdO,5>tO1XQdO,5vO$)VQdO,5>vOOQS1G1p1G1pO$8[QtO,5<[OOQU7+'P7+'PO$+cQdO1G/iO$)VQdO,5wO$8jQdO,5>wOOQS1G1s1G1sOOQS7+'S7+'SP$)VQdO'#GdO$8rQdO1G4bO$8|QdO1G4bO$9UQdO1G4bOOQS7+%T7+%TO$9dQdO1G1tO$9rQtO'#FaO$9yQdO,5<}OOQS,5<},5<}O$:XQdO1G4cOOQS-E:a-E:aO$)VQdO,5<|O$:`QdO,5<|O$:eQdO7+)|OOQS-E:`-E:`O$:oQdO7+)|O$)VQdO,5m>pPP'Z'ZPP?PPP'Z'ZPP'Z'Z'Z'Z'Z?T?}'ZP@QP@WD_G{HPPHSH^Hb'ZPPPHeHn'RP'R'RP'RP'RP'RP'RP'R'R'RP'RPP'RPP'RP'RPHtIQIYPIaIgPIaPIaIaPPPIaPKuPLOLYL`KuPIaLiPIaPLpLvPLzM`M}NhLzLzNnN{LzLzLzLz! a! g! j! o! r! |!!S!!`!!r!!x!#S!#Y!#v!#|!$S!$^!$d!$j!$|!%W!%^!%d!%n!%t!%z!&Q!&W!&^!&h!&n!&x!'O!'X!'_!'n!'v!(Q!(XPPPPPPPPPPP!(_!(b!(h!(q!({!)WPPPPPPPPPPPP!-z!/`!3`!6pPP!6x!7X!7b!8Z!8Q!8d!8j!8m!8p!8s!8{!9lPPPPPPPPPPPPPPPPP!9o!9s!9yP!:_!:c!:o!:x!;U!;l!;o!;r!;x!_![!]Do!]!^Es!^!_FZ!_!`Gk!`!aHX!a!b%T!b!cIf!c!dJU!d!eK^!e!hJU!h!i!#f!i!tJU!t!u!,|!u!wJU!w!x!.t!x!}JU!}#O!0S#O#P&o#P#Q!0j#Q#R!1Q#R#SJU#S#T%T#T#UJU#U#VK^#V#YJU#Y#Z!#f#Z#fJU#f#g!,|#g#iJU#i#j!.t#j#oJU#o#p!1n#p#q!1s#q#r!2a#r#s!2f#s$g%T$g;'SJU;'S;=`KW<%lOJU`%YT&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T`%lP;=`<%l%To%v]&n`%c_OX%TXY%oY[%T[]%o]p%Tpq%oq#O%T#O#P&o#P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To&tX&n`OY%TYZ%oZ]%T]^%o^#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc'f[&n`O!_%T!_!`([!`#T%T#T#U(r#U#f%T#f#g(r#g#h(r#h#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(cTmR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(yT!mR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk)aV&n`&[ZOr%Trs)vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk){V&n`Or%Trs*bs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk*iT&n`&^ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To+PZS_&n`OY*xYZ%TZ]*x]^%T^#o*x#o#p+r#p#q*x#q#r+r#r;'S*x;'S;=`,^<%lO*x_+wTS_OY+rZ]+r^;'S+r;'S;=`,W<%lO+r_,ZP;=`<%l+ro,aP;=`<%l*xj,kV%rQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-XT!xY&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-oV%lQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.]V&n`&ZZOw%Twx.rx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.wV&n`Ow%Twx/^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/eT&n`&]ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/{ThZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc0cTgR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk0yXVZ&n`Oz%Tz{1f{!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk1mVaR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk2ZV%oZ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc2wTzR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To3_W%pZ&n`O!_%T!_!`-Q!`!a3w!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Td4OT&{S&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk4fX!fQ&n`O!O%T!O!P5R!P!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5WV&n`O!O%T!O!P5m!P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5tT!rZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti6[a!hX&n`O!Q%T!Q![6T![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S6T#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti7fZ&n`O{%T{|8X|}%T}!O8X!O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8^V&n`O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8z]!hX&n`O!Q%T!Q![8s![!l%T!l!m9s!m#R%T#R#S8s#S#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti9zT!hX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk:bX%qR&n`O!P%T!P!Q:}!Q!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj;UV%sQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti;ro!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!d%T!d!e?q!e!g%T!g!h7a!h!l%T!l!m9s!m!q%T!q!rA]!r!z%T!z!{Bq!{#R%T#R#S>_#S#U%T#U#V?q#V#X%T#X#Y7a#Y#^%T#^#_9s#_#c%T#c#dA]#d#l%T#l#mBq#m#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti=xV&n`O!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti>fc!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S>_#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti?vY&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti@mY!hX&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiAbX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBUX!hX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBv]&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiCv]!hX&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToDvV{_&n`O!_%T!_!`E]!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TcEdT%{R&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkEzT#gZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkFbXmR&n`O!^%T!^!_F}!_!`([!`!a([!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjGUV%mQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkGrV%zZ&n`O!_%T!_!`([!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkH`WmR&n`O!_%T!_!`([!`!aHx!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjIPV%nQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkIoV_Q#}P&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToJ_]&n`&YS%uZO!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoKZP;=`<%lJUoKge&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!tJU!t!uLx!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#gLx#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoMRa&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUkN_V&n`&`ZOr%TrsNts#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkNyV&n`Or%Trs! `s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! gT&n`&bZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! }V&n`&_ZOw%Twx!!dx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!!iV&n`Ow%Twx!#Ox#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!#VT&n`&aZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!#oe&n`&YS%uZOr%Trs!%Qsw%Twx!&px!Q%T!Q![JU![!c%T!c!tJU!t!u!(`!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#g!(`#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!%XV&n`&dZOr%Trs!%ns#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!%sV&n`Or%Trs!&Ys#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&aT&n`&fZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&wV&n`&cZOw%Twx!'^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!'cV&n`Ow%Twx!'xx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!(PT&n`&eZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!(ia&n`&YS%uZOr%Trs!)nsw%Twx!+^x!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!)uV&n`&hZOr%Trs!*[s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*aV&n`Or%Trs!*vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*}T&n`&jZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!+eV&n`&gZOw%Twx!+zx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,PV&n`Ow%Twx!,fx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,mT&n`&iZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!-Vi&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!dJU!d!eLx!e!hJU!h!i!(`!i!}JU!}#R%T#R#SJU#S#T%T#T#UJU#U#VLx#V#YJU#Y#Z!(`#Z#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUo!.}a&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!0ZT!XZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc!0qT!WR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj!1XV%kQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!1sO!]~k!1zV%jR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!2fO![~i!2mT%tX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T",tokenizers:[$k,Qk,Ak,Vk,0,1,2,3,4],topRules:{Script:[0,5]},specialized:[{term:221,get:i=>Bk[i]||-1}],tokenPrec:7652});var zr=xr([{tag:b.keyword,class:"tok-keyword"},{tag:b.operator,class:"tok-operator"},{tag:b.definitionOperator,class:"tok-definitionOperator"},{tag:b.compareOperator,class:"tok-compareOperator"},{tag:b.attributeName,class:"tok-attributeName"},{tag:b.controlKeyword,class:"tok-controlKeyword"},{tag:b.comment,class:"tok-comment"},{tag:b.string,class:"tok-string"},{tag:b.regexp,class:"tok-string2"},{tag:b.variableName,class:"tok-variableName"},{tag:b.bool,class:"tok-bool"},{tag:b.separator,class:"tok-separator"},{tag:b.literal,class:"tok-literal"},{tag:[b.number,b.integer],class:"tok-number"},{tag:b.function(b.variableName),class:"tok-function-variableName"},{tag:b.function(b.attributeName),class:"tok-function-attributeName"}]);function Tn(i){let e=document.createElement("code");e.className="sourceCode r";function t(r,s){let o=document.createTextNode(r);if(s){let a=document.createElement("span");a.appendChild(o),a.className=s,o=a}e.appendChild(o)}function n(){e.appendChild(document.createTextNode(` +`))}return Lh(i,ia.parse(i),zr,t,n),e}function Pn(i){let e=document.createElement("code");e.className="sourceCode python";function t(r,s){let o=document.createTextNode(r);if(s){let a=document.createElement("span");a.appendChild(o),a.className=s,o=a}e.appendChild(o)}function n(){e.appendChild(document.createTextNode(` +`))}return Lh(i,oa.parse(i),zr,t,n),e}function Jc(i,e,t,n){if(typeof t=="number"&&(t=t.toLocaleString()),i.textContent.includes(e)){let r=!1;for(let s of i.children)r||=Jc(s,e,t,n);if(!r)switch(i.textContent=i.textContent.replaceAll(e,()=>t),n){case"none":break;case"r":i.innerHTML=Tn(i.textContent).innerHTML;break;case"python":i.innerHTML=Pn(i.textContent).innerHTML;break;default:throw new Error(`Can't highlight interpolation, unknown language \`${n}\`.`)}return!0}return!1}var Fg=new go,Zg=new Set(["Script","Body","FunctionDefinition","ClassDefinition","LambdaExpression","ForStatement","MatchClause"]);function aa(i){return(e,t,n)=>{if(n)return!1;let r=e.node.getChild("VariableName");return r&&t(r,i),!0}}var Xk={FunctionDefinition:aa("function"),ClassDefinition:aa("class"),ForStatement(i,e,t){if(t){for(let n=i.node.firstChild;n;n=n.nextSibling)if(n.name=="VariableName")e(n,"variable");else if(n.name=="in")break}},ImportStatement(i,e){var t,n;let{node:r}=i,s=((t=r.firstChild)===null||t===void 0?void 0:t.name)=="from";for(let o=r.getChild("import");o;o=o.nextSibling)o.name=="VariableName"&&((n=o.nextSibling)===null||n===void 0?void 0:n.name)!="as"&&e(o,s?"variable":"namespace")},AssignStatement(i,e){for(let t=i.node.firstChild;t;t=t.nextSibling)if(t.name=="VariableName")e(t,"variable");else if(t.name==":"||t.name=="AssignOp")break},ParamList(i,e){for(let t=null,n=i.node.firstChild;n;n=n.nextSibling)n.name=="VariableName"&&(!t||!/\*|AssignOp/.test(t.name))&&e(n,"variable"),t=n},CapturePattern:aa("variable"),AsPattern:aa("variable"),__proto__:null};function Jg(i,e){let t=Fg.get(e);if(t)return t;let n=[],r=!0;function s(o,a){let l=i.sliceString(o.from,o.to);n.push({label:l,type:a})}return e.cursor(oe.IncludeAnonymous).iterate(o=>{if(o.name){let a=Xk[o.name];if(a&&a(o,s,r)||!r&&Zg.has(o.name))return!1;r=!1}else if(o.to-o.from>8192){for(let a of Jg(i,o.node))n.push(a);return!1}}),Fg.set(e,n),n}var Hg=/^[\w\xa1-\uffff][\w\d\xa1-\uffff]*$/,Kg=["String","FormatString","Comment","PropertyName"];function Wk(i){let e=he(i.state).resolveInner(i.pos,-1);if(Kg.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Hg.test(i.state.sliceDoc(e.from,e.to));if(!t&&!i.explicit)return null;let n=[];for(let r=e;r;r=r.parent)Zg.has(r.name)&&(n=n.concat(Jg(i.state.doc,r)));return{options:n,from:t?e.from:i.pos,validFor:Hg}}var Ik=["__annotations__","__builtins__","__debug__","__doc__","__import__","__name__","__loader__","__package__","__spec__","False","None","True"].map(i=>({label:i,type:"constant"})).concat(["ArithmeticError","AssertionError","AttributeError","BaseException","BlockingIOError","BrokenPipeError","BufferError","BytesWarning","ChildProcessError","ConnectionAbortedError","ConnectionError","ConnectionRefusedError","ConnectionResetError","DeprecationWarning","EOFError","Ellipsis","EncodingWarning","EnvironmentError","Exception","FileExistsError","FileNotFoundError","FloatingPointError","FutureWarning","GeneratorExit","IOError","ImportError","ImportWarning","IndentationError","IndexError","InterruptedError","IsADirectoryError","KeyError","KeyboardInterrupt","LookupError","MemoryError","ModuleNotFoundError","NameError","NotADirectoryError","NotImplemented","NotImplementedError","OSError","OverflowError","PendingDeprecationWarning","PermissionError","ProcessLookupError","RecursionError","ReferenceError","ResourceWarning","RuntimeError","RuntimeWarning","StopAsyncIteration","StopIteration","SyntaxError","SyntaxWarning","SystemError","SystemExit","TabError","TimeoutError","TypeError","UnboundLocalError","UnicodeDecodeError","UnicodeEncodeError","UnicodeError","UnicodeTranslateError","UnicodeWarning","UserWarning","ValueError","Warning","ZeroDivisionError"].map(i=>({label:i,type:"type"}))).concat(["bool","bytearray","bytes","classmethod","complex","float","frozenset","int","list","map","memoryview","object","range","set","staticmethod","str","super","tuple","type"].map(i=>({label:i,type:"class"}))).concat(["abs","aiter","all","anext","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dict","dir","divmod","enumerate","eval","exec","exit","filter","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","license","locals","max","min","next","oct","open","ord","pow","print","property","quit","repr","reversed","round","setattr","slice","sorted","sum","vars","zip"].map(i=>({label:i,type:"function"}))),Nk=[Rt("def ${name}(${params}):\n ${}",{label:"def",detail:"function",type:"keyword"}),Rt("for ${name} in ${collection}:\n ${}",{label:"for",detail:"loop",type:"keyword"}),Rt("while ${}:\n ${}",{label:"while",detail:"loop",type:"keyword"}),Rt("try:\n ${}\nexcept ${error}:\n ${}",{label:"try",detail:"/ except block",type:"keyword"}),Rt(`if \${}: + +`,{label:"if",detail:"block",type:"keyword"}),Rt("if ${}:\n ${}\nelse:\n ${}",{label:"if",detail:"/ else block",type:"keyword"}),Rt("class ${name}:\n def __init__(self, ${params}):\n ${}",{label:"class",detail:"definition",type:"keyword"}),Rt("import ${module}",{label:"import",detail:"statement",type:"keyword"}),Rt("from ${module} import ${names}",{label:"from",detail:"import",type:"keyword"})],jk=fg(Kg,Cc(Ik.concat(Nk)));function Gg(i){let{node:e,pos:t}=i,n=i.lineIndent(t,-1),r=null;for(;;){let s=e.childBefore(t);if(s)if(s.name=="Comment")t=s.from;else if(s.name=="Body")i.baseIndentFor(s)+i.unit<=n&&(r=s),e=s;else if(s.type.is("Statement"))e=s;else break;else break}return r}function Yg(i,e){let t=i.baseIndentFor(e),n=i.lineAt(i.pos,-1),r=n.from+n.text.length;return/^\s*($|#)/.test(n.text)&&i.node.tot?null:t+i.unit}var Kc=dn.define({name:"python",parser:oa.configure({props:[Cr.add({Body:i=>{var e;let t=Gg(i);return(e=Yg(i,t||i.node))!==null&&e!==void 0?e:i.continue()},IfStatement:i=>/^\s*(else:|elif )/.test(i.textAfter)?i.baseIndent:i.continue(),"ForStatement WhileStatement":i=>/^\s*else:/.test(i.textAfter)?i.baseIndent:i.continue(),TryStatement:i=>/^\s*(except |finally:|else:)/.test(i.textAfter)?i.baseIndent:i.continue(),"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression":Mi({closing:")"}),"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression":Mi({closing:"}"}),"ArrayExpression ArrayComprehensionExpression":Mi({closing:"]"}),"String FormatString":()=>null,Script:i=>{var e;let t=Gg(i);return(e=t&&Yg(i,t))!==null&&e!==void 0?e:i.continue()}}),Rr.add({"ArrayExpression DictionaryExpression SetExpression TupleExpression":To,Body:(i,e)=>({from:i.from+1,to:i.to-(i.to==e.doc.length?0:1)})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""'],stringPrefixes:["f","fr","rf","r","u","b","br","rb","F","FR","RF","R","U","B","BR","RB"]},commentTokens:{line:"#"},indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:)$/}});function eO(){return new pn(Kc,[Kc.data.of({autocomplete:Wk}),Kc.data.of({autocomplete:jk})])}var zk=dn.define({parser:ia.configure({props:[Cr.add({Block:Mi({closing:"}"}),"ParamList ArgList":Mi({closing:")"})}),Rr.add({Block:To})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"']},commentTokens:{line:"#"}}});function tO(){return new pn(zk)}var Yk={"arrow-repeat":iO(),"exclamation-circle":nO(),lightbulb:rO(),play:sO()};function Zk(){let i=document.querySelectorAll(".tab-content > .tab-pane");Array.from(i).forEach(t=>{t.innerHTML.trim()==""&&(t.classList.add("d-none"),document.querySelector(`.nav-item > a[data-bs-target="#${t.id}"]`)?.parentElement?.classList.add("d-none"))});let e=document.querySelectorAll(".tab-content");Array.from(e).forEach(t=>{if(Array.from(t.children).reduce((r,s)=>s.classList.contains("d-none")?r:r+1,0)==1){let r=t.querySelector(".tab-pane:not(.d-none)"),s=t.parentElement;s.appendChild(r),s.querySelector(".nav.nav-tabs").remove(),t.remove()}})}var la=class{constructor(e,t){if(typeof e!="string")throw new Error("Can't create editor, `code` must be a string.");this.container=document.createElement("div"),this.initialCode=e,this.options=Object.assign({autorun:!1,completion:!0,runbutton:!0,startover:!0,persist:!1},t),this.storageKey=`editor-${window.location.href}#${this.options.id}`;let n=[Eg,this.languageExtensions(),E.updateListener.of(a=>this.onViewUpdate(a))];if(this.options.persist){let a=window.localStorage.getItem(this.storageKey);a&&(e=a)}this.state=N.create({doc:e,extensions:n}),this.view=new E({state:this.state});let r=this.render(),s=String(t["min-lines"]||0),o=String(t["max-lines"])||"infinity";r.style.setProperty("--exercise-min-lines",s),r.style.setProperty("--exercise-max-lines",o),this.container.oninput=a=>this.onInput(a),this.container.appendChild(r),this.container.value={code:this.options.autorun?e:null,options:this.options},this.container.value.indicator=this.indicator=new Ke({runningCallback:()=>{Array.from(this.container.getElementsByClassName("exercise-editor-eval-indicator")).forEach(a=>a.classList.remove("d-none"))},finishedCallback:()=>{Array.from(this.container.getElementsByClassName("exercise-editor-eval-indicator")).forEach(a=>a.classList.add("d-none"))},busyCallback:()=>{Array.from(this.container.getElementsByClassName("exercise-editor-btn-run-code")).forEach(a=>a.classList.add("disabled"))},idleCallback:()=>{Array.from(this.container.getElementsByClassName("exercise-editor-btn-run-code")).forEach(a=>a.classList.remove("disabled"))}})}onInput(e){if(this.options.runbutton&&!e.detail.commit){e.preventDefault(),e.stopImmediatePropagation();return}this.container.value.code=this.view.state.doc.toString(),"code"in e.detail&&(this.container.value.code=e.detail.code),this.options.persist&&window.localStorage.setItem(this.storageKey,this.container.value.code)}onViewUpdate(e){e.docChanged&&this.container.dispatchEvent(new CustomEvent("input",{detail:{commit:!1}}))}renderButton(e){let t=document.createElement("a"),n=document.createElement("span");return t.className=`d-flex align-items-center gap-1 btn btn-exercise-editor ${e.className} text-nowrap`,t.setAttribute("role","button"),t.setAttribute("aria-label",e.text),n.className="btn-label-exercise-editor",n.innerText=e.text,t.innerHTML=Yk[e.icon],t.appendChild(n),t.onclick=e.onclick||null,t.onkeydown=e.onclick||null,t}renderButtonGroup(e){let t=document.createElement("div");return t.className="btn-group btn-group-exercise-editor btn-group-sm",e.forEach(n=>t.appendChild(n)),t}renderSpinner(){let e=document.createElement("div");return e.className="exercise-editor-eval-indicator spinner-grow spinner-grow-sm",e.setAttribute("role","status"),e}renderHintButton(e,t){return Array.from(e).reduceRight((n,r,s,o)=>this.renderButton({text:s===0?"Show Hint":"Next Hint",icon:"lightbulb",className:"btn-outline-dark btn-sm",onclick:function(){s>0&&o[s-1].classList.add("d-none"),r.classList.remove("d-none"),n?this.replaceWith(n):this.remove()}}),t)}renderSolutionButton(e,t){return this.renderButton({text:"Show Solution",icon:"exclamation-circle",className:"btn-exercise-solution btn-outline-dark btn-sm",onclick:function(){t&&t.forEach(n=>n.classList.add("d-none")),Array.from(e).forEach(n=>{n.classList.remove("d-none")}),this.remove()}})}renderHintsTabset(e,t){let n=new Set;e.forEach(s=>{let o=s.parentElement;o.id.includes("tabset-")&&n.add(o)});let r=new Set;return t.forEach(s=>{let o=s.parentElement;o.id.includes("tabset-")&&r.add(o)}),n.forEach(s=>{let o=document.createElement("div");o.className="d-flex justify-content-between exercise-tab-pane-header";let a=s.querySelectorAll(`.exercise-hint[data-exercise="${this.options.exercise}"]`);o.appendChild(this.renderHintButton(a,null)),s.prepend(o)}),r.forEach(s=>{let o=document.createElement("div");o.className="d-flex justify-content-between exercise-tab-pane-header";let a=s.querySelectorAll(`.exercise-solution[data-exercise="${this.options.exercise}"]`);o.appendChild(this.renderSolutionButton(a,null)),s.prepend(o)}),null}renderHints(){let e=document.querySelectorAll(`.d-none.exercise-hint[data-exercise="${this.options.exercise}"]`),t=document.querySelectorAll(`.d-none.exercise-solution[data-exercise="${this.options.exercise}"]`),n=Array.from(e).some(s=>s.parentElement.id.includes("tabset-"))||Array.from(t).some(s=>s.parentElement.id.includes("tabset-")),r=null;if(n)this.renderHintsTabset(e,t);else{let s;t.length>0&&(s=this.renderSolutionButton(t,e)),r=this.renderHintButton(e,s)}return Zk(),r}render(){let e=document.createElement("div"),t=document.createElement("div"),n=document.createElement("div");e.className="card exercise-editor my-3",t.className="card-header exercise-editor-header d-flex justify-content-between",n.className="card-body exercise-editor-body p-0";let r=document.createElement("div");r.className="d-flex align-items-center gap-3";let s=document.createElement("div");s.innerHTML="caption"in this.options?this.options.caption:this.defaultCaption,r.appendChild(s);let o=[];this.options.startover&&o.push(this.renderButton({text:"Start Over",icon:"arrow-repeat",className:"btn-outline-dark",onclick:()=>{if(this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:this.initialCode}}),this.options.runbutton){let c=this.options.autorun?this.initialCode:null;this.container.dispatchEvent(new CustomEvent("input",{detail:{code:c,commit:!0}}))}}}));let a=this.renderHints();a&&o.push(a),o.length>0&&r.appendChild(this.renderButtonGroup(o)),t.appendChild(r);let l=document.createElement("div");l.className="d-flex align-items-center gap-3";let h=[];return this.options.runbutton&&h.push(this.renderButton({text:"Run Code",icon:"play",className:"btn-primary disabled exercise-editor-btn-run-code",onclick:()=>{this.container.dispatchEvent(new CustomEvent("input",{detail:{commit:!0}}))}})),l.appendChild(this.renderSpinner()),h.length>0&&l.appendChild(this.renderButtonGroup(h)),t.appendChild(l),e.appendChild(t),n.appendChild(this.view.dom),e.appendChild(n),e}},ha=class extends la{constructor(e,t,n){super(t,n),this.webRPromise=e,this.completionMethods=this.setupCompletion()}languageExtensions(){let e=new Dt,t=new Dt;return[Ar(zr),Xr({override:[(...n)=>this.doCompletion(...n)]}),e.of(tO()),t.of(N.tabSize.of(2)),Qe.high(qt.of([{key:"Mod-Enter",run:()=>(this.container.dispatchEvent(new CustomEvent("input",{detail:{commit:!0}})),!0)},{key:"Mod-Shift-m",run:()=>(this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:this.view.state.doc.toString().trimEnd()+" |> "}}),!0)}]))]}render(){return this.defaultCaption="R Code",super.render()}async setupCompletion(){let e=await this.webRPromise;return await e.evalRVoid("rc.settings(func=TRUE, fuzzy=TRUE)"),{assignLineBuffer:await e.evalR("utils:::.assignLinebuffer"),assignToken:await e.evalR("utils:::.assignToken"),assignStart:await e.evalR("utils:::.assignStart"),assignEnd:await e.evalR("utils:::.assignEnd"),completeToken:await e.evalR("utils:::.completeToken"),retrieveCompletions:await e.evalR("utils:::.retrieveCompletions")}}async doCompletion(e){if(!this.options.completion)return null;let t=await this.completionMethods,n=e.state.doc.lineAt(e.state.selection.main.head).text,{from:r,to:s,text:o}=e.matchBefore(/[a-zA-Z0-9_.:]*/)??{from:0,to:0,text:""};if(r===s&&!e.explicit)return null;await t.assignLineBuffer(n.replace(/\)+$/,"")),await t.assignToken(o),await t.assignStart(r+1),await t.assignEnd(s+1),await t.completeToken();let l=(await t.retrieveCompletions()).values.map(h=>{if(!h)throw new Error("Missing values in completion result.");return{label:h,boost:h.endsWith("=")?10:0}});return{from:r,options:l}}},ca=class extends la{constructor(e,t,n){super(t,n),this.pyodidePromise=e}render(){return this.defaultCaption="Python Code",super.render()}languageExtensions(){let e=new Dt,t=new Dt,n=[Ar(zr),e.of(eO()),t.of(N.tabSize.of(2)),Qe.high(qt.of([{key:"Mod-Enter",run:()=>(this.container.dispatchEvent(new CustomEvent("input",{detail:{commit:!0}})),!0)}]))];return this.options.completion||n.push(Xr({override:[(...r)=>null]})),n}};function Cn(i){for(var e="",t=new Uint8Array(i),n=t.byteLength,r=0;rString.fromCharCode(parseInt(t,16))))}function aO(i){return decodeURIComponent(atob(i).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function ef(i){return typeof ImageBitmap<"u"&&i instanceof ImageBitmap}function Ur(i,e,t,...n){return i==null||ef(i)||i instanceof ArrayBuffer||ArrayBuffer.isView(i)?i:e(i)?t(i,...n):Array.isArray(i)?i.map(r=>Ur(r,e,t,...n)):typeof i=="object"?Object.fromEntries(Object.entries(i).map(([r,s])=>[r,Ur(s,e,t,...n)])):i}function fa(i){for(let e of i.getElementsByTagName("script"))if(!e.type||e.type=="text/javascript"||e.type=="module"){let t=document.createElement("script");e.async&&(t.async=e.async),e.crossOrigin&&(t.crossOrigin=e.crossOrigin),e.defer&&(t.defer=e.async),e.integrity&&(t.integrity=e.integrity),e.src&&(t.src=e.src),e.text&&(t.text=e.text),e.type&&(t.type=e.type),e.parentNode.replaceChild(t,e)}}function lO(i){return new Promise(function(e,t){var n=document.createElement("script");n.onload=()=>e(i),n.onerror=()=>t(`Can't load script: "${i}".`),n.async=!0,n.src=i,document.getElementsByTagName("head")[0].appendChild(n)})}function hO(i){let e=i.replace(/\/+/g,"/").split("/"),t=[];for(let n of e)n==="."||n===""||(n===".."?t.pop():t.push(n));return t.join("/")}var cO=[];async function Fr(i){let e=await i.toJs({depth:-1}),t=await Promise.all(e.names.map(async(n,r)=>[n,await e.values[r].toString()]));return Object.fromEntries(t)}async function tf(i,e){let t=await i.toJs({depth:-1});return await Promise.all(t.values.map(async n=>({[e]:await n.toString()})))}async function nf(i){let e=await i.toJs({depth:-1});return await Promise.all(e.values.map(t=>Fr(t)))}async function Jk(i){if(!(await(await i.class()).toArray()).includes("html_dependency"))throw new Error("Can't interpret R object of class `${classes}` as HTML dependency.");let t=await i.get("attachment"),n=await i.get("head"),r=await i.get("meta"),s=await(await i.get("name")).toString(),o=await i.get("package"),a=await i.get("restyle"),l=await i.get("script"),h=await i.get("src"),c=await i.get("stylesheet"),f=await(await i.get("version")).toString(),u={attachment:[],head:Re(n)?void 0:await n.toString(),meta:[],name:s,pkg:Re(o)?void 0:await o.toString(),restyle:Re(a)?void 0:await a.toBoolean(),script:[],src:{},stylesheet:[],version:f};if(Ui(h)?u.src={file:await h.toString()}:ot(h)&&(u.src=await Fr(h)),!Re(r)){let d=await r.toObject();u.meta=await Promise.all(Object.entries(d).map(async([m,p])=>({name:m,content:await p.toString()})))}if(Ui(c))u.stylesheet=(await c.toArray()).map(d=>({href:d}));else if(ot(c)){let d=await c.toJs({depth:-1});d.names?d.names.includes("href")?u.stylesheet=[await Fr(c)]:u.stylesheet=await nf(c):u.stylesheet=await tf(c,"href")}if(Ui(l))u.script=(await l.toArray()).map(d=>({src:d}));else if(ot(l)){let d=await l.toJs({depth:-1});d.names?d.names.includes("src")?u.script=[await Fr(l)]:u.script=await nf(l):u.script=await tf(l,"src")}if(Ui(t))u.attachment=(await t.toArray()).map((d,m)=>({key:(m+1).toString(),href:d}));else if(ot(t)){let d=await t.toJs({depth:-1});d.names?d.names.includes("href")?(u.attachment=[await Fr(t)],u.attachment[0].key="1"):(u.attachment=await nf(t),u.attachment.forEach((m,p)=>{m.key=(p+1).toString()})):(u.attachment=await tf(t,"href"),u.attachment.forEach((m,p)=>{m.key=(p+1).toString()}))}return u}async function rf(i,e){let t=await Jk(e),n=t.pkg?await i.evalRString(`find.package("${t.pkg}")`):"";if(t.name in cO)return!1;if(cO[t.name]=t.version,t.head){let r=document.createElement("div");r.innerHTML=t.head,r.childNodes.forEach(s=>document.head.appendChild(s))}if(t.meta&&t.meta.forEach(async r=>{let s=document.createElement("meta");Object.entries(r).map(([o,a])=>{s.setAttribute(o,a||"")}),document.head.appendChild(s)}),t.stylesheet&&t.stylesheet.forEach(async r=>{let s=document.createElement("link");if(t.src.file){let o=await i.FS.readFile(`${n}/${t.src.file}/${r.href}`);r.href=`data:text/css;base64,${Cn(o)}`}else r.href=`${t.src.href}/${r.href}`;r.rel||(s.rel="stylesheet"),r.type||(s.type="text/css"),Object.entries(r).map(([o,a])=>{s.setAttribute(o,a||"")}),document.head.appendChild(s)}),t.script){let r=t.script.map(async s=>{let o=document.createElement("script");if(t.src.file){let l=await i.FS.readFile(`${n}/${t.src.file}/${s.src}`);s.src=`data:text/javascript;base64,${Cn(l)}`}else s.src=`${t.src.href}/${s.src}`;o.async=!1,Object.entries(s).map(([l,h])=>{l==="async"&&(o.async=h==="true"),o.setAttribute(l,h||"")});let a=new Promise((l,h)=>{o.onload=()=>l(null),o.onerror=c=>h(c)});return document.head.appendChild(o),a});await Promise.allSettled(r)}return!0}var Rn=class{constructor(e,t){this.manager=e;let n=t.options;!n.exercise||n.envir==="global"?(this.labels={prep:n.envir,result:n.envir,grading:n.envir,solution:n.envir,global:"global"},this.discard=!1):(this.labels={prep:`${n.envir}-prep`,result:`${n.envir}-result`,grading:`${n.envir}-grading`,solution:`${n.envir}-solution`,global:"global"},this.discard=n.envir===`exercise-env-${n.exercise}`)}get(e="global"){return this.manager.get(this.labels[e])}bind(e,t,n="global"){return this.manager.bind(e,t,this.labels[n])}create(e,t){return this.manager.create(this.labels[e],this.labels[t],this.discard)}destroy(e){return this.manager.destroy(this.labels[e])}},En=class i{constructor(e){this.env={};this.shelter=new e.Shelter,this.env.global=Promise.resolve().then(()=>e.objs.globalEnv)}static#e;static instance(e){return i.#e||(i.#e=new i(e)),i.#e}async toR(e){if(!e||ee(e))return e;let t=await this.shelter;if(e.constructor===Object)try{return await new t.RObject(e)}catch(n){let r=n;if(!r.message.includes("Can't construct `data.frame`"))throw r;return await new t.RList(Object.fromEntries(await Promise.all(Object.entries(e).map(async([s,o])=>[s,await this.toR(o)]))))}if(e.constructor===Array)try{return await new t.RObject(e)}catch(n){let r=n;if(!r.message.includes("Can't construct `data.frame`"))throw r;return await new t.RList(await Promise.all(e.map(s=>this.toR(s))))}return e}async get(e="global"){let t=await this.shelter;return e in this.env||(this.env[e]=t.evalR("new.env(parent = globalenv())")),await this.env[e]}async bind(e,t,n="global"){let r=await this.get(n);t=await this.toR(t),await r.bind(e,t)}async create(e,t,n=!0){if(e===t||e==="global")return this.get(e);if(e in this.env){if(!n)return this.get(e);await this.destroy(e)}let r=await this.shelter,s=await this.get(t);return this.env[e]=r.evalR("new.env(parent = parent)",{env:{parent:s}}),await this.env[e]}async destroy(e){if(e=="global"||!(e in this.env))return;let t=await this.shelter,n=await this.env[e];try{await t.destroy(n)}catch(r){let s=r;if(!s.message.includes("Can't find object in shelter."))throw s}delete this.env[e]}},An=class i{constructor(e){this.env={};this.pyodide=e,this.env.global=Promise.resolve().then(()=>e.toPy({}))}static#e;static instance(e){return i.#e||(i.#e=new i(e)),i.#e}async get(e="global"){return e in this.env||(this.env[e]=this.pyodide.toPy({})),await this.env[e]}async bind(e,t,n="global"){let r=await this.get(n),s=await this.pyodide.toPy({environment:r,key:e,value:t});await this.pyodide.runPythonAsync("environment[key] = value",{locals:s}),s.destroy()}async create(e,t,n=!0){if(e===t||e==="global")return this.get(e);n&&e in this.env&&await this.destroy(e);let r=await this.get(e),s=await this.get(t),o=await this.pyodide.toPy({target:r,parent:s});return await this.pyodide.runPythonAsync("target.update(parent)",{locals:o}),o.destroy(),await this.env[e]}async destroy(e){if(e=="global"||!(e in this.env))return;await(await this.env[e]).destroy(),delete this.env[e]}};var ua=class{constructor(e,t){this.container=this.newContainer(),this.nullResult={result:null,evaluate_result:null,evaluator:this},this.container.value=this.nullResult,this.webR=e,this.context=t,this.shelter=new e.Shelter,this.envManager=new Rn(En.instance(e),t),this.options=Object.assign({envir:"global",eval:!0,echo:!1,warning:!0,error:!0,include:!0,output:!0,timelimit:30},t.options)}newContainer(){let e=document.createElement("div");return e.classList.add("cell-output-container"),e.classList.add("cell-output-container-webr"),e}async purge(){(await this.shelter).purge()}getSetupCode(){let e=this.options.exercise,t=document.querySelectorAll(`script[type="exercise-setup-${e}-contents"]`);if(t.length>0)return t.length>1&&console.warn(`Multiple \`setup\` blocks found for exercise "${e}", using the first.`),JSON.parse(atob(t[0].textContent)).code}async process(e){if(!this.options.eval){this.container=this.asSourceHTML(this.context.code),this.container.value=this.nullResult;return}if(this.options.exercise&&this.context.code&&this.context.code.match(/_{6}_*/g)){this.container.value.result=null;return}let t=this.context.indicator;this.context.indicator||(t=new Ke),t.running();try{await Promise.all(Object.entries(e).map(async([l,h])=>{await this.envManager.bind(l,h,"prep")}));let n=this.getSetupCode();await this.evaluate(n,"prep"),await this.envManager.create("result","prep");let r=await this.evaluate(this.context.code,"result");if(!r)this.container.value.result=null;else if(this.options.output==="asis"){let l=await r.toArray(),h=await l[l.length-1].get("value");this.container.innerHTML=await h.toString()}else if(this.container=await this.asHtml(r),!this.options.output){let l=this.container.value;this.container=this.newContainer(),this.container.value=l}let s=await this.envManager.get("result"),a=await(await this.webR.objs.globalEnv.get(".webr_ojs")).toObject({depth:-1});typeof this.options.define=="string"?a[this.options.define]=await s.get(this.options.define):this.options.define&&Object.assign(a,Object.fromEntries(await Promise.all(this.options.define.map(async l=>{let h=await s.get(l);return[l,h]})))),Object.keys(a).forEach(async l=>{let h=await this.asOjs(a[l]);window._ojs.ojsConnector.mainModule._scope.has(l)?window._ojs.ojsConnector.mainModule.redefine(l,()=>h):window._ojs.ojsConnector.define(l)(h)}),await this.webR.evalRVoid("rm(list = ls(.webr_ojs), envir = .webr_ojs)")}finally{this.purge(),t.finished(),this.context.indicator||t.destroy()}}async evaluate(e,t,n=this.options){return e==null?null:(await(await this.shelter).captureR(` + setTimeLimit(elapsed = timelimit) + on.exit(setTimeLimit(elapsed = Inf)) + eval_result <- evaluate::evaluate( + code, + envir = envir, + keep_message = warning, + keep_warning = warning, + stop_on_error = error, + filename = "User code", + output_handler = getOption("webr.evaluate.handler") + ) + knitr:::merge_low_plot(eval_result) + `,{env:{code:e,timelimit:Number(n.timelimit),envir:await this.envManager.get(t),warning:n.warning,error:n.error?0:1}})).result}asSourceHTML(e){let t=document.createElement("div"),n=document.createElement("pre");t.className="sourceCode",n.className="sourceCode r";let r=Tn(e);return n.appendChild(r),t.appendChild(n),t}async asHtml(e,t=this.options){let n=[],r=this.newContainer();r.value=this.nullResult;let s=()=>{if(t.echo&&n.length){let m=document.createElement("div"),p=document.createElement("pre");m.className="sourceCode",p.className="sourceCode r";let g=Tn(n.join(""));p.appendChild(g),m.appendChild(p),r.appendChild(m)}n.length=0},o=m=>{let p=document.createElement("div");p.className="exercise-cell-output cell-output cell-output-webr cell-output-stdout",p.innerHTML=`
${m}
`,t.output&&(s(),r.appendChild(p))},a=m=>{let p=document.createElement("div");p.className="exercise-cell-output cell-output cell-output-webr cell-output-stderr",p.innerHTML=`
${m}
`,t.output&&(s(),r.appendChild(p))},l=m=>{let p=document.createElement("canvas");p.width=m.width,p.height=m.height,p.className="img-fluid figure-img",p.style.width=`${2*m.width/3}px`,p.getContext("bitmaprenderer").transferFromImageBitmap(m);let g=document.createElement("div");g.className="cell-output-display cell-output-webr",g.appendChild(p),t.output&&(s(),r.appendChild(g))},h=async(m,p,g)=>{if(t.output){s();let O=await u.evalR("format(cnd, backtrace = FALSE)",{env:{cnd:m}}),y=await O.names(),v="",x="";if(y&&y.includes("message")){let P=await m.get("message"),C=await m.get("call");x=await gs(C)?` in \`${await C.deparse()}\``:": ",v=`${g}: ${await P.toString()}`}else v=await O.toString();let w=document.createElement("div");w.innerHTML=` +
+
+
+
R ${g}${x}
+
+
+

+          
+
+ `,w.querySelector(".callout-body pre").appendChild(document.createTextNode(v)),r.appendChild(w)}},c=async m=>{if(t.output){let p=await m.toString(),g=await(await m.attrs()).get("knit_meta"),O=document.createElement("div");if(O.className="cell-output cell-output-webr",O.innerHTML=p,fa(O),s(),r.appendChild(O),ot(g)){let y=await g.toArray();for(let v=0;v{if(t.output){let g=document.createElement("div"),O=document.createElement("img");g.className="cell-output-display cell-output-pyodide",O.src=`data:${m};base64, ${p}`,g.appendChild(O),r.appendChild(g)}},u=await this.shelter,d=await e.toArray();for(let m=0;m{try{let o=await this.webR.evalRNumber('72 * getOption("webr.fig.width")'),a=await this.webR.evalRNumber('72 * getOption("webr.fig.height")'),l=[],h=typeof OffscreenCanvas<"u";h||this.webR.evalRVoid(` + while (dev.cur() > 1) dev.off() + options(device = function() { + png(file = "/tmp/.webr-plot.png", width = width, height = height) + }) + `,{env:{width:o,height:a}});let c=await r.capture({withAutoprint:!0,captureGraphics:h?{width:o,height:a}:!1},...s);if(h)l=c.images;else{let f=await this.webR.evalR(` + while (dev.cur() > 1) dev.off() + filename <- "/tmp/.webr-plot.png" + if (file.exists(filename)) { + filesize <- file.info(filename)[["size"]] + readBin(filename, "raw", n = filesize) + } else NULL + `);if(Ja(f)){let u=await f.toTypedArray(),d=document.createElement("img");d.src=`data:image/png;base64, ${Cn(u)}`,l=[d]}}if(l.length){let f=await this.asOjs(l[l.length-1]);return f.value=await this.asOjs(c.result),f}return await this.asOjs(c.result)}finally{this.webR.globalShelter.purge()}};switch(r._payload.obj.type){case"null":return null;case"character":if((await(await r.class()).toArray()).includes("knit_asis")){let o=await r.toString(),a=await(await r.attrs()).get("knit_meta"),l=document.createElement("div");if(l.className="cell-output",l.innerHTML=o,ot(a)){let h=await a.toArray();for(let c=0;c{window.HTMLWidgets.staticRender()},250),l}case"logical":case"double":case"raw":case"integer":return await r.toArray();case"list":{let o=await(await r.attrs()).get("class");if(!Re(o)&&(await o.toArray()).includes("data.frame"))return await r.toD3()}case"environment":case"pairlist":{let s={},o=await r.toJs({depth:-1});for(let a=0;a0)return t.length>1&&console.warn(`Multiple \`setup\` blocks found for exercise "${e}", using the first.`),JSON.parse(atob(t[0].textContent)).code}async process(e){if(!this.options.eval){this.container=this.asSourceHTML(this.context.code),this.container.value=this.nullResult;return}if(this.options.exercise&&this.context.code&&this.context.code.match(/_{6}_*/g)){this.container.value.result=null;return}let t=this.context.indicator;this.context.indicator||(t=new Ke),t.running();try{await Promise.all(Object.entries(e).map(async([a,l])=>{await this.envManager.bind(a,l,"prep")}));let n=this.getSetupCode();await this.evaluate(n,"prep"),await this.envManager.create("result","prep");let r=await this.evaluate(this.context.code,"result");if(!r)this.container.value.result=null;else if(this.options.output==="asis")this.container.innerHTML=await r.stdout;else if(this.container=await this.asHtml(r),!this.options.output){let a=this.container.value;this.container=this.newContainer(),this.container.value=a}let s=await this.envManager.get("result"),o={};typeof this.options.define=="string"?o[this.options.define]=await s.get(this.options.define):this.options.define&&Object.assign(o,Object.fromEntries(await Promise.all(this.options.define.map(async a=>{let l=await s.get(a);return[a,l]})))),Object.keys(o).forEach(async a=>{let l=await this.asOjs(o[a]);window._ojs.ojsConnector.mainModule._scope.has(a)?window._ojs.ojsConnector.mainModule.redefine(a,()=>l):window._ojs.ojsConnector.define(a)(l)})}finally{t.finished(),this.context.indicator||t.destroy()}}async evaluate(e,t,n=this.options){if(e==null)return null;await this.pyodide.loadPackagesFromImports(e);let[r,s,o]=[7,5,100];"fig-width"in this.options&&(r=Number(this.options["fig-width"])),"fig-height"in this.options&&(s=Number(this.options["fig-height"])),"fig-dpi"in this.options&&(o=Number(this.options["fig-dpi"]));let a=await this.pyodide.toPy({code:e,dpi:o,width:r,height:s,environment:await this.envManager.get(t)}),l=await this.pyodide.runPythonAsync(atob(fO()),{locals:a});a.destroy();let h=await l.get("value"),c=await l.get("stdout"),f=await l.get("stderr"),u=await l.get("outputs");return{value:h,stdout:c,stderr:f,outputs:u}}asSourceHTML(e){let t=document.createElement("div"),n=document.createElement("pre");t.className="sourceCode",n.className="sourceCode python";let r=Pn(e);return n.appendChild(r),t.appendChild(n),t}async asOjs(e){return Object.getOwnPropertyNames(e).includes("toJs")?e.toJs():e}async asHtml(e,t=this.options){let n=this.newContainer();if(n.value=this.nullResult,!e)return n;let r=h=>{if(h.width<=1&&h.height<=1)return;let c=document.createElement("canvas");c.width=h.width,c.height=h.height,c.className="img-fluid figure-img",c.style.width=`${2*h.width/3}px`,c.getContext("bitmaprenderer").transferFromImageBitmap(h);let f=document.createElement("div");f.className="cell-output-display cell-output-pyodide",f.appendChild(c),t.output&&n.appendChild(f)},s=h=>{if(t.output){let c=document.createElement("div");c.appendChild(document.createTextNode(h)),c.className="cell-output cell-output-pyodide",c.innerHTML=`
${c.innerHTML}
`,n.appendChild(c)}},o=async h=>{let c=await this.pyodide.runPythonAsync(` + import ipywidgets as widgets + import json + json.dumps(widgets.Widget.get_manager_state()) + `);Qn||(Qn=document.createElement("script"),Qn.type="application/vnd.jupyter.widget-state+json",Qn=document.body.appendChild(Qn),await lO("https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@1.0.11/dist/embed.js")),Qn.innerHTML=c;let f=await this.pyodide.toPy({widget:h}),u=await this.pyodide.runPythonAsync(` + import json + json.dumps(widget) + `,{locals:f});f.destroy();let d=document.createElement("script");d.type="application/vnd.jupyter.widget-view+json",d.innerHTML=u,n.appendChild(d),dispatchEvent(new Event("load"))},a=async h=>{if(t.output){let c=document.createElement("div");c.className="cell-output cell-output-pyodide",c.innerHTML=h,fa(c),n.appendChild(c)}},l=async(h,c)=>{if(t.output){let f=document.createElement("div"),u=document.createElement("img");f.className="cell-output-display cell-output-pyodide",u.src=`data:${h};base64, ${c}`,f.appendChild(u),n.appendChild(f)}};if(t.echo){let h=document.createElement("div"),c=document.createElement("pre");h.className="sourceCode",c.className="sourceCode python";let f=Pn(this.context.code);c.appendChild(f),h.appendChild(c),n.appendChild(h)}if(e.stdout){let h=document.createElement("div");h.className="exercise-cell-output cell-output cell-output-pyodide cell-output-stdout",h.innerHTML=`
${e.stdout}
`,n.appendChild(h)}if(e.stderr){let h=document.createElement("div");h.className="exercise-cell-output cell-output cell-output-pyodide cell-output-stderr",h.innerHTML=`
${e.stderr}
`,n.appendChild(h)}for(let h=0;h0)return t.length>1&&console.warn(`Multiple \`check\` blocks found for exercise "${e}", using the first.`),JSON.parse(atob(t[0].textContent)).code}};var pa=class extends Mn{constructor(e){super(e),this.webR=this.evaluator.webR}async gradeExercise(){let e=this.context.code;if(!e)return null;let t=await this.blankCheck(e);if(!Re(t))return await this.feedbackAsHtmlAlert(t);if(t=await this.parseCheck(e),!Re(t))return await this.feedbackAsHtmlAlert(t);let n=this.context.indicator;this.context.indicator||(n=new Ke),n.running();try{if(t=await this.evaluateExercise(),Re(t))return null;let r=await this.evaluator.asHtml(t,this.options),s=await r.value.result,o=await(await s.class()).toArray();if(o.includes("gradethis_graded")||o.includes("gradethis_feedback"))return await this.feedbackAsHtmlAlert(s);if(ot(s)){let a=await s.get("message"),l=await s.get("correct");if(!Re(a)&&!Re(l))return await this.feedbackAsHtmlAlert(s)}return r}finally{n.finished(),this.context.indicator||n.destroy()}}async parseCheck(e,t){let n=await this.evaluator.shelter;try{return await n.evalR("parse(text = user_code)",{env:{user_code:e}}),this.evaluator.webR.objs.null}catch{return await new n.RList({message:await n.evalR(`htmltools::HTML(" + It looks like this might not be valid R code. + R cannot determine how to turn your text into a complete command. + You may have forgotten to fill in a blank, + to remove an underscore, to include a comma between arguments, + or to close an opening ", ', ( + or { with a matching ", ', + ) or }. + ")`),correct:!1,location:"append",type:"error"})}finally{n.purge()}}async blankCheck(e){let t=await this.evaluator.shelter;return e.match(/_{6}_*/g)?await new t.RList({message:"Please replace ______ with valid code.",correct:!1,location:"append",type:"info"}):this.evaluator.webR.objs.null}async evaluateSolution(){let e=this.evaluator.options.exercise,t=document.querySelectorAll(`.exercise-solution[data-exercise="${e}"] > code.solution-code`);if(t.length>0){t.length>1&&console.warn(`Multiple solutions found for exercise "${e}", using first solution.`);let n=await this.evaluator.shelter;await this.envManager.create("solution","prep");let r=await this.envManager.get("solution"),s=t[0].textContent,o=await n.evalR(s,{env:r});return{envir:r,code:s,result:o}}return null}async evaluateExercise(){await this.envManager.create("grading","result");let e=await this.evaluator.shelter;try{let t=await this.envManager.get("result"),n=this.evaluator.container.value.evaluate_result,r=await this.envManager.get("prep"),s=this.evaluator.container.value.result,o={user_code:this.context.code,stage:"check",engine:"r",label:this.context.options.exercise||this.webR.objs.null,check_code:this.getCheckingAlgorithm()||this.webR.objs.null,envir_result:t,evaluate_result:n,envir_prep:r,last_value:s,solution_code:this.webR.objs.null,solution_code_all:this.webR.objs.null,envir_solution:this.webR.objs.null,solution:this.webR.objs.null},a=await this.evaluateSolution();a&&(o.solution_code=a.code,o.solution_code_all=[a.code],o.envir_solution=a.envir,o.solution=a.result);let l=await new e.RList(o);await this.envManager.bind(".checker_args",l,"grading");let h={...this.options};return h.error=!1,h.output=!0,await this.evaluator.evaluate(`.checker <- getOption('webr.exercise.checker') + environment(.checker) <- environment() + do.call(.checker, .checker_args)`,"grading",h)}finally{e.purge()}}async feedbackAsHtmlAlert(e){let t=await this.evaluator.shelter,n=document.createElement("div"),r=await e.get("type"),s=await e.get("correct");switch(n.classList.add("alert"),n.classList.add("exercise-grade"),await r.toString()){case"success":n.classList.add("alert-success");break;case"info":n.classList.add("alert-info");break;case"warning":n.classList.add("alert-warning");break;case"error":case"danger":n.classList.add("alert-danger");break;default:{let u=await s.toArray();u.length>0&&u[0]?n.classList.add("alert-success"):n.classList.add("alert-danger")}}let o=document.createElement("span");o.className="exercise-feedback";let a=await e.get("message");a=(await t.captureR("knitr::knit_print(grade$message)",{env:{grade:e}})).result;let h=await a.toString(),c=document.createElement("div");c.innerHTML=h,n.append(...c.childNodes);let f=await e.get("error");if(!Re(f)){a=await f.get("message"),h=await a.toString();let u=await f.get("call"),d=await f.get("gradethis_call"),m=document.createElement("p"),p=document.createElement("pre");p.appendChild(document.createTextNode(`Error: ${h}`)),m.appendChild(p),n.appendChild(m);let g=document.createElement("details");p=document.createElement("pre"),p.appendChild(document.createTextNode(await u.toString())),g.appendChild(p),p=document.createElement("pre"),p.appendChild(document.createTextNode(await d.toString())),g.appendChild(p),n.appendChild(g)}return n}};var ma=class extends Mn{constructor(e){super(e),this.pyodide=this.evaluator.pyodide}async gradeExercise(){let e=this.context.code;if(!e)return null;let t=await this.blankCheck(e);if(t)return await this.feedbackAsHtmlAlert(t);if(t=await this.parseCheck(e),t)return await this.feedbackAsHtmlAlert(t);let n=this.context.indicator;this.context.indicator||(n=new Ke),n.running();try{let r=await this.evaluateExercise();if(!r.value)return null;let s=await this.evaluator.asHtml(r,this.options),o=await s.value.result.value,a,l;return await o.type==="dict"&&(a=await o.get("message"),l=await o.get("correct")),a&&l!==void 0?await this.feedbackAsHtmlAlert(o):s}finally{n.finished(),this.context.indicator||n.destroy()}}async parseCheck(e,t){try{return await this.pyodide.runPythonAsync(` + from ast import parse + parse(user_code) + `,{locals:await this.pyodide.toPy({user_code:e})}),null}catch{return await this.pyodide.toPy({message:` + It looks like this might not be valid Python code. + Python cannot determine how to turn your text into a complete command. + Your code may be indented incorrectly, or you may have forgotten to + fill in a blank, to remove an underscore, to include a comma between + arguments, or to close an opening ", ', + ( or { with a matching ", + ', ) or }. + `,correct:!1,location:"append",type:"error"})}}async blankCheck(e){return e.match(/_{6}_*/g)?await this.pyodide.toPy({message:"Please replace ______ with valid code.",correct:!1,location:"append",type:"info"}):null}async evaluateSolution(){let e=this.evaluator.options.exercise,t=document.querySelectorAll(`.exercise-solution[data-exercise="${e}"] > code.solution-code`);if(t.length>0){t.length>1&&console.warn(`Multiple solutions found for exercise "${e}", using first solution.`),await this.envManager.create("solution","prep");let n=await this.envManager.get("solution"),r=t[0].textContent,s=await this.pyodide.runPythonAsync(r,{globals:n});return{envir:n,code:r,result:s}}return null}async evaluateExercise(){await this.envManager.create("grading","result");let e=await this.envManager.get("result"),t=this.evaluator.container.value.evaluate_result,n=await this.envManager.get("prep"),r=this.evaluator.container.value.result.value,s={user_code:this.context.code,stage:"check",engine:"python",label:this.context.options.exercise,check_code:this.getCheckingAlgorithm(),envir_result:e,evaluate_result:t,envir_prep:n,last_value:r,result:r,solution_code:null,solution_code_all:null,envir_solution:null,solution:null},o=await this.evaluateSolution();o&&(s.solution_code=o.code,s.solution_code_all=[o.code],s.envir_solution=o.envir,s.solution=o.result);let a=await this.pyodide.toPy(s);await this.envManager.bind("_checker_env",a,"grading"),a.destroy();let l={...this.options};return l.error=!1,l.output=!0,await this.evaluator.evaluate(` + import pyodide + feedback = None + if (_checker_env["check_code"]): + try: + feedback = pyodide.code.eval_code( + _checker_env["check_code"], + globals = globals(), + locals = _checker_env + ) + except Exception as error: + feedback = { + 'correct': False, + 'message': 'Error while checking \`{}\`: "{}"'.format(_checker_env["label"], error), + 'type': 'error' + } + feedback + `,"grading",l)}async feedbackAsHtmlAlert(e){let t=document.createElement("div"),n=await e.get("type"),r=await e.get("correct"),s=await e.get("message");switch(t.classList.add("alert"),t.classList.add("exercise-grade"),n){case"success":t.classList.add("alert-success");break;case"info":t.classList.add("alert-info");break;case"warning":t.classList.add("alert-warning");break;case"error":case"danger":t.classList.add("alert-danger");break;default:t.classList.add(r?"alert-success":"alert-danger")}let o=document.createElement("span");return o.className="exercise-feedback",o.innerHTML=s,t.appendChild(o),t}};function eS(i){return i&&i[Symbol.toStringTag]=="PyProxy"}function uO(i){return i&&!!i[il]}function tS(i){return i&&typeof i=="object"&&"_comlinkProxy"in i&&"ptr"in i}function iS(i){return i&&i[Symbol.toStringTag]=="Map"}function sf(i){if(uO(i))return!0;if(i==null||i instanceof ArrayBuffer||ArrayBuffer.isView(i))return!1;if(i instanceof Array)return i.some(e=>sf(e));if(typeof i=="object")return Object.entries(i).some(([e,t])=>sf(t))}var dO={},pO={canHandle:eS,serialize(i){let e=self.pyodide._module.PyProxy_getPtr(i);dO[e]=i;let{port1:t,port2:n}=new MessageChannel;return ks(i,t),[[n,e],[n]]},deserialize([i,e]){i.start();let t=Wn(i);return new Proxy(t,{get:(r,s)=>s==="_ptr"?e:r[s]})}},mO={canHandle:sf,serialize(i){return[Ur(i,uO,e=>({_comlinkProxy:!0,ptr:e._ptr})),[]]},deserialize(i){return Ur(i,tS,e=>dO[e.ptr])}},gO={canHandle:ef,serialize(i){if(i.width==0&&i.height==0){let e=new OffscreenCanvas(1,1);e.getContext("2d"),i=e.transferToImageBitmap()}return[i,[i]]},deserialize(i){return i}},OO={canHandle:iS,serialize(i){return[Object.fromEntries(i.entries()),[]]},deserialize(i){return i}};async function oS(i,e){return await i.evalRVoid('options("webr.render.df" = x)',{env:{x:e.render_df||"default"}}),await i.evalRVoid(atob(yO()))}async function aS(i){await i.runPythonAsync(atob(bO()));let e=atob(wO());await i.FS.mkdir("/pyodide"),await i.FS.writeFile("/pyodide/matplotlib_display.py",e)}async function lS(i){let e=new URL("./pyodide-worker.js",import.meta.url),t=new Worker(e,{type:"module"}),r=await Wn(t).init(i);return gi.set("PyProxy",pO),gi.set("Comlink",mO),gi.set("ImageBitmap",gO),gi.set("Map",OO),r}window._exercise_ojs_runtime={PyodideExerciseEditor:ca,PyodideEvaluator:da,PyodideEnvironment:An,PyodideGrader:ma,WebR:Ka,WebRExerciseEditor:ha,WebREvaluator:ua,WebRGrader:pa,WebREnvironment:En,highlightR:Tn,highlightPython:Pn,interpolate:Jc,setupR:oS,setupPython:aS,startPyodideWorker:lS,b64Encode:oO,b64Decode:aO,collapsePath:hO};export{An as PyodideEnvironment,da as PyodideEvaluator,ca as PyodideExerciseEditor,ma as PyodideGrader,Ka as WebR,En as WebREnvironment,ua as WebREvaluator,ha as WebRExerciseEditor,pa as WebRGrader,aO as b64Decode,oO as b64Encode,hO as collapsePath,Pn as highlightPython,Tn as highlightR,Jc as interpolate,aS as setupPython,oS as setupR,lS as startPyodideWorker}; +/*! Bundled license information: + +comlink/dist/esm/comlink.mjs: + (** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + *) +*/ diff --git a/_extensions/r-wasm/live/resources/pyodide-worker.js b/_extensions/r-wasm/live/resources/pyodide-worker.js new file mode 100644 index 0000000..e5ec99b --- /dev/null +++ b/_extensions/r-wasm/live/resources/pyodide-worker.js @@ -0,0 +1,18 @@ +var je=Object.create;var U=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var x=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var qe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ye=(e,t)=>{for(var r in t)U(e,r,{get:t[r],enumerable:!0})},Ge=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of ze(t))!Ve.call(e,a)&&a!==r&&U(e,a,{get:()=>t[a],enumerable:!(o=Be(t,a))||o.enumerable});return e};var Je=(e,t,r)=>(r=e!=null?je(We(e)):{},Ge(t||!e||!e.__esModule?U(r,"default",{value:e,enumerable:!0}):r,e));var ae=qe(()=>{});var M={};Ye(M,{createEndpoint:()=>R,expose:()=>k,finalizer:()=>T,proxy:()=>I,proxyMarker:()=>B,releaseProxy:()=>ee,transfer:()=>oe,transferHandlers:()=>v,windowEndpoint:()=>nt,wrap:()=>A});var B=Symbol("Comlink.proxy"),R=Symbol("Comlink.endpoint"),ee=Symbol("Comlink.releaseProxy"),T=Symbol("Comlink.finalizer"),C=Symbol("Comlink.thrown"),te=e=>typeof e=="object"&&e!==null||typeof e=="function",Xe={canHandle:e=>te(e)&&e[B],serialize(e){let{port1:t,port2:r}=new MessageChannel;return k(e,t),[r,[r]]},deserialize(e){return e.start(),A(e)}},Ke={canHandle:e=>te(e)&&C in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},v=new Map([["proxy",Xe],["throw",Ke]]);function Qe(e,t){for(let r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function k(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(a){if(!a||!a.data)return;if(!Qe(r,a.origin)){console.warn(`Invalid origin '${a.origin}' for comlink proxy`);return}let{id:i,type:n,path:l}=Object.assign({path:[]},a.data),s=(a.data.argumentList||[]).map(E),u;try{let c=l.slice(0,-1).reduce((p,y)=>p[y],e),f=l.reduce((p,y)=>p[y],e);switch(n){case"GET":u=f;break;case"SET":c[l.slice(-1)[0]]=E(a.data.value),u=!0;break;case"APPLY":u=f.apply(c,s);break;case"CONSTRUCT":{let p=new f(...s);u=I(p)}break;case"ENDPOINT":{let{port1:p,port2:y}=new MessageChannel;k(e,y),u=oe(p,[p])}break;case"RELEASE":u=void 0;break;default:return}}catch(c){u={value:c,[C]:0}}Promise.resolve(u).catch(c=>({value:c,[C]:0})).then(c=>{let[f,p]=N(c);t.postMessage(Object.assign(Object.assign({},f),{id:i}),p),n==="RELEASE"&&(t.removeEventListener("message",o),re(t),T in e&&typeof e[T]=="function"&&e[T]())}).catch(c=>{let[f,p]=N({value:new TypeError("Unserializable return value"),[C]:0});t.postMessage(Object.assign(Object.assign({},f),{id:i}),p)})}),t.start&&t.start()}function Ze(e){return e.constructor.name==="MessagePort"}function re(e){Ze(e)&&e.close()}function A(e,t){return j(e,[],t)}function F(e){if(e)throw new Error("Proxy has been released and is not useable")}function ne(e){return P(e,{type:"RELEASE"}).then(()=>{re(e)})}var L=new WeakMap,_="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(L.get(e)||0)-1;L.set(e,t),t===0&&ne(e)});function et(e,t){let r=(L.get(t)||0)+1;L.set(t,r),_&&_.register(e,t,e)}function tt(e){_&&_.unregister(e)}function j(e,t=[],r=function(){}){let o=!1,a=new Proxy(r,{get(i,n){if(F(o),n===ee)return()=>{tt(a),ne(e),o=!0};if(n==="then"){if(t.length===0)return{then:()=>a};let l=P(e,{type:"GET",path:t.map(s=>s.toString())}).then(E);return l.then.bind(l)}return j(e,[...t,n])},set(i,n,l){F(o);let[s,u]=N(l);return P(e,{type:"SET",path:[...t,n].map(c=>c.toString()),value:s},u).then(E)},apply(i,n,l){F(o);let s=t[t.length-1];if(s===R)return P(e,{type:"ENDPOINT"}).then(E);if(s==="bind")return j(e,t.slice(0,-1));let[u,c]=Z(l);return P(e,{type:"APPLY",path:t.map(f=>f.toString()),argumentList:u},c).then(E)},construct(i,n){F(o);let[l,s]=Z(n);return P(e,{type:"CONSTRUCT",path:t.map(u=>u.toString()),argumentList:l},s).then(E)}});return et(a,e),a}function rt(e){return Array.prototype.concat.apply([],e)}function Z(e){let t=e.map(N);return[t.map(r=>r[0]),rt(t.map(r=>r[1]))]}var ie=new WeakMap;function oe(e,t){return ie.set(e,t),e}function I(e){return Object.assign(e,{[B]:!0})}function nt(e,t=globalThis,r="*"){return{postMessage:(o,a)=>e.postMessage(o,r,a),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function N(e){for(let[t,r]of v)if(r.canHandle(e)){let[o,a]=r.serialize(e);return[{type:"HANDLER",name:t,value:o},a]}return[{type:"RAW",value:e},ie.get(e)||[]]}function E(e){switch(e.type){case"HANDLER":return v.get(e.name).deserialize(e.value);case"RAW":return e.value}}function P(e,t,r){return new Promise(o=>{let a=it();e.addEventListener("message",function i(n){!n.data||!n.data.id||n.data.id!==a||(e.removeEventListener("message",i),o(n.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:a},t),r)})}function it(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var ot=Object.create,V=Object.defineProperty,at=Object.getOwnPropertyDescriptor,st=Object.getOwnPropertyNames,ct=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty,d=(e,t)=>V(e,"name",{value:t,configurable:!0}),le=(e=>typeof x<"u"?x:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof x<"u"?x:t)[r]}):e)(function(e){if(typeof x<"u")return x.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),ue=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ut=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of st(t))!lt.call(e,a)&&a!==r&&V(e,a,{get:()=>t[a],enumerable:!(o=at(t,a))||o.enumerable});return e},ft=(e,t,r)=>(r=e!=null?ot(ct(e)):{},ut(t||!e||!e.__esModule?V(r,"default",{value:e,enumerable:!0}):r,e)),pt=ue((e,t)=>{(function(r,o){"use strict";typeof define=="function"&&define.amd?define("stackframe",[],o):typeof e=="object"?t.exports=o():r.StackFrame=o()})(e,function(){"use strict";function r(m){return!isNaN(parseFloat(m))&&isFinite(m)}d(r,"_isNumber");function o(m){return m.charAt(0).toUpperCase()+m.substring(1)}d(o,"_capitalize");function a(m){return function(){return this[m]}}d(a,"_getter");var i=["isConstructor","isEval","isNative","isToplevel"],n=["columnNumber","lineNumber"],l=["fileName","functionName","source"],s=["args"],u=["evalOrigin"],c=i.concat(n,l,s,u);function f(m){if(m)for(var g=0;g{(function(r,o){"use strict";typeof define=="function"&&define.amd?define("error-stack-parser",["stackframe"],o):typeof e=="object"?t.exports=o(pt()):r.ErrorStackParser=o(r.StackFrame)})(e,d(function(r){"use strict";var o=/(^|@)\S+:\d+/,a=/^\s*at .*(\S+:\d+|\(native\))/m,i=/^(eval@)?(\[native code])?$/;return{parse:d(function(n){if(typeof n.stacktrace<"u"||typeof n["opera#sourceloc"]<"u")return this.parseOpera(n);if(n.stack&&n.stack.match(a))return this.parseV8OrIE(n);if(n.stack)return this.parseFFOrSafari(n);throw new Error("Cannot parse given Error object")},"ErrorStackParser$$parse"),extractLocation:d(function(n){if(n.indexOf(":")===-1)return[n];var l=/(.+?)(?::(\d+))?(?::(\d+))?$/,s=l.exec(n.replace(/[()]/g,""));return[s[1],s[2]||void 0,s[3]||void 0]},"ErrorStackParser$$extractLocation"),parseV8OrIE:d(function(n){var l=n.stack.split(` +`).filter(function(s){return!!s.match(a)},this);return l.map(function(s){s.indexOf("(eval ")>-1&&(s=s.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var u=s.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),c=u.match(/ (\(.+\)$)/);u=c?u.replace(c[0],""):u;var f=this.extractLocation(c?c[1]:u),p=c&&u||void 0,y=["eval",""].indexOf(f[0])>-1?void 0:f[0];return new r({functionName:p,fileName:y,lineNumber:f[1],columnNumber:f[2],source:s})},this)},"ErrorStackParser$$parseV8OrIE"),parseFFOrSafari:d(function(n){var l=n.stack.split(` +`).filter(function(s){return!s.match(i)},this);return l.map(function(s){if(s.indexOf(" > eval")>-1&&(s=s.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),s.indexOf("@")===-1&&s.indexOf(":")===-1)return new r({functionName:s});var u=/((.*".+"[^@]*)?[^@]*)(?:@)/,c=s.match(u),f=c&&c[1]?c[1]:void 0,p=this.extractLocation(s.replace(u,""));return new r({functionName:f,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:s})},this)},"ErrorStackParser$$parseFFOrSafari"),parseOpera:d(function(n){return!n.stacktrace||n.message.indexOf(` +`)>-1&&n.message.split(` +`).length>n.stacktrace.split(` +`).length?this.parseOpera9(n):n.stack?this.parseOpera11(n):this.parseOpera10(n)},"ErrorStackParser$$parseOpera"),parseOpera9:d(function(n){for(var l=/Line (\d+).*script (?:in )?(\S+)/i,s=n.message.split(` +`),u=[],c=2,f=s.length;c/,"$2").replace(/\([^)]*\)/g,"")||void 0,y;f.match(/\(([^)]*)\)/)&&(y=f.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var h=y===void 0||y==="[arguments not available]"?void 0:y.split(",");return new r({functionName:p,args:h,fileName:c[0],lineNumber:c[1],columnNumber:c[2],source:s})},this)},"ErrorStackParser$$parseOpera11")}},"ErrorStackParser"))}),dt=ft(mt()),w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&typeof process.browser>"u",fe=w&&typeof module<"u"&&typeof module.exports<"u"&&typeof le<"u"&&typeof __dirname<"u",yt=w&&!fe,gt=typeof Deno<"u",pe=!w&&!gt,ht=pe&&typeof window=="object"&&typeof document=="object"&&typeof document.createElement=="function"&&typeof sessionStorage=="object"&&typeof importScripts!="function",wt=pe&&typeof importScripts=="function"&&typeof self=="object",Tt=typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Chrome")==-1&&navigator.userAgent.indexOf("Safari")>-1,me,z,de,se,q;async function Y(){if(!w||(me=(await import("node:url")).default,se=await import("node:fs"),q=await import("node:fs/promises"),de=(await import("node:vm")).default,z=await import("node:path"),G=z.sep,typeof le<"u"))return;let e=se,t=await import("node:crypto"),r=await Promise.resolve().then(()=>Je(ae(),1)),o=await import("node:child_process"),a={fs:e,crypto:t,ws:r,child_process:o};globalThis.require=function(i){return a[i]}}d(Y,"initNodeModules");function ye(e,t){return z.resolve(t||".",e)}d(ye,"node_resolvePath");function ge(e,t){return t===void 0&&(t=location),new URL(e,t).toString()}d(ge,"browser_resolvePath");var W;w?W=ye:W=ge;var G;w||(G="/");function he(e,t){return e.startsWith("file://")&&(e=e.slice(7)),e.includes("://")?{response:fetch(e)}:{binary:q.readFile(e).then(r=>new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}}d(he,"node_getBinaryResponse");function we(e,t){let r=new URL(e,location);return{response:fetch(r,t?{integrity:t}:{})}}d(we,"browser_getBinaryResponse");var D;w?D=he:D=we;async function ve(e,t){let{response:r,binary:o}=D(e,t);if(o)return o;let a=await r;if(!a.ok)throw new Error(`Failed to load '${e}': request failed.`);return new Uint8Array(await a.arrayBuffer())}d(ve,"loadBinaryFile");var $;if(ht)$=d(async e=>await import(e),"loadScript");else if(wt)$=d(async e=>{try{globalThis.importScripts(e)}catch(t){if(t instanceof TypeError)await import(e);else throw t}},"loadScript");else if(w)$=be;else throw new Error("Cannot determine runtime environment");async function be(e){e.startsWith("file://")&&(e=e.slice(7)),e.includes("://")?de.runInThisContext(await(await fetch(e)).text()):await import(me.pathToFileURL(e).href)}d(be,"nodeLoadScript");async function xe(e){if(w){await Y();let t=await q.readFile(e,{encoding:"utf8"});return JSON.parse(t)}else return await(await fetch(e)).json()}d(xe,"loadLockFile");async function Ee(){if(fe)return __dirname;let e;try{throw new Error}catch(o){e=o}let t=dt.default.parse(e)[0].fileName;if(yt){let o=await import("node:path");return(await import("node:url")).fileURLToPath(o.dirname(t))}let r=t.lastIndexOf(G);if(r===-1)throw new Error("Could not extract indexURL path from pyodide module location");return t.slice(0,r)}d(Ee,"calculateDirname");function ke(e){let t=e.FS,r=e.FS.filesystems.MEMFS,o=e.PATH,a={DIR_MODE:16895,FILE_MODE:33279,mount:function(i){if(!i.opts.fileSystemHandle)throw new Error("opts.fileSystemHandle is required");return r.mount.apply(null,arguments)},syncfs:async(i,n,l)=>{try{let s=a.getLocalSet(i),u=await a.getRemoteSet(i),c=n?u:s,f=n?s:u;await a.reconcile(i,c,f),l(null)}catch(s){l(s)}},getLocalSet:i=>{let n=Object.create(null);function l(c){return c!=="."&&c!==".."}d(l,"isRealDir");function s(c){return f=>o.join2(c,f)}d(s,"toAbsolute");let u=t.readdir(i.mountpoint).filter(l).map(s(i.mountpoint));for(;u.length;){let c=u.pop(),f=t.stat(c);t.isDir(f.mode)&&u.push.apply(u,t.readdir(c).filter(l).map(s(c))),n[c]={timestamp:f.mtime,mode:f.mode}}return{type:"local",entries:n}},getRemoteSet:async i=>{let n=Object.create(null),l=await vt(i.opts.fileSystemHandle);for(let[s,u]of l)s!=="."&&(n[o.join2(i.mountpoint,s)]={timestamp:u.kind==="file"?(await u.getFile()).lastModifiedDate:new Date,mode:u.kind==="file"?a.FILE_MODE:a.DIR_MODE});return{type:"remote",entries:n,handles:l}},loadLocalEntry:i=>{let n=t.lookupPath(i).node,l=t.stat(i);if(t.isDir(l.mode))return{timestamp:l.mtime,mode:l.mode};if(t.isFile(l.mode))return n.contents=r.getFileDataAsTypedArray(n),{timestamp:l.mtime,mode:l.mode,contents:n.contents};throw new Error("node type not supported")},storeLocalEntry:(i,n)=>{if(t.isDir(n.mode))t.mkdirTree(i,n.mode);else if(t.isFile(n.mode))t.writeFile(i,n.contents,{canOwn:!0});else throw new Error("node type not supported");t.chmod(i,n.mode),t.utime(i,n.timestamp,n.timestamp)},removeLocalEntry:i=>{var n=t.stat(i);t.isDir(n.mode)?t.rmdir(i):t.isFile(n.mode)&&t.unlink(i)},loadRemoteEntry:async i=>{if(i.kind==="file"){let n=await i.getFile();return{contents:new Uint8Array(await n.arrayBuffer()),mode:a.FILE_MODE,timestamp:n.lastModifiedDate}}else{if(i.kind==="directory")return{mode:a.DIR_MODE,timestamp:new Date};throw new Error("unknown kind: "+i.kind)}},storeRemoteEntry:async(i,n,l)=>{let s=i.get(o.dirname(n)),u=t.isFile(l.mode)?await s.getFileHandle(o.basename(n),{create:!0}):await s.getDirectoryHandle(o.basename(n),{create:!0});if(u.kind==="file"){let c=await u.createWritable();await c.write(l.contents),await c.close()}i.set(n,u)},removeRemoteEntry:async(i,n)=>{await i.get(o.dirname(n)).removeEntry(o.basename(n)),i.delete(n)},reconcile:async(i,n,l)=>{let s=0,u=[];Object.keys(n.entries).forEach(function(p){let y=n.entries[p],h=l.entries[p];(!h||t.isFile(y.mode)&&y.timestamp.getTime()>h.timestamp.getTime())&&(u.push(p),s++)}),u.sort();let c=[];if(Object.keys(l.entries).forEach(function(p){n.entries[p]||(c.push(p),s++)}),c.sort().reverse(),!s)return;let f=n.type==="remote"?n.handles:l.handles;for(let p of u){let y=o.normalize(p.replace(i.mountpoint,"/")).substring(1);if(l.type==="local"){let h=f.get(y),m=await a.loadRemoteEntry(h);a.storeLocalEntry(p,m)}else{let h=a.loadLocalEntry(p);await a.storeRemoteEntry(f,y,h)}}for(let p of c)if(l.type==="local")a.removeLocalEntry(p);else{let y=o.normalize(p.replace(i.mountpoint,"/")).substring(1);await a.removeRemoteEntry(f,y)}}};e.FS.filesystems.NATIVEFS_ASYNC=a}d(ke,"initializeNativeFS");var vt=d(async e=>{let t=[];async function r(a){for await(let i of a.values())t.push(i),i.kind==="directory"&&await r(i)}d(r,"collect"),await r(e);let o=new Map;o.set(".",e);for(let a of t){let i=(await e.resolve(a)).join("/");o.set(i,a)}return o},"getFsHandles");function Pe(e){let t={noImageDecoding:!0,noAudioDecoding:!0,noWasmDecoding:!1,preRun:Ce(e),quit(r,o){throw t.exited={status:r,toThrow:o},o},print:e.stdout,printErr:e.stderr,arguments:e.args,API:{config:e},locateFile:r=>e.indexURL+r,instantiateWasm:Le(e.indexURL)};return t}d(Pe,"createSettings");function Se(e){return function(t){let r="/";try{t.FS.mkdirTree(e)}catch(o){console.error(`Error occurred while making a home directory '${e}':`),console.error(o),console.error(`Using '${r}' for a home directory instead`),e=r}t.FS.chdir(e)}}d(Se,"createHomeDirectory");function Oe(e){return function(t){Object.assign(t.ENV,e)}}d(Oe,"setEnvironment");function Fe(e){return t=>{for(let r of e)t.FS.mkdirTree(r),t.FS.mount(t.FS.filesystems.NODEFS,{root:r},r)}}d(Fe,"mountLocalDirectories");function Te(e){let t=ve(e);return r=>{let o=r._py_version_major(),a=r._py_version_minor();r.FS.mkdirTree("/lib"),r.FS.mkdirTree(`/lib/python${o}.${a}/site-packages`),r.addRunDependency("install-stdlib"),t.then(i=>{r.FS.writeFile(`/lib/python${o}${a}.zip`,i)}).catch(i=>{console.error("Error occurred while installing the standard library:"),console.error(i)}).finally(()=>{r.removeRunDependency("install-stdlib")})}}d(Te,"installStdlib");function Ce(e){let t;return e.stdLibURL!=null?t=e.stdLibURL:t=e.indexURL+"python_stdlib.zip",[Te(t),Se(e.env.HOME),Oe(e.env),Fe(e._node_mounts),ke]}d(Ce,"getFileSystemInitializationFuncs");function Le(e){let{binary:t,response:r}=D(e+"pyodide.asm.wasm");return function(o,a){return async function(){try{let i;r?i=await WebAssembly.instantiateStreaming(r,o):i=await WebAssembly.instantiate(await t,o);let{instance:n,module:l}=i;typeof WasmOffsetConverter<"u"&&(wasmOffsetConverter=new WasmOffsetConverter(wasmBinary,l)),a(n,l)}catch(i){console.warn("wasm instantiation failed!"),console.warn(i)}}(),{}}}d(Le,"getInstantiateWasmFunc");var ce="0.26.1";async function J(e={}){await Y();let t=e.indexURL||await Ee();t=W(t),t.endsWith("/")||(t+="/"),e.indexURL=t;let r={fullStdLib:!1,jsglobals:globalThis,stdin:globalThis.prompt?globalThis.prompt:void 0,lockFileURL:t+"pyodide-lock.json",args:[],_node_mounts:[],env:{},packageCacheDir:t,packages:[],enableRunUntilComplete:!1},o=Object.assign(r,e);o.env.HOME||(o.env.HOME="/home/pyodide");let a=Pe(o),i=a.API;if(i.lockFilePromise=xe(o.lockFileURL),typeof _createPyodideModule!="function"){let c=`${o.indexURL}pyodide.asm.js`;await $(c)}let n;if(e._loadSnapshot){let c=await e._loadSnapshot;ArrayBuffer.isView(c)?n=c:n=new Uint8Array(c),a.noInitialRun=!0,a.INITIAL_MEMORY=n.length}let l=await _createPyodideModule(a);if(a.exited)throw a.exited.toThrow;if(e.pyproxyToStringRepr&&i.setPyProxyToStringMethod(!0),i.version!==ce)throw new Error(`Pyodide version does not match: '${ce}' <==> '${i.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`);l.locateFile=c=>{throw new Error("Didn't expect to load any more file_packager files!")};let s;n&&(s=i.restoreSnapshot(n));let u=i.finalizeBootstrap(s);return i.sys.path.insert(0,i.config.env.HOME),u.version.includes("dev")||i.setCdnUrl(`https://cdn.jsdelivr.net/pyodide/v${u.version}/full/`),i._pyodide.set_excepthook(),await i.packageIndexReady,i.initializeStreams(o.stdin,o.stdout,o.stderr),u}d(J,"loadPyodide");function X(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap}function S(e,t,r,...o){return e==null||X(e)||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e:t(e)?r(e,...o):Array.isArray(e)?e.map(a=>S(a,t,r,...o)):typeof e=="object"?Object.fromEntries(Object.entries(e).map(([a,i])=>[a,S(i,t,r,...o)])):e}function bt(e){return e&&e[Symbol.toStringTag]=="PyProxy"}function _e(e){return e&&!!e[R]}function xt(e){return e&&typeof e=="object"&&"_comlinkProxy"in e&&"ptr"in e}function Et(e){return e&&e[Symbol.toStringTag]=="Map"}function K(e){if(_e(e))return!0;if(e==null||e instanceof ArrayBuffer||ArrayBuffer.isView(e))return!1;if(e instanceof Array)return e.some(t=>K(t));if(typeof e=="object")return Object.entries(e).some(([t,r])=>K(r))}var Ne={},Re={canHandle:bt,serialize(e){let t=self.pyodide._module.PyProxy_getPtr(e);Ne[t]=e;let{port1:r,port2:o}=new MessageChannel;return k(e,r),[[o,t],[o]]},deserialize([e,t]){e.start();let r=A(e);return new Proxy(r,{get:(a,i)=>i==="_ptr"?t:a[i]})}},Ae={canHandle:K,serialize(e){return[S(e,_e,t=>({_comlinkProxy:!0,ptr:t._ptr})),[]]},deserialize(e){return S(e,xt,t=>Ne[t.ptr])}},Ie={canHandle:X,serialize(e){if(e.width==0&&e.height==0){let t=new OffscreenCanvas(1,1);t.getContext("2d"),e=t.transferToImageBitmap()}return[e,[e]]},deserialize(e){return e}},Me={canHandle:Et,serialize(e){return[Object.fromEntries(e.entries()),[]]},deserialize(e){return e}};var kt={mkdir(e){self.pyodide._FS.mkdir(e)},writeFile(e,t){self.pyodide._FS.writeFile(e,t)}};async function Pt(e){return self.pyodide=await J(e),self.pyodide.registerComlink(M),self.pyodide._FS=self.pyodide.FS,self.pyodide.FS=kt,v.set("PyProxy",Re),v.set("Comlink",Ae),v.set("ImageBitmap",Ie),v.set("Map",Me),I(self.pyodide)}k({init:Pt}); +/*! Bundled license information: + +comlink/dist/esm/comlink.mjs: + (** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + *) +*/ diff --git a/_extensions/r-wasm/live/resources/tinyyaml.lua b/_extensions/r-wasm/live/resources/tinyyaml.lua new file mode 100644 index 0000000..6dd0fd3 --- /dev/null +++ b/_extensions/r-wasm/live/resources/tinyyaml.lua @@ -0,0 +1,883 @@ +------------------------------------------------------------------------------- +-- tinyyaml - YAML subset parser +-- https://github.com/api7/lua-tinyyaml +-- +-- MIT License +-- +-- Copyright (c) 2017 peposso +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +------------------------------------------------------------------------------- + +local table = table +local string = string +local schar = string.char +local ssub, gsub = string.sub, string.gsub +local sfind, smatch = string.find, string.match +local tinsert, tconcat, tremove = table.insert, table.concat, table.remove +local setmetatable = setmetatable +local pairs = pairs +local rawget = rawget +local type = type +local tonumber = tonumber +local math = math +local getmetatable = getmetatable +local error = error +local end_symbol = "..." +local end_break_symbol = "...\n" + +local UNESCAPES = { + ['0'] = "\x00", z = "\x00", N = "\x85", + a = "\x07", b = "\x08", t = "\x09", + n = "\x0a", v = "\x0b", f = "\x0c", + r = "\x0d", e = "\x1b", ['\\'] = '\\', +}; + +------------------------------------------------------------------------------- +-- utils +local function select(list, pred) + local selected = {} + for i = 0, #list do + local v = list[i] + if v and pred(v, i) then + tinsert(selected, v) + end + end + return selected +end + +local function startswith(haystack, needle) + return ssub(haystack, 1, #needle) == needle +end + +local function ltrim(str) + return smatch(str, "^%s*(.-)$") +end + +local function rtrim(str) + return smatch(str, "^(.-)%s*$") +end + +local function trim(str) + return smatch(str, "^%s*(.-)%s*$") +end + +------------------------------------------------------------------------------- +-- Implementation. +-- +local class = {__meta={}} +function class.__meta.__call(cls, ...) + local self = setmetatable({}, cls) + if cls.__init then + cls.__init(self, ...) + end + return self +end + +function class.def(base, typ, cls) + base = base or class + local mt = {__metatable=base, __index=base} + for k, v in pairs(base.__meta) do mt[k] = v end + cls = setmetatable(cls or {}, mt) + cls.__index = cls + cls.__metatable = cls + cls.__type = typ + cls.__meta = mt + return cls +end + + +local types = { + null = class:def('null'), + map = class:def('map'), + omap = class:def('omap'), + pairs = class:def('pairs'), + set = class:def('set'), + seq = class:def('seq'), + timestamp = class:def('timestamp'), +} + +local Null = types.null +function Null.__tostring() return 'yaml.null' end +function Null.isnull(v) + if v == nil then return true end + if type(v) == 'table' and getmetatable(v) == Null then return true end + return false +end +local null = Null() + +function types.timestamp:__init(y, m, d, h, i, s, f, z) + self.year = tonumber(y) + self.month = tonumber(m) + self.day = tonumber(d) + self.hour = tonumber(h or 0) + self.minute = tonumber(i or 0) + self.second = tonumber(s or 0) + if type(f) == 'string' and sfind(f, '^%d+$') then + self.fraction = tonumber(f) * 10 ^ (3 - #f) + elseif f then + self.fraction = f + else + self.fraction = 0 + end + self.timezone = z +end + +function types.timestamp:__tostring() + return string.format( + '%04d-%02d-%02dT%02d:%02d:%02d.%03d%s', + self.year, self.month, self.day, + self.hour, self.minute, self.second, self.fraction, + self:gettz()) +end + +function types.timestamp:gettz() + if not self.timezone then + return '' + end + if self.timezone == 0 then + return 'Z' + end + local sign = self.timezone > 0 + local z = sign and self.timezone or -self.timezone + local zh = math.floor(z) + local zi = (z - zh) * 60 + return string.format( + '%s%02d:%02d', sign and '+' or '-', zh, zi) +end + + +local function countindent(line) + local _, j = sfind(line, '^%s+') + if not j then + return 0, line + end + return j, ssub(line, j+1) +end + +local Parser = { + timestamps=true,-- parse timestamps as objects instead of strings +} + +function Parser:parsestring(line, stopper) + stopper = stopper or '' + local q = ssub(line, 1, 1) + if q == ' ' or q == '\t' then + return self:parsestring(ssub(line, 2)) + end + if q == "'" then + local i = sfind(line, "'", 2, true) + if not i then + return nil, line + end + -- Unescape repeated single quotes. + while i < #line and ssub(line, i+1, i+1) == "'" do + i = sfind(line, "'", i + 2, true) + if not i then + return nil, line + end + end + return ssub(line, 2, i-1):gsub("''", "'"), ssub(line, i+1) + end + if q == '"' then + local i, buf = 2, '' + while i < #line do + local c = ssub(line, i, i) + if c == '\\' then + local n = ssub(line, i+1, i+1) + if UNESCAPES[n] ~= nil then + buf = buf..UNESCAPES[n] + elseif n == 'x' then + local h = ssub(i+2,i+3) + if sfind(h, '^[0-9a-fA-F]$') then + buf = buf..schar(tonumber(h, 16)) + i = i + 2 + else + buf = buf..'x' + end + else + buf = buf..n + end + i = i + 1 + elseif c == q then + break + else + buf = buf..c + end + i = i + 1 + end + return buf, ssub(line, i+1) + end + if q == '{' or q == '[' then -- flow style + return nil, line + end + if q == '|' or q == '>' then -- block + return nil, line + end + if q == '-' or q == ':' then + if ssub(line, 2, 2) == ' ' or ssub(line, 2, 2) == '\n' or #line == 1 then + return nil, line + end + end + + if line == "*" then + error("did not find expected alphabetic or numeric character") + end + + local buf = '' + while #line > 0 do + local c = ssub(line, 1, 1) + if sfind(stopper, c, 1, true) then + break + elseif c == ':' and (ssub(line, 2, 2) == ' ' or ssub(line, 2, 2) == '\n' or #line == 1) then + break + elseif c == '#' and (ssub(buf, #buf, #buf) == ' ') then + break + else + buf = buf..c + end + line = ssub(line, 2) + end + buf = rtrim(buf) + local val = tonumber(buf) or buf + return val, line +end + +local function isemptyline(line) + return line == '' or sfind(line, '^%s*$') or sfind(line, '^%s*#') +end + +local function equalsline(line, needle) + return startswith(line, needle) and isemptyline(ssub(line, #needle+1)) +end + +local function compactifyemptylines(lines) + -- Appends empty lines as "\n" to the end of the nearest preceding non-empty line + local compactified = {} + local lastline = {} + for i = 1, #lines do + local line = lines[i] + if isemptyline(line) then + if #compactified > 0 and i < #lines then + tinsert(lastline, "\n") + end + else + if #lastline > 0 then + tinsert(compactified, tconcat(lastline, "")) + end + lastline = {line} + end + end + if #lastline > 0 then + tinsert(compactified, tconcat(lastline, "")) + end + return compactified +end + +local function checkdupekey(map, key) + if rawget(map, key) ~= nil then + -- print("found a duplicate key '"..key.."' in line: "..line) + local suffix = 1 + while rawget(map, key..'_'..suffix) do + suffix = suffix + 1 + end + key = key ..'_'..suffix + end + return key +end + + +function Parser:parseflowstyle(line, lines) + local stack = {} + while true do + if #line == 0 then + if #lines == 0 then + break + else + line = tremove(lines, 1) + end + end + local c = ssub(line, 1, 1) + if c == '#' then + line = '' + elseif c == ' ' or c == '\t' or c == '\r' or c == '\n' then + line = ssub(line, 2) + elseif c == '{' or c == '[' then + tinsert(stack, {v={},t=c}) + line = ssub(line, 2) + elseif c == ':' then + local s = tremove(stack) + tinsert(stack, {v=s.v, t=':'}) + line = ssub(line, 2) + elseif c == ',' then + local value = tremove(stack) + if value.t == ':' or value.t == '{' or value.t == '[' then error() end + if stack[#stack].t == ':' then + -- map + local key = tremove(stack) + key.v = checkdupekey(stack[#stack].v, key.v) + stack[#stack].v[key.v] = value.v + elseif stack[#stack].t == '{' then + -- set + stack[#stack].v[value.v] = true + elseif stack[#stack].t == '[' then + -- seq + tinsert(stack[#stack].v, value.v) + end + line = ssub(line, 2) + elseif c == '}' then + if stack[#stack].t == '{' then + if #stack == 1 then break end + stack[#stack].t = '}' + line = ssub(line, 2) + else + line = ','..line + end + elseif c == ']' then + if stack[#stack].t == '[' then + if #stack == 1 then break end + stack[#stack].t = ']' + line = ssub(line, 2) + else + line = ','..line + end + else + local s, rest = self:parsestring(line, ',{}[]') + if not s then + error('invalid flowstyle line: '..line) + end + tinsert(stack, {v=s, t='s'}) + line = rest + end + end + return stack[1].v, line +end + +function Parser:parseblockstylestring(line, lines, indent) + if #lines == 0 then + error("failed to find multi-line scalar content") + end + local s = {} + local firstindent = -1 + local endline = -1 + for i = 1, #lines do + local ln = lines[i] + local idt = countindent(ln) + if idt <= indent then + break + end + if ln == '' then + tinsert(s, '') + else + if firstindent == -1 then + firstindent = idt + elseif idt < firstindent then + break + end + tinsert(s, ssub(ln, firstindent + 1)) + end + endline = i + end + + local striptrailing = true + local sep = '\n' + local newlineatend = true + if line == '|' then + striptrailing = true + sep = '\n' + newlineatend = true + elseif line == '|+' then + striptrailing = false + sep = '\n' + newlineatend = true + elseif line == '|-' then + striptrailing = true + sep = '\n' + newlineatend = false + elseif line == '>' then + striptrailing = true + sep = ' ' + newlineatend = true + elseif line == '>+' then + striptrailing = false + sep = ' ' + newlineatend = true + elseif line == '>-' then + striptrailing = true + sep = ' ' + newlineatend = false + else + error('invalid blockstyle string:'..line) + end + + if #s == 0 then + return "" + end + + local _, eonl = s[#s]:gsub('\n', '\n') + s[#s] = rtrim(s[#s]) + if striptrailing then + eonl = 0 + end + if newlineatend then + eonl = eonl + 1 + end + for i = endline, 1, -1 do + tremove(lines, i) + end + return tconcat(s, sep)..string.rep('\n', eonl) +end + +function Parser:parsetimestamp(line) + local _, p1, y, m, d = sfind(line, '^(%d%d%d%d)%-(%d%d)%-(%d%d)') + if not p1 then + return nil, line + end + if p1 == #line then + return types.timestamp(y, m, d), '' + end + local _, p2, h, i, s = sfind(line, '^[Tt ](%d+):(%d+):(%d+)', p1+1) + if not p2 then + return types.timestamp(y, m, d), ssub(line, p1+1) + end + if p2 == #line then + return types.timestamp(y, m, d, h, i, s), '' + end + local _, p3, f = sfind(line, '^%.(%d+)', p2+1) + if not p3 then + p3 = p2 + f = 0 + end + local zc = ssub(line, p3+1, p3+1) + local _, p4, zs, z = sfind(line, '^ ?([%+%-])(%d+)', p3+1) + if p4 then + z = tonumber(z) + local _, p5, zi = sfind(line, '^:(%d+)', p4+1) + if p5 then + z = z + tonumber(zi) / 60 + end + z = zs == '-' and -tonumber(z) or tonumber(z) + elseif zc == 'Z' then + p4 = p3 + 1 + z = 0 + else + p4 = p3 + z = false + end + return types.timestamp(y, m, d, h, i, s, f, z), ssub(line, p4+1) +end + +function Parser:parsescalar(line, lines, indent) + line = trim(line) + line = gsub(line, '^%s*#.*$', '') -- comment only -> '' + line = gsub(line, '^%s*', '') -- trim head spaces + + if line == '' or line == '~' then + return null + end + + if self.timestamps then + local ts, _ = self:parsetimestamp(line) + if ts then + return ts + end + end + + local s, _ = self:parsestring(line) + -- startswith quote ... string + -- not startswith quote ... maybe string + if s and (startswith(line, '"') or startswith(line, "'")) then + return s + end + + if startswith('!', line) then -- unexpected tagchar + error('unsupported line: '..line) + end + + if equalsline(line, '{}') then + return {} + end + if equalsline(line, '[]') then + return {} + end + + if startswith(line, '{') or startswith(line, '[') then + return self:parseflowstyle(line, lines) + end + + if startswith(line, '|') or startswith(line, '>') then + return self:parseblockstylestring(line, lines, indent) + end + + -- Regular unquoted string + line = gsub(line, '%s*#.*$', '') -- trim tail comment + local v = line + if v == 'null' or v == 'Null' or v == 'NULL'then + return null + elseif v == 'true' or v == 'True' or v == 'TRUE' then + return true + elseif v == 'false' or v == 'False' or v == 'FALSE' then + return false + elseif v == '.inf' or v == '.Inf' or v == '.INF' then + return math.huge + elseif v == '+.inf' or v == '+.Inf' or v == '+.INF' then + return math.huge + elseif v == '-.inf' or v == '-.Inf' or v == '-.INF' then + return -math.huge + elseif v == '.nan' or v == '.NaN' or v == '.NAN' then + return 0 / 0 + elseif sfind(v, '^[%+%-]?[0-9]+$') or sfind(v, '^[%+%-]?[0-9]+%.$')then + return tonumber(v) -- : int + elseif sfind(v, '^[%+%-]?[0-9]+%.[0-9]+$') then + return tonumber(v) + end + return s or v +end + +function Parser:parseseq(line, lines, indent) + local seq = setmetatable({}, types.seq) + if line ~= '' then + error() + end + while #lines > 0 do + -- Check for a new document + line = lines[1] + if startswith(line, '---') then + while #lines > 0 and not startswith(lines, '---') do + tremove(lines, 1) + end + return seq + end + + -- Check the indent level + local level = countindent(line) + if level < indent then + return seq + elseif level > indent then + error("found bad indenting in line: ".. line) + end + + local i, j = sfind(line, '%-%s+') + if not i then + i, j = sfind(line, '%-$') + if not i then + return seq + end + end + local rest = ssub(line, j+1) + + if sfind(rest, '^[^\'\"%s]*:%s*$') or sfind(rest, '^[^\'\"%s]*:%s+.') then + -- Inline nested hash + -- There are two patterns need to match as inline nested hash + -- first one should have no other characters except whitespace after `:` + -- and the second one should have characters besides whitespace after `:` + -- + -- value: + -- - foo: + -- bar: 1 + -- + -- and + -- + -- value: + -- - foo: bar + -- + -- And there is one pattern should not be matched, where there is no space after `:` + -- in below, `foo:bar` should be parsed into a single string + -- + -- value: + -- - foo:bar + local indent2 = j or 0 + lines[1] = string.rep(' ', indent2)..rest + tinsert(seq, self:parsemap('', lines, indent2)) + elseif sfind(rest, '^%-%s+') then + -- Inline nested seq + local indent2 = j or 0 + lines[1] = string.rep(' ', indent2)..rest + tinsert(seq, self:parseseq('', lines, indent2)) + elseif isemptyline(rest) then + tremove(lines, 1) + if #lines == 0 then + tinsert(seq, null) + return seq + end + if sfind(lines[1], '^%s*%-') then + local nextline = lines[1] + local indent2 = countindent(nextline) + if indent2 == indent then + -- Null seqay entry + tinsert(seq, null) + else + tinsert(seq, self:parseseq('', lines, indent2)) + end + else + -- - # comment + -- key: value + local nextline = lines[1] + local indent2 = countindent(nextline) + tinsert(seq, self:parsemap('', lines, indent2)) + end + elseif line == "*" then + error("did not find expected alphabetic or numeric character") + elseif rest then + -- Array entry with a value + local nextline = lines[1] + local indent2 = countindent(nextline) + tremove(lines, 1) + tinsert(seq, self:parsescalar(rest, lines, indent2)) + end + end + return seq +end + +function Parser:parseset(line, lines, indent) + if not isemptyline(line) then + error('not seq line: '..line) + end + local set = setmetatable({}, types.set) + while #lines > 0 do + -- Check for a new document + line = lines[1] + if startswith(line, '---') then + while #lines > 0 and not startswith(lines, '---') do + tremove(lines, 1) + end + return set + end + + -- Check the indent level + local level = countindent(line) + if level < indent then + return set + elseif level > indent then + error("found bad indenting in line: ".. line) + end + + local i, j = sfind(line, '%?%s+') + if not i then + i, j = sfind(line, '%?$') + if not i then + return set + end + end + local rest = ssub(line, j+1) + + if sfind(rest, '^[^\'\"%s]*:') then + -- Inline nested hash + local indent2 = j or 0 + lines[1] = string.rep(' ', indent2)..rest + set[self:parsemap('', lines, indent2)] = true + elseif sfind(rest, '^%s+$') then + tremove(lines, 1) + if #lines == 0 then + tinsert(set, null) + return set + end + if sfind(lines[1], '^%s*%?') then + local indent2 = countindent(lines[1]) + if indent2 == indent then + -- Null array entry + set[null] = true + else + set[self:parseseq('', lines, indent2)] = true + end + end + + elseif rest then + tremove(lines, 1) + set[self:parsescalar(rest, lines)] = true + else + error("failed to classify line: "..line) + end + end + return set +end + +function Parser:parsemap(line, lines, indent) + if not isemptyline(line) then + error('not map line: '..line) + end + local map = setmetatable({}, types.map) + while #lines > 0 do + -- Check for a new document + line = lines[1] + if line == end_symbol or line == end_break_symbol then + for i, _ in ipairs(lines) do + lines[i] = nil + end + return map + end + + if startswith(line, '---') then + while #lines > 0 and not startswith(lines, '---') do + tremove(lines, 1) + end + return map + end + + -- Check the indent level + local level, _ = countindent(line) + if level < indent then + return map + elseif level > indent then + error("found bad indenting in line: ".. line) + end + + -- Find the key + local key + local s, rest = self:parsestring(line) + + -- Quoted keys + if s and startswith(rest, ':') then + local sc = self:parsescalar(s, {}, 0) + if sc and type(sc) ~= 'string' then + key = sc + else + key = s + end + line = ssub(rest, 2) + else + error("failed to classify line: "..line) + end + + key = checkdupekey(map, key) + line = ltrim(line) + + if ssub(line, 1, 1) == '!' then + -- ignore type + local rh = ltrim(ssub(line, 3)) + local typename = smatch(rh, '^!?[^%s]+') + line = ltrim(ssub(rh, #typename+1)) + end + + if not isemptyline(line) then + tremove(lines, 1) + line = ltrim(line) + map[key] = self:parsescalar(line, lines, indent) + else + -- An indent + tremove(lines, 1) + if #lines == 0 then + map[key] = null + return map; + end + if sfind(lines[1], '^%s*%-') then + local indent2 = countindent(lines[1]) + map[key] = self:parseseq('', lines, indent2) + elseif sfind(lines[1], '^%s*%?') then + local indent2 = countindent(lines[1]) + map[key] = self:parseset('', lines, indent2) + else + local indent2 = countindent(lines[1]) + if indent >= indent2 then + -- Null hash entry + map[key] = null + else + map[key] = self:parsemap('', lines, indent2) + end + end + end + end + return map +end + + +-- : (list)->dict +function Parser:parsedocuments(lines) + lines = compactifyemptylines(lines) + + if sfind(lines[1], '^%%YAML') then tremove(lines, 1) end + + local root = {} + local in_document = false + while #lines > 0 do + local line = lines[1] + -- Do we have a document header? + local docright; + if sfind(line, '^%-%-%-') then + -- Handle scalar documents + docright = ssub(line, 4) + tremove(lines, 1) + in_document = true + end + if docright then + if (not sfind(docright, '^%s+$') and + not sfind(docright, '^%s+#')) then + tinsert(root, self:parsescalar(docright, lines)) + end + elseif #lines == 0 or startswith(line, '---') then + -- A naked document + tinsert(root, null) + while #lines > 0 and not sfind(lines[1], '---') do + tremove(lines, 1) + end + in_document = false + -- XXX The final '-+$' is to look for -- which ends up being an + -- error later. + elseif not in_document and #root > 0 then + -- only the first document can be explicit + error('parse error: '..line) + elseif sfind(line, '^%s*%-') then + -- An array at the root + tinsert(root, self:parseseq('', lines, 0)) + elseif sfind(line, '^%s*[^%s]') then + -- A hash at the root + local level = countindent(line) + tinsert(root, self:parsemap('', lines, level)) + else + -- Shouldn't get here. @lines have whitespace-only lines + -- stripped, and previous match is a line with any + -- non-whitespace. So this clause should only be reachable via + -- a perlbug where \s is not symmetric with \S + + -- uncoverable statement + error('parse error: '..line) + end + end + if #root > 1 and Null.isnull(root[1]) then + tremove(root, 1) + return root + end + return root +end + +--- Parse yaml string into table. +function Parser:parse(source) + local lines = {} + for line in string.gmatch(source .. '\n', '(.-)\r?\n') do + tinsert(lines, line) + end + + local docs = self:parsedocuments(lines) + if #docs == 1 then + return docs[1] + end + + return docs +end + +local function parse(source, options) + local options = options or {} + local parser = setmetatable (options, {__index=Parser}) + return parser:parse(source) +end + +return { + version = 0.1, + parse = parse, +} diff --git a/_extensions/r-wasm/live/templates/interpolate.ojs b/_extensions/r-wasm/live/templates/interpolate.ojs new file mode 100644 index 0000000..6987b7a --- /dev/null +++ b/_extensions/r-wasm/live/templates/interpolate.ojs @@ -0,0 +1,16 @@ +{ + const { interpolate } = window._exercise_ojs_runtime; + const block_id = "{{block_id}}"; + const language = "{{language}}"; + const def_map = {{def_map}}; + const elem = document.getElementById(`interpolate-${block_id}`); + + // Store original templated HTML for reference in future reactive updates + if (!elem.origHTML) elem.origHTML = elem.innerHTML; + + // Interpolate reactive OJS variables into established HTML element + elem.innerHTML = elem.origHTML; + Object.keys(def_map).forEach((def) => + interpolate(elem, "${" + def + "}", def_map[def], language) + ); +} diff --git a/_extensions/r-wasm/live/templates/pyodide-editor.ojs b/_extensions/r-wasm/live/templates/pyodide-editor.ojs new file mode 100644 index 0000000..cf6e36a --- /dev/null +++ b/_extensions/r-wasm/live/templates/pyodide-editor.ojs @@ -0,0 +1,16 @@ +viewof _pyodide_editor_{{block_id}} = { + const { PyodideExerciseEditor, b64Decode } = window._exercise_ojs_runtime; + + const scriptContent = document.querySelector(`script[type=\"pyodide-{{block_id}}-contents\"]`).textContent; + const block = JSON.parse(b64Decode(scriptContent)); + + const options = Object.assign({ id: `pyodide-{{block_id}}-contents` }, block.attr); + const editor = new PyodideExerciseEditor( + pyodideOjs.pyodidePromise, + block.code, + options + ); + + return editor.container; +} +_pyodide_value_{{block_id}} = pyodideOjs.process(_pyodide_editor_{{block_id}}, {{block_input}}); diff --git a/_extensions/r-wasm/live/templates/pyodide-evaluate.ojs b/_extensions/r-wasm/live/templates/pyodide-evaluate.ojs new file mode 100644 index 0000000..5575240 --- /dev/null +++ b/_extensions/r-wasm/live/templates/pyodide-evaluate.ojs @@ -0,0 +1,41 @@ +_pyodide_value_{{block_id}} = { + const { highlightPython, b64Decode} = window._exercise_ojs_runtime; + + const scriptContent = document.querySelector(`script[type=\"pyodide-{{block_id}}-contents\"]`).textContent; + const block = JSON.parse(b64Decode(scriptContent)); + + // Default evaluation configuration + const options = Object.assign({ + id: "pyodide-{{block_id}}-contents", + echo: true, + output: true + }, block.attr); + + // Evaluate the provided Python code + const result = pyodideOjs.process({code: block.code, options}, {{block_input}}); + + // Early yield while we wait for the first evaluation and render + if (options.output && !("{{block_id}}" in pyodideOjs.renderedOjs)) { + const container = document.createElement("div"); + const spinner = document.createElement("div"); + + if (options.echo) { + // Show output as highlighted source + const preElem = document.createElement("pre"); + container.className = "sourceCode"; + preElem.className = "sourceCode python"; + preElem.appendChild(highlightPython(block.code)); + spinner.className = "spinner-grow spinner-grow-sm m-2 position-absolute top-0 end-0"; + preElem.appendChild(spinner); + container.appendChild(preElem); + } else { + spinner.className = "spinner-border spinner-border-sm"; + container.appendChild(spinner); + } + + yield container; + } + + pyodideOjs.renderedOjs["{{block_id}}"] = true; + yield await result; +} diff --git a/_extensions/r-wasm/live/templates/pyodide-exercise.ojs b/_extensions/r-wasm/live/templates/pyodide-exercise.ojs new file mode 100644 index 0000000..9cd450b --- /dev/null +++ b/_extensions/r-wasm/live/templates/pyodide-exercise.ojs @@ -0,0 +1,30 @@ +viewof _pyodide_editor_{{block_id}} = { + const { PyodideExerciseEditor, b64Decode } = window._exercise_ojs_runtime; + + const scriptContent = document.querySelector(`script[type=\"pyodide-{{block_id}}-contents\"]`).textContent; + const block = JSON.parse(b64Decode(scriptContent)); + + // Default exercise configuration + const options = Object.assign( + { + id: "pyodide-{{block_id}}-contents", + envir: `exercise-env-${block.attr.exercise}`, + error: false, + caption: 'Exercise', + }, + block.attr + ); + + const editor = new PyodideExerciseEditor(pyodideOjs.pyodidePromise, block.code, options); + return editor.container; +} +viewof _pyodide_value_{{block_id}} = pyodideOjs.process(_pyodide_editor_{{block_id}}, {{block_input}}); +_pyodide_feedback_{{block_id}} = { + const { PyodideGrader } = window._exercise_ojs_runtime; + const emptyFeedback = document.createElement('div'); + + const grader = new PyodideGrader(_pyodide_value_{{block_id}}.evaluator); + const feedback = await grader.gradeExercise(); + if (!feedback) return emptyFeedback; + return feedback; +} diff --git a/_extensions/r-wasm/live/templates/pyodide-setup.ojs b/_extensions/r-wasm/live/templates/pyodide-setup.ojs new file mode 100644 index 0000000..a99dfb3 --- /dev/null +++ b/_extensions/r-wasm/live/templates/pyodide-setup.ojs @@ -0,0 +1,129 @@ +pyodideOjs = { + const { + PyodideEvaluator, + PyodideEnvironmentManager, + setupPython, + startPyodideWorker, + b64Decode, + collapsePath, + } = window._exercise_ojs_runtime; + + const statusContainer = document.getElementById("exercise-loading-status"); + const indicatorContainer = document.getElementById("exercise-loading-indicator"); + indicatorContainer.classList.remove("d-none"); + + let statusText = document.createElement("div") + statusText.classList = "exercise-loading-details"; + statusText = statusContainer.appendChild(statusText); + statusText.textContent = `Initialise`; + + // Hoist indicator out from final slide when running under reveal + const revealStatus = document.querySelector(".reveal .exercise-loading-indicator"); + if (revealStatus) { + revealStatus.remove(); + document.querySelector(".reveal > .slides").appendChild(revealStatus); + } + + // Make any reveal slides with live cells scrollable + document.querySelectorAll(".reveal .exercise-cell").forEach((el) => { + el.closest('section.slide').classList.add("scrollable"); + }) + + // Pyodide supplemental data and options + const dataContent = document.querySelector(`script[type=\"pyodide-data\"]`).textContent; + const data = JSON.parse(b64Decode(dataContent)); + + // Grab list of resources to be downloaded + const filesContent = document.querySelector(`script[type=\"vfs-file\"]`).textContent; + const files = JSON.parse(b64Decode(filesContent)); + + let pyodidePromise = (async () => { + statusText.textContent = `Downloading Pyodide`; + const pyodide = await startPyodideWorker(data.options); + + statusText.textContent = `Downloading package: micropip`; + await pyodide.loadPackage("micropip"); + const micropip = await pyodide.pyimport("micropip"); + await data.packages.pkgs.map((pkg) => () => { + statusText.textContent = `Downloading package: ${pkg}`; + return micropip.install(pkg); + }).reduce((cur, next) => cur.then(next), Promise.resolve()); + await micropip.destroy(); + + // Download and install resources + await files.map((file) => async () => { + const name = file.substring(file.lastIndexOf('/') + 1); + statusText.textContent = `Downloading resource: ${name}`; + const response = await fetch(file); + if (!response.ok) { + throw new Error(`Can't download \`${file}\`. Error ${response.status}: "${response.statusText}".`); + } + const data = await response.arrayBuffer(); + + // Store URLs in the cwd without any subdirectory structure + if (file.includes("://")) { + file = name; + } + + // Collapse higher directory structure + file = collapsePath(file); + + // Create directory tree, ignoring "directory exists" VFS errors + const parts = file.split('/').slice(0, -1); + let path = ''; + while (parts.length > 0) { + path += parts.shift() + '/'; + try { + await pyodide.FS.mkdir(path); + } catch (e) { + if (e.name !== "ErrnoError") throw e; + if (e.errno !== 20) { + const errorTextPtr = await pyodide._module._strerror(e.errno); + const errorText = await pyodide._module.UTF8ToString(errorTextPtr); + throw new Error(`Filesystem Error ${e.errno} "${errorText}".`); + } + } + } + + // Write this file to the VFS + try { + return await pyodide.FS.writeFile(file, new Uint8Array(data)); + } catch (e) { + if (e.name !== "ErrnoError") throw e; + const errorTextPtr = await pyodide._module._strerror(e.errno); + const errorText = await pyodide._module.UTF8ToString(errorTextPtr); + throw new Error(`Filesystem Error ${e.errno} "${errorText}".`); + } + }).reduce((cur, next) => cur.then(next), Promise.resolve()); + + statusText.textContent = `Pyodide environment setup`; + await setupPython(pyodide); + + statusText.remove(); + if (statusContainer.children.length == 0) { + statusContainer.parentNode.remove(); + } + return pyodide; + })().catch((err) => { + statusText.style.color = "var(--exercise-editor-hl-er, #AD0000)"; + statusText.textContent = err.message; + //indicatorContainer.querySelector(".spinner-grow").classList.add("d-none"); + throw err; + }); + + // Keep track of initial OJS block render + const renderedOjs = {}; + + const process = async (context, inputs) => { + const pyodide = await pyodidePromise; + const evaluator = new PyodideEvaluator(pyodide, context); + await evaluator.process(inputs); + return evaluator.container; + } + + return { + pyodidePromise, + renderedOjs, + process, + }; +} diff --git a/_extensions/r-wasm/live/templates/webr-editor.ojs b/_extensions/r-wasm/live/templates/webr-editor.ojs new file mode 100644 index 0000000..efa6e74 --- /dev/null +++ b/_extensions/r-wasm/live/templates/webr-editor.ojs @@ -0,0 +1,11 @@ +viewof _webr_editor_{{block_id}} = { + const { WebRExerciseEditor, b64Decode } = window._exercise_ojs_runtime; + const scriptContent = document.querySelector(`script[type=\"webr-{{block_id}}-contents\"]`).textContent; + const block = JSON.parse(b64Decode(scriptContent)); + + const options = Object.assign({ id: `webr-{{block_id}}-contents` }, block.attr); + const editor = new WebRExerciseEditor(webROjs.webRPromise, block.code, options); + + return editor.container; +} +_webr_value_{{block_id}} = webROjs.process(_webr_editor_{{block_id}}, {{block_input}}); diff --git a/_extensions/r-wasm/live/templates/webr-evaluate.ojs b/_extensions/r-wasm/live/templates/webr-evaluate.ojs new file mode 100644 index 0000000..614bcfe --- /dev/null +++ b/_extensions/r-wasm/live/templates/webr-evaluate.ojs @@ -0,0 +1,40 @@ +_webr_value_{{block_id}} = { + const { highlightR, b64Decode } = window._exercise_ojs_runtime; + const scriptContent = document.querySelector(`script[type=\"webr-{{block_id}}-contents\"]`).textContent; + const block = JSON.parse(b64Decode(scriptContent)); + + // Default evaluation configuration + const options = Object.assign({ + id: "webr-{{block_id}}-contents", + echo: true, + output: true + }, block.attr); + + // Evaluate the provided R code + const result = webROjs.process({code: block.code, options}, {{block_input}}); + + // Early yield while we wait for the first evaluation and render + if (options.output && !("{{block_id}}" in webROjs.renderedOjs)) { + const container = document.createElement("div"); + const spinner = document.createElement("div"); + + if (options.echo) { + // Show output as highlighted source + const preElem = document.createElement("pre"); + container.className = "sourceCode"; + preElem.className = "sourceCode r"; + preElem.appendChild(highlightR(block.code)); + spinner.className = "spinner-grow spinner-grow-sm m-2 position-absolute top-0 end-0"; + preElem.appendChild(spinner); + container.appendChild(preElem); + } else { + spinner.className = "spinner-border spinner-border-sm"; + container.appendChild(spinner); + } + + yield container; + } + + webROjs.renderedOjs["{{block_id}}"] = true; + yield await result; +} diff --git a/_extensions/r-wasm/live/templates/webr-exercise.ojs b/_extensions/r-wasm/live/templates/webr-exercise.ojs new file mode 100644 index 0000000..3884990 --- /dev/null +++ b/_extensions/r-wasm/live/templates/webr-exercise.ojs @@ -0,0 +1,29 @@ +viewof _webr_editor_{{block_id}} = { + const { WebRExerciseEditor, b64Decode } = window._exercise_ojs_runtime; + const scriptContent = document.querySelector(`script[type=\"webr-{{block_id}}-contents\"]`).textContent; + const block = JSON.parse(b64Decode(scriptContent)); + + // Default exercise configuration + const options = Object.assign( + { + id: "webr-{{block_id}}-contents", + envir: `exercise-env-${block.attr.exercise}`, + error: false, + caption: 'Exercise', + }, + block.attr + ); + + const editor = new WebRExerciseEditor(webROjs.webRPromise, block.code, options); + return editor.container; +} +viewof _webr_value_{{block_id}} = webROjs.process(_webr_editor_{{block_id}}, {{block_input}}); +_webr_feedback_{{block_id}} = { + const { WebRGrader } = window._exercise_ojs_runtime; + const emptyFeedback = document.createElement('div'); + + const grader = new WebRGrader(_webr_value_{{block_id}}.evaluator); + const feedback = await grader.gradeExercise(); + if (!feedback) return emptyFeedback; + return feedback; +} diff --git a/_extensions/r-wasm/live/templates/webr-setup.ojs b/_extensions/r-wasm/live/templates/webr-setup.ojs new file mode 100644 index 0000000..1d0224f --- /dev/null +++ b/_extensions/r-wasm/live/templates/webr-setup.ojs @@ -0,0 +1,123 @@ +webROjs = { + const { WebR } = window._exercise_ojs_runtime.WebR; + const { + WebREvaluator, + WebREnvironmentManager, + setupR, + b64Decode, + collapsePath + } = window._exercise_ojs_runtime; + + const statusContainer = document.getElementById("exercise-loading-status"); + const indicatorContainer = document.getElementById("exercise-loading-indicator"); + indicatorContainer.classList.remove("d-none"); + + let statusText = document.createElement("div") + statusText.classList = "exercise-loading-details"; + statusText = statusContainer.appendChild(statusText); + statusText.textContent = `Initialise`; + + // Hoist indicator out from final slide when running under reveal + const revealStatus = document.querySelector(".reveal .exercise-loading-indicator"); + if (revealStatus) { + revealStatus.remove(); + document.querySelector(".reveal > .slides").appendChild(revealStatus); + } + + // Make any reveal slides with live cells scrollable + document.querySelectorAll(".reveal .exercise-cell").forEach((el) => { + el.closest('section.slide').classList.add("scrollable"); + }) + + // webR supplemental data and options + const dataContent = document.querySelector(`script[type=\"webr-data\"]`).textContent; + const data = JSON.parse(b64Decode(dataContent)); + + // Grab list of resources to be downloaded + const filesContent = document.querySelector(`script[type=\"vfs-file\"]`).textContent; + const files = JSON.parse(b64Decode(filesContent)); + + // Initialise webR and setup for R code evaluation + let webRPromise = (async (webR) => { + statusText.textContent = `Downloading webR`; + await webR.init(); + + // Install provided list of packages + // Ensure webR default repo is included + data.packages.repos.push("https://repo.r-wasm.org") + await data.packages.pkgs.map((pkg) => () => { + statusText.textContent = `Downloading package: ${pkg}`; + return webR.evalRVoid(` + webr::install(pkg, repos = repos) + library(pkg, character.only = TRUE) + `, { env: { + pkg: pkg, + repos: data.packages.repos, + }}); + }).reduce((cur, next) => cur.then(next), Promise.resolve()); + + // Download and install resources + await files.map((file) => async () => { + const name = file.substring(file.lastIndexOf('/') + 1); + statusText.textContent = `Downloading resource: ${name}`; + const response = await fetch(file); + if (!response.ok) { + throw new Error(`Can't download \`${file}\`. Error ${response.status}: "${response.statusText}".`); + } + const data = await response.arrayBuffer(); + + // Store URLs in the cwd without any subdirectory structure + if (file.includes("://")) { + file = name; + } + + // Collapse higher directory structure + file = collapsePath(file); + + // Create directory tree, ignoring "directory exists" VFS errors + const parts = file.split('/').slice(0, -1); + let path = ''; + while (parts.length > 0) { + path += parts.shift() + '/'; + try { + await webR.FS.mkdir(path); + } catch (e) { + if (!e.message.includes("FS error")) { + throw e; + } + } + } + + // Write this file to the VFS + return await webR.FS.writeFile(file, new Uint8Array(data)); + }).reduce((cur, next) => cur.then(next), Promise.resolve()); + + statusText.textContent = `Installing webR shims`; + await webR.evalRVoid(`webr::shim_install()`); + + statusText.textContent = `WebR environment setup`; + await setupR(webR, data); + + statusText.remove(); + if (statusContainer.children.length == 0) { + statusContainer.parentNode.remove(); + } + return webR; + })(new WebR(data.options)); + + // Keep track of initial OJS block render + const renderedOjs = {}; + + const process = async (context, inputs) => { + const webR = await webRPromise; + const evaluator = new WebREvaluator(webR, context) + await evaluator.process(inputs); + return evaluator.container; + } + + return { + process, + webRPromise, + renderedOjs, + }; +} diff --git a/_extensions/r-wasm/live/templates/webr-widget.ojs b/_extensions/r-wasm/live/templates/webr-widget.ojs new file mode 100644 index 0000000..b41a3c2 --- /dev/null +++ b/_extensions/r-wasm/live/templates/webr-widget.ojs @@ -0,0 +1,10 @@ +{ + // Wait for output to be written to the DOM, then trigger widget rendering + await _webr_value_{{block_id}}; + if (window.HTMLWidgets) { + window.HTMLWidgets.staticRender(); + } + if (window.PagedTableDoc) { + window.PagedTableDoc.initAll(); + } +} diff --git a/week1/activities.qmd b/week1/activities.qmd index bfe5412..2bce134 100644 --- a/week1/activities.qmd +++ b/week1/activities.qmd @@ -3,13 +3,22 @@ title: "Activities: Week 1" editor: source engine: knitr filters: - - webr-teachr + - live - quiz-teachr +ojs-engine: true webr: - packages: ["fpp3", "urca"] + packages: + - qlcheckr + - fpp3 + - urca autoload-packages: false + repos: + - https://repo.r-wasm.org/ + - https://learnr-academy.github.io/qlcheckr --- +{{< include /_extensions/r-wasm/live/_knitr.qmd >}} + # Time series data and patterns ## Exercise 1 @@ -94,32 +103,78 @@ The units of the measured variables are as follows: Complete the code to convert this dataset into a tsibble. ::: -```{webr-teachr} -library(<>) +```{webr} +#| exercise: make_tsibble +library(______ ) aus_accommodation <- read.csv( "https://workshop.nectric.com.au/user2024/data/aus_accommodation.csv" ) |> mutate(Date = as.Date(Date)) |> as_tsibble( - <> + ______ ) -??? - -if(!("fpp3" %in% .packages())) return(c("You need to load the fpp3 package!" = TRUE)) +aus_accommodation +``` -checks <- c( - "You need to use the as_tsibble() function to convert the data into a tsibble." = !search_ast(.code, .fn = as_tsibble), - "You should specify which column provides the time of the measurements with `index`." = !search_ast(.code, .fn = as_tsibble, index = Date), - "You need to specify the key variables that identify each time series" = exists_in(.errored, grepl, pattern = "distinct rows", fixed = TRUE) +```{webr} +#| exercise: make_tsibble +#| check: true +library(qlcheckr) +apply_checks( + c( + "You need to load the fpp3 package!" = !("fpp3" %in% .packages()), + "You need to use the as_tsibble() function to convert the data into a tsibble." = !search_ast(ql_ast(), .fn = as_tsibble), + "You should specify which column provides the time of the measurements with `index`." = !search_ast(ql_ast(), .fn = as_tsibble, index = Date), + "You need to specify the key variables that identify each time series" = exists_in(ql_errors(), grepl, pattern = "distinct rows", fixed = TRUE) + ), + .msg_correct = if (!is_yearquarter(aus_accommodation$Date)) "Great, you've got a tsibble!
Although something doesn't look right - check the frequency of the data, why isn't it quarterly?" else "That's correct! Well done." ) +``` + +::: { .hint exercise="make_tsibble"} +::: { .callout-note collapse="false"} +## Hint + +Begin by loading the `fpp3` library to use its time series functions. + +```r +library(fpp3) +``` +::: +::: + +::: { .hint exercise="make_tsibble"} +::: { .callout-note collapse="false"} +## Hint -if(any(checks)) return(checks) +After loading the `fpp3` package, convert the data frame into a tsibble. -if(!is_yearquarter(aus_accommodation$Date)) cat("Great, you've got a tsibble!\nAlthough something doesn't look right - check the frequency of the data, why isn't it quarterly?\n") -FALSE +```r +library(fpp3) +aus_accommodation <- read.csv( + "https://workshop.nectric.com.au/user2024/data/aus_accommodation.csv" +) |> mutate(Date = as.Date(Date)) ``` +::: +::: + +::: { .hint exercise="make_tsibble"} +::: { .callout-note collapse="false"} +## Hint +Remember to specify the time index and key for `as_tsibble()` to function correctly. + +```r +library(fpp3) +aus_accommodation <- read.csv( + "https://workshop.nectric.com.au/user2024/data/aus_accommodation.csv" +) |> + mutate(Date = as.Date(Date)) |> + as_tsibble(key = State, index = Date) +``` +::: +::: ## Exercise 3 @@ -153,26 +208,63 @@ Use the appropriate granularity for the `aus_accommodation` dataset, and verify ::: -```{webr-teachr} +```{webr} +#| exercise: process_accommodation_data aus_accommodation <- read.csv( "https://workshop.nectric.com.au/user2024/data/aus_accommodation.csv" ) |> - mutate(<>) |> + mutate(______ ) |> as_tsibble( - key = State, index = <> + key = State, index = ______ ) -??? - -if(!("fpp3" %in% .packages())) return(c("You need to load the fpp3 package!" = TRUE)) +``` -c( - "You need to save the dataset as `aus_accommodation`" = !exists("aus_accommodation"), - "You need to use the as_tsibble() function to convert the data into a tsibble." = !search_ast(.code, .fn = as_tsibble), - "You need to specify the key variables that identify each time series" = exists_in(.errored, grepl, pattern = "distinct rows", fixed = TRUE), - "You should use `yearquarter()` to change the time column into a quarterly granularity" = !is_yearquarter(aus_accommodation[[index_var(aus_accommodation)]]) +```{webr} +#| exercise: process_accommodation_data +#| check: true +library(qlcheckr) +apply_checks( + c( + "You need to load the fpp3 package!" = !("fpp3" %in% .packages()), + "You need to save the dataset as `aus_accommodation`" = !exists("aus_accommodation"), + "You need to use the as_tsibble() function to convert the data into a tsibble." = !search_ast(ql_ast(), .fn = as_tsibble), + "You need to specify the key variables that identify each time series" = exists_in(ql_errors(), grepl, pattern = "distinct rows", fixed = TRUE), + "You should use `yearquarter()` to change the time column into a quarterly granularity" = !is_yearquarter(aus_accommodation[[index_var(aus_accommodation)]]) + ) ) ``` +::: { .hint exercise="process_accommodation_data"} +::: { .callout-note collapse="false"} +## Hint + +Start by reading the CSV file and transform the data using `mutate()` and `yearquarter()` for the Date column. + +```r +aus_accommodation <- read.csv( + "https://workshop.nectric.com.au/user2024/data/aus_accommodation.csv" +) |> + mutate(Quarter = yearquarter(Date)) +``` +::: +::: + +::: { .hint exercise="process_accommodation_data"} +::: { .callout-note collapse="false"} +## Hint + +After transforming the Date column, make sure you convert the data frame to a tsibble. + +```r +aus_accommodation <- read.csv( + "https://workshop.nectric.com.au/user2024/data/aus_accommodation.csv" +) |> + mutate(Quarter = yearquarter(Date)) |> + as_tsibble(key = State, index = Quarter) +``` +::: +::: + ## Exercise 4 The `tourism` dataset contains the quarterly overnight trips from 1998 Q1 to 2016 Q4 across Australia. @@ -185,51 +277,151 @@ It is disaggregated by 3 key variables: Calculate the total quarterly tourists visiting Victoria from the `tourism` dataset. -```{webr-teachr} +```{webr} +#| exercise: filter_summarise_tourism tourism |> - filter(<>) |> - summarise(<>) + filter(______) |> + summarise(______) +``` -??? +```{webr} +#| exercise: filter_summarise_tourism +#| check: true +library(qlcheckr) +apply_checks( + c( + "You need to load the fpp3 package!" = !("fpp3" %in% .packages()), + "You need to use the filter() function to extract only Victorian tourists." = !search_ast(ql_ast(), .fn = filter), + "You need to use the summarise() function to sum over the Region and Purpose keys." = !search_ast(ql_ast(), .fn = summarise) + ) +) +``` -if(!("fpp3" %in% .packages())) return(c("You need to load the fpp3 package!" = TRUE)) +::: { .hint exercise="filter_summarise_tourism"} +::: { .callout-note collapse="false"} +## Hint -c( - "You need to use the filter() function to extract only Victorian tourists." = !search_ast(.code, .fn = filter), - "You need to use the summarise() function to sum over the Region and Purpose keys." = !search_ast(.code, .fn = summarise), -) +To start off, filter the `tourism` dataset for only Victoria. + +```r +tourism |> + filter(State == "Victoria") +``` +::: +::: + +::: { .hint exercise="filter_summarise_tourism"} +::: { .callout-note collapse="false"} +## Hint + +After filtering, summarise the total trips for Victoria. + +```r +tourism |> + filter(State == "Victoria") |> + summarise(Trips = sum(Trips)) ``` +::: +::: Find what combination of `Region` and `Purpose` had the maximum number of overnight trips on average. -```{webr-teachr} +```{webr} +#| exercise: group_summarise_filter_tourism tourism |> as_tibble() |> - group_by(<>) |> - summarise(<>) |> - filter(<>) + group_by(______) |> + summarise(______) |> + filter(______) +``` + +```{webr} +#| exercise: group_summarise_filter_tourism +#| check: true +library(qlcheckr) +apply_checks( + c( + "You need to load the fpp3 package!" = !("fpp3" %in% .packages()), + "You need to use the as_tibble() function to convert back to a tibble object." = !search_ast(ql_ast(), .fn = as_tibble), + "You need to use the group_by() function to group by Region and Purpose." = !search_ast(ql_ast(), .fn = group_by) + ) +) +``` -??? +::: { .hint exercise="group_summarise_filter_tourism"} +::: { .callout-note collapse="false"} +## Hint -if(!("fpp3" %in% .packages())) return(c("You need to load the fpp3 package!" = TRUE)) +Start by using `as_tibble()` to convert `tourism` back to a tibble and group it by Region and Purpose. -c( - "You need to use the as_tibble() function to convert back to a tibble object." = !search_ast(.code, .fn = as_tibble), - "You need to use the group_by() function to group by Region and Purpose." = !search_ast(.code, .fn = group_by), -) +```r +tourism |> + as_tibble() |> + group_by(Region, Purpose) ``` +::: +::: -Create a new tsibble which combines the Purposes and Regions, and just has total trips by State. +::: { .hint exercise="group_summarise_filter_tourism"} +::: { .callout-note collapse="false"} +## Hint + +After grouping, summarise the mean number of trips and filter for maximum trips. -```{webr-teachr} -tourism +```r +tourism |> + as_tibble() |> + group_by(Region, Purpose) |> + summarise(Trips = mean(Trips), .groups = "drop") |> + filter(Trips == max(Trips)) +``` +::: +::: -??? +Create a new tsibble which combines the Purposes and Regions, and just has total trips by State. -if(!("fpp3" %in% .packages())) return(c("You need to load the fpp3 package!" = TRUE)) +```{webr} +#| exercise: summarise_tourism_by_state +tourism |> + group_by(______) |> + summarise(______) +``` -c( - "You need to use the filter() function to extract only Victorian tourists." = !search_ast(.code, .fn = filter), - "You need to use the summarise() function to sum over the Region and Purpose keys." = !search_ast(.code, .fn = summarise), +```{webr} +#| exercise: summarise_tourism_by_state +#| check: true +library(qlcheckr) +apply_checks( + c( + "You need to group by the State to summarise trips for each state." = !search_ast(ql_ast(), .expr = group_by(State)), + "You need to use the summarise() function to sum trips for each state." = !search_ast(ql_ast(), .expr = summarise(Trips = sum(Trips))) + ) ) ``` + +::: { .hint exercise="summarise_tourism_by_state"} +::: { .callout-note collapse="false"} +## Hint + +To summarise the number of trips by each State, start by grouping the data by State. + +```r +tourism |> + group_by(State) +``` +::: +::: + +::: { .hint exercise="summarise_tourism_by_state"} +::: { .callout-note collapse="false"} +## Hint + +After grouping, use the `summarise()` function to sum the trips. + +```r +tourism |> + group_by(State) |> + summarise(Trips = sum(Trips)) +``` +::: +:::