diff --git a/_config.yml b/_config.yml index 44973e0..ecb55ec 100644 --- a/_config.yml +++ b/_config.yml @@ -1,9 +1,9 @@ title: "GeneratedArt" description: >- - Community-run generative art platform and NFT marketplace for code-based - generative art (p5.js, three.js, WebGL, GLSL). A spiritual successor to - fxhash and Art Blocks, with a physical-digital bridge through the Geneva - gallery. + Community-run platform for AI Art Creative Coding and NFT marketplace — + train custom AI art models with disclosed provenance, or hand-code p5.js, + three.js, WebGL, and GLSL sketches. A spiritual successor to fxhash and + Art Blocks, with a physical-digital bridge through the Geneva gallery. url: "https://generatedart.com" baseurl: "" permalink: "/:title" diff --git a/_data/navigation.yml b/_data/navigation.yml index 002b705..88fc91a 100644 --- a/_data/navigation.yml +++ b/_data/navigation.yml @@ -1,426 +1,25 @@ main_menu: - - text: "Home" - url: "/" - menu_type: "megamenu" - submenu: - - text: "Digital Startup" - url: "/" - - text: "Saas Landing" - url: "/home-pages/index-2" - - text: "SEO Agency" - url: "/home-pages/index-3" - - text: "Modern Business" - url: "/home-pages/index-4" - - text: "Design Agency" - url: "/home-pages/index-5" - - text: "App Presentation" - url: "/home-pages/index-6" - - text: "Creative Landing" - url: "/home-pages/index-7" - - text: "Marketing Startup" - url: "/home-pages/index-8" - - text: "Digital Agency" - url: "/home-pages/index-9" - - text: "Creative Business" - url: "/home-pages/index-10" - - text: "Software Landing" - url: "/home-pages/index-11" - - text: "App Landing" - url: "/home-pages/index-12" - - text: "Creative Agency" - url: "/home-pages/index-13" - - text: "Wedding Photography" - url: "/home-pages/index-14" - - text: "Food Photography" - url: "/home-pages/index-15" - - text: "Creative Onepage" - url: "/home-pages/index-16" - - text: "Marketing Company" - url: "/home-pages/index-17" - - text: "Startup Business" - url: "/home-pages/index-18" - - text: "Creative Resume" - url: "/home-pages/index-19" - - text: "Digital Studio" - url: "/home-pages/index-20" - - text: "Travel Blog" - url: "/home-pages/index-21" - - text: "Minimal Shop" - url: "/home-pages/index-22" - - text: "Minimal Portfolio" - url: "/home-pages/index-23" - - text: "Coming Soon" - url: "/home-pages/index-24" - - text: "Personal Creative" - url: "/home-pages/index-25" - - text: "Minimal Photography" - url: "/home-pages/index-26" - - text: "Maintenance" - url: "/home-pages/index-27" - - text: "Features" - url: "#" - menu_type: "dropdown" - level_two: - - sub_menu_text: "Navigation" - sub_menu: - - text: "Classic Navigation" - url: "/features/navigation1" - - text: "Classic Light Navigation" - url: "/features/navigation2" - - text: "Classic Dark Navigation" - url: "/features/navigation3" - - text: "Topbar Navigation" - url: "/features/navigation4" - - text: "Wide Navigation" - url: "/features/navigation5" - - text: "Extended Navigation" - url: "/features/navigation6" - - text: "Fancy Light Navigation" - url: "/features/navigation7" - - text: "Fancy Dark Navigation" - url: "/features/navigation8" - - text: "Centered Navigation" - url: "/features/navigation9" - - text: "Shop Navigation" - url: "/features/navigation10" - - text: "Classic Navigation for Light Background" - url: "/features/navigation11" - - sub_menu_text: "Page Header" - sub_menu: - - text: "Header with Image" - url: "/features/header1" - - text: "Header with Breadcrumb" - url: "/features/header2" - - text: "Header with no Image" - url: "/features/header3" - - text: "Header with Gray Wrapper" - url: "/features/header4" - - text: "Header with Dark Wrapper" - url: "/features/header5" - - text: "Header with Colored Background" - url: "/features/header6" - - text: "Header with Gradient" - url: "/features/header7" - - text: "Header with Video Wrapper" - url: "/features/header8" - - text: "Header with Section Wrapper" - url: "/features/header9" - - text: "Header with Page Title" - url: "/features/header10" - - sub_menu_text: "Footer" - sub_menu: - - text: "Multi Column Footer V1" - url: "/features/footer1" - - text: "Centered Footer" - url: "/features/footer2" - - text: "Minimal Footer" - url: "/features/footer3" - - text: "Blog Footer" - url: "/features/footer4" - - text: "Multi Column Footer V2" - url: "/features/footer5" - - text: "Footer with Overflow" - url: "/features/footer6" - - text: "Footer with Background Image" - url: "/features/footer7" - - text: "Blog Footer with Background" - url: "/features/footer8" - level_one: - - text: "Modal" - url: "/features/modal" - - text: "FAQ" - url: "/features/faq" - - text: "Page Loading " - url: "/features/loading" - - text: "Page Scrolling" - url: "/features/scroll" - - - text: "Pages" - url: "#" - menu_type: "dropdown" - level_two: - - sub_menu_text: "Services" - sub_menu: - - text: "Service 01" - url: "/services/index" + - text: "Models" + url: "/models/" + menu_type: "simple" - - text: "Service 02" - url: "/services/index-2" + - text: "Explore" + url: "/explore/" + menu_type: "simple" - - text: "Service 03" - url: "/services/index-3" + - text: "Galleries" + url: "/galleries/" + menu_type: "simple" - - text: "Service 04" - url: "/services/index-4" + - text: "Briefs" + url: "/briefs/" + menu_type: "simple" - - text: "Service 05" - url: "/services/index-5" + - text: "About" + url: "/about/" + menu_type: "simple" - - sub_menu_text: "About Us" - sub_menu: - - text: "About 01" - url: "/about/about" - - - text: "About 02" - url: "/about/about-2" - - - text: "About 03" - url: "/about/about-3" - - - text: "About 04" - url: "/about/about-4" - - - sub_menu_text: "Shop" - sub_menu: - - text: "Shop 01" - url: "/shop/index" - - - text: "Shop 02" - url: "/shop/index-2" - - - text: "Product Page" - url: "/shop/brand-box" - - - text: "Featurd Product Page" - url: "/shop/featured/featured_product1" - - - text: "Cart Page" - url: "/shop/cart" - - - text: "Checkout Page" - url: "/shop/checkout" - - - sub_menu_text: "Contact" - sub_menu: - - text: "Contact 01" - url: "/contact/contact-1" - - - text: "Contact 02" - url: "/contact/contact-2" - - - text: "Contact 03" - url: "/contact/contact-3" - - - text: "Contact 04" - url: "/contact/contact-4" - - - - - text: "Elements" - url: "#" - menu_type: "megamenu" - submenu: - - - text: "Accordion" - url: "/elements/accordion" - - - text: "Dividers" - url: "/elements/dividers" - - - text: "Lightbox" - url: "/elements/lightbox" - - - text: "Tabs" - url: "/elements/tabs" - - - text: "Alerts" - url: "/elements/alerts" - - - text: "Dropcap" - url: "/elements/dropcap" - - - text: "Lists" - url: "/elements/lists" - - - text: "Team" - url: "/elements/team" - - - text: "Animated Text" - url: "/elements/animated_text" - - - text: "Forms" - url: "/elements/forms" - - - text: "Media Player" - url: "/elements/media_player" - - - text: "Testimonials" - url: "/elements/testimonials" - - - text: "Blockquote" - url: "/elements/blockquote" - - - text: "Buttons & Badges" - url: "/elements/buttons_badges" - - - text: "Call to Action" - url: "/elements/call_to_action" - - - text: "Carousel" - url: "/elements/carousel" - - - text: "Clients" - url: "/elements/clients" - - - text: "Countdown" - url: "/elements/countdown" - - - text: "Counter" - url: "/elements/counter" - - - text: "Icons - Concept" - url: "/elements/icons_concept" - - - text: "Icons - Jam" - url: "/elements/icons_jam" - - - text: "Icons - Icofont" - url: "/elements/icons_icofont" - - - text: "Icons - Lineal" - url: "/elements/icons_lineal" - - - text: "Icon Box" - url: "/elements/icon_box" - - - text: "Image Hover" - url: "/elements/image_hover" - - - text: "Image Mask" - url: "/elements/icons_image_mask" - - - text: "Modal" - url: "/elements/modal" - - - text: "Pricing Tables" - url: "/elements/pricing" - - - text: "Process Steps" - url: "/elements/process_steps" - - - text: "Progress Bar" - url: "/elements/progress_bar" - - - text: "Scroll Animations" - url: "/elements/scroll_animations" - - - text: "Social Icons" - url: "/elements/social_icons" - - - text: "Tables" - url: "/elements/tables" - - - text: "Titles" - url: "/elements/titles" - - - text: "Toggle" - url: "/elements/toggle" - - - text: "Tooltip & Popover" - url: "/elements/tooltip_popover" - - - text: "Typography" - url: "/elements/typography" - - - text: "Video Popup" - url: "/elements/video_popup" - - - text: "Waves" - url: "/elements/waves" - - - text: "Wrappers" - url: "/elements/wrappers" - - - text: "Portfolio" - url: "#" - level_one: - - text: "Grid Portfolio" - url: "/portfolios/grid-portfolio" - - - text: "Grid Portfolio With Details" - url: "/portfolios/grid-portfolio-details" - - - text: "Masonry Portfolio" - url: "/portfolios/masonry-portfolio" - - - text: "Masonry Portfolio With Details" - url: "/portfolios/masonry-portfolio-details" - - - text: "Mosaic Portfolio" - url: "/portfolios/mosaic-portfolio" - - - text: "Full Screen Grid Portfolio" - url: "/portfolios/fullscreen-grid" - - - text: "Portfolio With Item Details" - url: "/portfolios/portfolio-item-details" - - - text: "Box Portfolio With Item Details" - url: "/portfolios/box-item-details" - level_two: - - sub_menu_text: "Portfolio Posts" - sub_menu: - - text: "Post with multiple images" - url: "/portfolio/portfolio-post-multi-images" - - text: "Post with slider" - url: "/portfolio/portfolio-post-slider" - - text: "Post with masonry gallery" - url: "/portfolio/portfolio-post-masonry" - - text: "Post with carousel" - url: "/portfolio/portfolio-post-carousel" - - text: "Post with columns" - url: "/portfolio/portfolio-post-columns" - - text: "Post with video" - url: "/portfolio/portfolio-post-video" - - - text: "Blog" - url: "#" - menu_type: "dropdown" - level_one: - - text: "Classic Grid" - url: "/blogs/classic-grid" - - - text: "Classic Grid With Sidebar" - url: "/blogs/classic-grid-sidebar" - - - text: "Box Grid Blog" - url: "/blogs/boxed-grid" - - - text: "Box Grid Blog With Sidebar" - url: "/blogs/boxed-grid-sidebar" - - - text: "Classic Blog" - url: "/blogs/classic" - - - text: "Classic Blog with Sidebar" - url: "/blogs/classic-sidebar" - - - text: "Boxed Classic Blog" - url: "/blogs/boxed-classic" - - - text: "Boxed Classic Blog With Sidebar" - url: "/blogs/boxed-classic-sidebar" - level_two: - - sub_menu_text: "Blog Posts" - sub_menu: - - text: "Post with sidebar" - url: "/posts/simple-post-with-sidebar" - - text: "Post with no sidebar" - url: "/posts/simple-post-with-no-sidebar" - - text: "Box Post with no sidebar" - url: "/posts/post-boxed" - - text: "Box Post with sidebar" - url: "/posts/post-boxed-sidebar" - - text: "Post with code highlight" - url: "/posts/post-with-code-highlight" - - text: "Post with video" - url: "/posts/post-with-video" - - text: "Post with image" - url: "/posts/post-with-image" - - text: "Post with carousel" - url: "/posts/post-with-carousel" - - text: "Post with Multiple Carousel" - url: "/posts/multi-carousel-post" - - text: "Post with gallery" - url: "/posts/post-with-gallery" + - text: "Dashboard" + url: "/dashboard/projects/" + menu_type: "simple" diff --git a/about/index.html b/about/index.html index 3c19adb..5a9eca4 100644 --- a/about/index.html +++ b/about/index.html @@ -1,12 +1,14 @@ --- layout: default title: "About GeneratedArt" -sub_title: "An open marketplace for code-based generative art, owned by the people who make it." +sub_title: "Where AI Creative Coders build the models that make the art — owned by the people who train them." header_image: "/assets/images/art/bg1.webp" description: >- - GeneratedArt is a community-run platform for code-based generative art - (p5.js, three.js, WebGL, GLSL). The repo is the artwork. The artist is the - owner. The platform is shared infrastructure. + GeneratedArt is a community-run platform for AI Art Creative Coding — + training custom AI art models, and hand-coded p5.js, three.js, WebGL, and + GLSL sketches. The code is the artwork, whether it's a sketch or the + model that produced it. The artist is the owner. The platform is shared + infrastructure. --- {% include layouts/nav/nav-2.html default_logo="black" drop_search=true %} {% include layouts/header/page-title9.html %} @@ -17,18 +19,23 @@

A platform we'd want to publish on ourselves.

- GeneratedArt is a marketplace and home for code-based generative art. - Everything that ships here is a sketch — a JavaScript or shader program that - renders a unique output for every collector who mints it. The repo is the - artwork. The artist owns the contract. The platform is shared - infrastructure, not a landlord. + GeneratedArt is a marketplace and home for AI Art Creative Coding — + the modern practice where an artist's creative act is training the model + that makes the art, in the same lineage as dataset-trained generative + systems like Refik Anadol's work, without claiming any affiliation. Hand-coded + p5.js, three.js, WebGL, and GLSL sketches remain a fully respected second + path. Either way, code is the medium: a model's architecture, training + config, and inference pipeline are code, exactly as a sketch is. The artist + owns the contract. The platform is shared infrastructure, not a landlord.

We started this because the existing options each gave up something we weren't willing to give up. Centralised marketplaces hold the keys, dictate - royalties, and de-platform without warning. Pure on-chain venues are - beautiful but inaccessible to most artists. The middle ground — open, - curatable, transparent, with a real physical-world endpoint — was empty. + royalties, and de-platform without warning. Prompt-only AI art tools rent + you an aesthetic with no reproducibility and no way to say what a model was + actually trained on. Pure on-chain venues are beautiful but inaccessible to + most artists. The middle ground — open, curatable, transparent, provenance + disclosed by construction, with a real physical-world endpoint — was empty.

@@ -42,11 +49,12 @@

A platform we'd want to publish on ourselves.

What we believe

-
The repo is the artwork.
+
The code is the artwork.

- A sketch is its source. Mints reference an immutable commit, not a - JPEG. If the platform disappears, the work still runs — pull the repo, - open the file, render in any browser. + A sketch is its source; a trained model is its base model, training + method, and dataset. Mints reference an immutable commit or a locked + CID, not a JPEG. If the platform disappears, the work still runs — + pull the repo or the weights, render in any browser.

@@ -58,6 +66,15 @@
The artist owns the contract.
gatekeeper.

+
+
Provenance is disclosed, not claimed.
+

+ Every AI art model publishes its base model, training method, and a + dataset note in the creator's own words — publicly, alongside the + model — the same trust mechanic frozen-CID provenance already gives + a code sketch. +

+
Curation is human.

@@ -87,7 +104,8 @@

There is a room.

Where it runs

Static front-end on GitHub Pages. Hono on Cloudflare Workers for the - API. D1 + KV + R2 + Queues at the edge. ERC-721 contracts on Base. + API. D1 + KV + R2 + Queues at the edge. Claude for code generation, + fal.ai for custom-trained models. ERC-721 contracts on Base. Wallets via WalletConnect. Pinning via IPFS. No central database, no auth provider, no platform that can pull the rug.

diff --git a/assets/js/ga-dashboard.js b/assets/js/ga-dashboard.js index 15a5c91..11083d8 100644 --- a/assets/js/ga-dashboard.js +++ b/assets/js/ga-dashboard.js @@ -1,19 +1,19 @@ -var u=new Set,f=10,g=!1,c=null;function v(e){g||(g=!0,c=e,window.addEventListener("error",t=>{let r=t.error&&t.error.message||t.message||"unknown_error",n=t.error&&t.error.stack||`${t.filename??""}:${t.lineno??0}:${t.colno??0}`;h(r,n)}),window.addEventListener("unhandledrejection",t=>{let r=t.reason,n=r instanceof Error?r.message:typeof r=="string"?r:"unhandled_rejection",a=r instanceof Error?r.stack??"":"";h(n,a)}))}function E(e){try{let t=new URL(e,location.origin);return`${t.origin}${t.pathname}`.slice(0,200)}catch{return e.split("?")[0].split("#")[0].slice(0,200)}}async function h(e,t){if(!c||u.size>=f)return;let r=`${e}::${t.slice(0,80)}`;if(!u.has(r)){u.add(r);try{await fetch(`${c.apiBase}/v1/internal/client-error`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:String(e).slice(0,500),stack:String(t).slice(0,4e3),page:c.page,url:E(location.href),ts:Date.now()}),keepalive:!0})}catch{}}}var y={draft:"Draft",published:"Published",minted:"Minted",archived:"Archived"};function j(e){return`${y[e]||e}`}function o(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function w(e){let t=e.status==="archived",r=e.repo_url?`View repo \u2192`:"",n=t?"":``;return` +var u=new Set,f=10,g=!1,d=null;function v(e){g||(g=!0,d=e,window.addEventListener("error",t=>{let n=t.error&&t.error.message||t.message||"unknown_error",r=t.error&&t.error.stack||`${t.filename??""}:${t.lineno??0}:${t.colno??0}`;h(n,r)}),window.addEventListener("unhandledrejection",t=>{let n=t.reason,r=n instanceof Error?n.message:typeof n=="string"?n:"unhandled_rejection",a=n instanceof Error?n.stack??"":"";h(r,a)}))}function E(e){try{let t=new URL(e,location.origin);return`${t.origin}${t.pathname}`.slice(0,200)}catch{return e.split("?")[0].split("#")[0].slice(0,200)}}async function h(e,t){if(!d||u.size>=f)return;let n=`${e}::${t.slice(0,80)}`;if(!u.has(n)){u.add(n);try{await fetch(`${d.apiBase}/v1/internal/client-error`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:String(e).slice(0,500),stack:String(t).slice(0,4e3),page:d.page,url:E(location.href),ts:Date.now()}),keepalive:!0})}catch{}}}var y={draft:"Draft",published:"Published",minted:"Minted",archived:"Archived"};function w(e){return`${y[e]||e}`}function s(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function C(e){let t=e.status==="archived",n=e.repo_url?`View repo \u2192`:"",r=t?"":``;return`
-

${o(e.title)}

-

${o(e.engine)} \xB7 ${o(e.license)}

+

${s(e.title)}

+

${s(e.engine)} \xB7 ${s(e.license)}

-

${o(e.description||"No description yet.")}

+

${s(e.description||"No description yet.")}

-
${j(e.status)}
+
${w(e.status)}
- ${r} ${n} + ${r}
- `}function C(){return` + `}function j(){return`

No projects yet.

Click "New project" to create your first generative-art repo.

@@ -66,5 +66,5 @@ var u=new Set,f=10,g=!1,c=null;function v(e){g||(g=!0,c=e,window.addEventListene
- `}async function d(e,t){let r=await fetch(e,{credentials:"include",...t});if(!r.ok){let n="";try{n=JSON.stringify(await r.json())}catch{}throw new Error(`${r.status}: ${n||r.statusText}`)}return await r.json()}async function p(e){let t=e.rootEl.querySelector("#ga-project-list");if(t){t.innerHTML='
Loading\u2026
';try{let{projects:r}=await d(`${e.apiBase}/v1/projects/mine`);r.length?t.innerHTML=r.map(w).join(""):t.innerHTML=C()}catch(r){t.innerHTML=`
Failed to load projects: ${o(String(r))}
`}}}async function T(e,t){return d(`${e.apiBase}/v1/projects`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function M(e,t){return d(`${e.apiBase}/v1/projects/${t}/archive`,{method:"POST"})}function L(e){e.rootEl.addEventListener("click",async r=>{let n=r.target;if(n.matches(".ga-archive-btn")){let a=parseInt(n.getAttribute("data-project-id")||"",10);if(!a||!confirm("Archive this project? The GitHub repo will be archived but its history is preserved."))return;try{await M(e,a),await p(e)}catch(s){alert("Archive failed: "+s)}}}),e.rootEl.querySelector("#ga-new-project-form")?.addEventListener("submit",async r=>{r.preventDefault();let n=e.rootEl.querySelector("#ga-np-title"),a=e.rootEl.querySelector("#ga-np-description"),s=e.rootEl.querySelector("#ga-np-engine"),m=e.rootEl.querySelector("#ga-np-license"),i=e.rootEl.querySelector("#ga-new-project-error");if(!(!n||!s||!m||!i)){i.classList.add("d-none");try{await T(e,{title:n.value,description:a?.value||null,engine:s.value,license:m.value}),n.value="",a&&(a.value="");let l=document.getElementById("ga-new-project-modal");l&&window.bootstrap?.Modal&&window.bootstrap.Modal.getOrCreateInstance(l).hide(),await p(e)}catch(l){i.textContent="Create failed: "+String(l),i.classList.remove("d-none")}}})}var b={async mount(e){v({apiBase:e.apiBase,page:"dashboard"});let t=null;try{t=await d(`${e.apiBase}/v1/me`)}catch{t=null}if(!t){e.onUnauthenticated?.();return}e.rootEl.querySelector("#ga-dashboard-handle").textContent=t.user.handle,e.rootEl.querySelector("#ga-dashboard-address").textContent=t.user.address;let r=e.rootEl.querySelector("#ga-modal-root");r&&!r.innerHTML.trim()&&(r.innerHTML=S()),L(e),await p(e)}};window.GADashboard=b;var x=b;export{x as default}; + `}async function o(e,t){let n=await fetch(e,{credentials:"include",...t});if(!n.ok){let r="";try{r=JSON.stringify(await n.json())}catch{}throw new Error(`${n.status}: ${r||n.statusText}`)}return await n.json()}async function p(e){let t=e.rootEl.querySelector("#ga-project-list");if(t){t.innerHTML='
Loading\u2026
';try{let{projects:n}=await o(`${e.apiBase}/v1/projects/mine`);n.length?t.innerHTML=n.map(C).join(""):t.innerHTML=j()}catch(n){t.innerHTML=`
Failed to load projects: ${s(String(n))}
`}}}async function T(e,t){return o(`${e.apiBase}/v1/projects`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function L(e,t){return o(`${e.apiBase}/v1/projects/${t}/archive`,{method:"POST"})}function M(e){e.rootEl.addEventListener("click",async n=>{let r=n.target;if(r.matches(".ga-archive-btn")){let a=parseInt(r.getAttribute("data-project-id")||"",10);if(!a||!confirm("Archive this project? The GitHub repo will be archived but its history is preserved."))return;try{await L(e,a),await p(e)}catch(i){alert("Archive failed: "+i)}}}),e.rootEl.querySelector("#ga-new-project-form")?.addEventListener("submit",async n=>{n.preventDefault();let r=e.rootEl.querySelector("#ga-np-title"),a=e.rootEl.querySelector("#ga-np-description"),i=e.rootEl.querySelector("#ga-np-engine"),m=e.rootEl.querySelector("#ga-np-license"),l=e.rootEl.querySelector("#ga-new-project-error");if(!(!r||!i||!m||!l)){l.classList.add("d-none");try{await T(e,{title:r.value,description:a?.value||null,engine:i.value,license:m.value}),r.value="",a&&(a.value="");let c=document.getElementById("ga-new-project-modal");c&&window.bootstrap?.Modal&&window.bootstrap.Modal.getOrCreateInstance(c).hide(),await p(e)}catch(c){l.textContent="Create failed: "+String(c),l.classList.remove("d-none")}}})}var b={async mount(e){v({apiBase:e.apiBase,page:"dashboard"});let t=null;try{t=await o(`${e.apiBase}/v1/me`)}catch{t=null}if(!t){e.onUnauthenticated?.();return}e.rootEl.querySelector("#ga-dashboard-handle").textContent=t.user.handle,e.rootEl.querySelector("#ga-dashboard-address").textContent=t.user.address;let n=e.rootEl.querySelector("#ga-modal-root");n&&!n.innerHTML.trim()&&(n.innerHTML=S()),M(e),await p(e),await $(e)}};async function $(e){let t=e.rootEl.querySelector("#ga-tile-datasets"),n=e.rootEl.querySelector("#ga-tile-models"),r=e.rootEl.querySelector("#ga-tile-wallet");if(t)try{let a=await o(`${e.apiBase}/v1/datasets/mine`);t.textContent=String(a.datasets.length)}catch{t.textContent="\u2014"}if(n)try{let a=await o(`${e.apiBase}/v1/models/mine`);n.textContent=String(a.models.length)}catch{n.textContent="\u2014"}if(r)try{let a=await o(`${e.apiBase}/v1/tokens/account`);r.textContent=`${a.balance.toLocaleString()} tokens`}catch{r.textContent="\u2014"}}window.GADashboard=b;var H=b;export{H as default}; //# sourceMappingURL=ga-dashboard.js.map diff --git a/assets/js/ga-dashboard.js.map b/assets/js/ga-dashboard.js.map index 973fd50..95c61da 100644 --- a/assets/js/ga-dashboard.js.map +++ b/assets/js/ga-dashboard.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../../workers/api/client/lib/clientErrors.ts", "../../workers/api/client/dashboard.ts"], - "sourcesContent": ["// Window onerror / unhandledrejection \u2192 POST /v1/internal/client-error.\n// Per-page de-dupe and 10-report cap; the Worker rate-limits per IP\n// and forwards to Sentry via SENTRY_DSN_PUBLIC server-side.\n//\n// Why not @sentry/browser? Bundle size is the deciding factor:\n// @sentry/browser min+gz is ~25KB, which is larger than every\n// per-page bundle this app ships (galleries 18KB, studio 100KB,\n// dashboard 7KB). The proxy pattern below has equivalent delivery\n// (the worker uses ctx.waitUntil for the forward), preserves stack\n// fidelity (we POST the raw `Error.stack` string verbatim), and\n// keeps the public DSN out of the client where it would otherwise\n// be visible to scrapers. The trade-off is that we don't get the\n// SDK's auto-capture of breadcrumbs / fetch/console hooks; for v1\n// observability that's an acceptable gap given the size budget.\n\nconst SEEN = new Set();\nconst MAX_REPORTS_PER_PAGE = 10;\nlet installed = false;\nlet configured: { apiBase: string; page: string } | null = null;\n\nexport interface ClientErrorReporterConfig {\n apiBase: string;\n /** Short page identifier \u2014 \"studio\", \"dashboard\", \"galleries\" etc. */\n page: string;\n}\n\nexport function installClientErrorReporter(cfg: ClientErrorReporterConfig): void {\n if (installed) return;\n installed = true;\n configured = cfg;\n window.addEventListener(\"error\", (ev) => {\n const message =\n (ev.error && ev.error.message) || ev.message || \"unknown_error\";\n const stack =\n (ev.error && ev.error.stack) ||\n `${ev.filename ?? \"\"}:${ev.lineno ?? 0}:${ev.colno ?? 0}`;\n void report(message, stack);\n });\n window.addEventListener(\"unhandledrejection\", (ev) => {\n const reason = (ev as PromiseRejectionEvent).reason;\n const message =\n reason instanceof Error\n ? reason.message\n : typeof reason === \"string\"\n ? reason\n : \"unhandled_rejection\";\n const stack = reason instanceof Error ? reason.stack ?? \"\" : \"\";\n void report(message, stack);\n });\n}\n\n// PII scrub: strip query string and hash from any URL we forward\n// so signed-upload tokens, ?email=, ?invite=, fragment-encoded\n// session bits, etc. never leave the browser. Also caps length.\nfunction scrubUrl(raw: string): string {\n try {\n const u = new URL(raw, location.origin);\n return `${u.origin}${u.pathname}`.slice(0, 200);\n } catch {\n return raw.split(\"?\")[0].split(\"#\")[0].slice(0, 200);\n }\n}\n\nasync function report(message: string, stack: string): Promise {\n if (!configured) return;\n // Per-page de-dupe + cap so a hot-loop error doesn't DoS the\n // /v1/internal/client-error endpoint.\n if (SEEN.size >= MAX_REPORTS_PER_PAGE) return;\n const key = `${message}::${stack.slice(0, 80)}`;\n if (SEEN.has(key)) return;\n SEEN.add(key);\n\n try {\n await fetch(`${configured.apiBase}/v1/internal/client-error`, {\n method: \"POST\",\n credentials: \"include\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n message: String(message).slice(0, 500),\n stack: String(stack).slice(0, 4000),\n page: configured.page,\n url: scrubUrl(location.href),\n ts: Date.now(),\n }),\n keepalive: true,\n });\n } catch {\n // never escalate a reporter failure into another error event\n }\n}\n", "import { installClientErrorReporter } from \"./lib/clientErrors\";\n\ninterface ProjectSummary {\n id: number;\n slug: string;\n title: string;\n description: string | null;\n engine: string;\n license: string;\n status: string;\n repo_url: string | null;\n repo_full: string | null;\n cover_url: string | null;\n created_at: number;\n updated_at: number;\n}\n\ninterface MeResponse {\n user: { id: number; address: string; handle: string };\n}\n\ninterface BootstrapModalInstance {\n show(): void;\n hide(): void;\n}\ninterface BootstrapModalCtor {\n getOrCreateInstance(el: Element): BootstrapModalInstance;\n}\ninterface BootstrapNamespace {\n Modal: BootstrapModalCtor;\n}\n\ndeclare global {\n interface Window {\n GADashboard?: typeof GADashboard;\n bootstrap?: BootstrapNamespace;\n }\n}\n\ninterface DashboardConfig {\n apiBase: string;\n rootEl: HTMLElement;\n}\n\nconst STATUS_LABELS: Record = {\n draft: \"Draft\",\n published: \"Published\",\n minted: \"Minted\",\n archived: \"Archived\",\n};\n\nfunction statusBadge(status: string): string {\n const cls = `ga-badge ga-badge-${status}`;\n return `${STATUS_LABELS[status] || status}`;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\": return \"&\";\n case \"<\": return \"<\";\n case \">\": return \">\";\n case '\"': return \""\";\n default: return \"'\";\n }\n });\n}\n\nfunction renderProjectCard(p: ProjectSummary): string {\n const isArchived = p.status === \"archived\";\n const repoLink = p.repo_url\n ? `View repo \u2192`\n : \"\";\n const archiveBtn = isArchived\n ? \"\"\n : ``;\n return `\n
\n
\n

${escapeHtml(p.title)}

\n

${escapeHtml(p.engine)} \u00B7 ${escapeHtml(p.license)}

\n
\n

${escapeHtml(p.description || \"No description yet.\")}

\n
\n
${statusBadge(p.status)}
\n
\n ${repoLink}\n ${archiveBtn}\n
\n
\n
\n `;\n}\n\nfunction renderEmpty(): string {\n return `\n
\n

No projects yet.

\n

Click \"New project\" to create your first generative-art repo.

\n
\n `;\n}\n\nfunction renderModal(): string {\n return `\n
\n
\n
\n
\n
New project
\n \n
\n
\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n
\n \n \n
\n
\n
\n
\n
\n `;\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise {\n const res = await fetch(url, { credentials: \"include\", ...init });\n if (!res.ok) {\n let detail = \"\";\n try { detail = JSON.stringify(await res.json()); } catch {}\n throw new Error(`${res.status}: ${detail || res.statusText}`);\n }\n return (await res.json()) as T;\n}\n\nasync function loadProjects(cfg: DashboardConfig): Promise {\n const listEl = cfg.rootEl.querySelector(\"#ga-project-list\");\n if (!listEl) return;\n listEl.innerHTML = `
Loading\u2026
`;\n try {\n const { projects } = await fetchJson<{ projects: ProjectSummary[] }>(\n `${cfg.apiBase}/v1/projects/mine`,\n );\n if (!projects.length) {\n listEl.innerHTML = renderEmpty();\n } else {\n listEl.innerHTML = projects.map(renderProjectCard).join(\"\");\n }\n } catch (err) {\n listEl.innerHTML = `
Failed to load projects: ${escapeHtml(String(err))}
`;\n }\n}\n\nasync function createProject(cfg: DashboardConfig, body: Record) {\n return fetchJson<{ project: ProjectSummary }>(`${cfg.apiBase}/v1/projects`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n}\n\nasync function archiveProject(cfg: DashboardConfig, id: number) {\n return fetchJson<{ project: ProjectSummary }>(\n `${cfg.apiBase}/v1/projects/${id}/archive`,\n { method: \"POST\" },\n );\n}\n\nfunction attachEvents(cfg: DashboardConfig) {\n cfg.rootEl.addEventListener(\"click\", async (ev) => {\n const target = ev.target as HTMLElement;\n if (target.matches(\".ga-archive-btn\")) {\n const id = parseInt(target.getAttribute(\"data-project-id\") || \"\", 10);\n if (!id) return;\n if (!confirm(\"Archive this project? The GitHub repo will be archived but its history is preserved.\")) return;\n try {\n await archiveProject(cfg, id);\n await loadProjects(cfg);\n } catch (err) {\n alert(\"Archive failed: \" + err);\n }\n }\n });\n\n const form = cfg.rootEl.querySelector(\"#ga-new-project-form\");\n form?.addEventListener(\"submit\", async (ev) => {\n ev.preventDefault();\n const titleEl = cfg.rootEl.querySelector(\"#ga-np-title\");\n const descEl = cfg.rootEl.querySelector(\"#ga-np-description\");\n const engineEl = cfg.rootEl.querySelector(\"#ga-np-engine\");\n const licenseEl = cfg.rootEl.querySelector(\"#ga-np-license\");\n const errEl = cfg.rootEl.querySelector(\"#ga-new-project-error\");\n if (!titleEl || !engineEl || !licenseEl || !errEl) return;\n errEl.classList.add(\"d-none\");\n try {\n await createProject(cfg, {\n title: titleEl.value,\n description: descEl?.value || null,\n engine: engineEl.value,\n license: licenseEl.value,\n });\n titleEl.value = \"\";\n if (descEl) descEl.value = \"\";\n const modalEl = document.getElementById(\"ga-new-project-modal\");\n if (modalEl && window.bootstrap?.Modal) {\n window.bootstrap.Modal.getOrCreateInstance(modalEl).hide();\n }\n await loadProjects(cfg);\n } catch (err) {\n errEl.textContent = \"Create failed: \" + String(err);\n errEl.classList.remove(\"d-none\");\n }\n });\n}\n\nconst GADashboard = {\n async mount(cfg: DashboardConfig & { onUnauthenticated?: () => void }) {\n installClientErrorReporter({ apiBase: cfg.apiBase, page: \"dashboard\" });\n let me: MeResponse | null = null;\n try {\n me = await fetchJson(`${cfg.apiBase}/v1/me`);\n } catch {\n me = null;\n }\n if (!me) {\n cfg.onUnauthenticated?.();\n return;\n }\n cfg.rootEl.querySelector(\"#ga-dashboard-handle\")!.textContent = me.user.handle;\n cfg.rootEl.querySelector(\"#ga-dashboard-address\")!.textContent = me.user.address;\n\n const modalRoot = cfg.rootEl.querySelector(\"#ga-modal-root\");\n if (modalRoot && !modalRoot.innerHTML.trim()) modalRoot.innerHTML = renderModal();\n attachEvents(cfg);\n await loadProjects(cfg);\n },\n};\n\nwindow.GADashboard = GADashboard;\nexport default GADashboard;\n"], - "mappings": "AAeA,IAAMA,EAAO,IAAI,IACXC,EAAuB,GACzBC,EAAY,GACZC,EAAuD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ZY,EAAM,YAAc,kBAAoB,OAAOZ,CAAG,EAClDY,EAAM,UAAU,OAAO,QAAQ,CACjC,EACF,CAAC,CACH,CAEA,IAAME,EAAc,CAClB,MAAM,MAAMjB,EAA2D,CACrEkB,EAA2B,CAAE,QAASlB,EAAI,QAAS,KAAM,WAAY,CAAC,EACtE,IAAImB,EAAwB,KAC5B,GAAI,CACFA,EAAK,MAAMzB,EAAsB,GAAGM,EAAI,OAAO,QAAQ,CACzD,MAAQ,CACNmB,EAAK,IACP,CACA,GAAI,CAACA,EAAI,CACPnB,EAAI,oBAAoB,EACxB,MACF,CACAA,EAAI,OAAO,cAA2B,sBAAsB,EAAG,YAAcmB,EAAG,KAAK,OACrFnB,EAAI,OAAO,cAA2B,uBAAuB,EAAG,YAAcmB,EAAG,KAAK,QAEtF,IAAMC,EAAYpB,EAAI,OAAO,cAA2B,gBAAgB,EACpEoB,GAAa,CAACA,EAAU,UAAU,KAAK,IAAGA,EAAU,UAAY3B,EAAY,GAChFe,EAAaR,CAAG,EAChB,MAAMD,EAAaC,CAAG,CACxB,CACF,EAEA,OAAO,YAAciB,EACrB,IAAOI,EAAQJ", - "names": ["SEEN", "MAX_REPORTS_PER_PAGE", "installed", "configured", "installClientErrorReporter", "cfg", "ev", "message", "stack", "report", "reason", "scrubUrl", "raw", "u", "key", "STATUS_LABELS", "statusBadge", "status", "escapeHtml", "s", "ch", "renderProjectCard", "p", "isArchived", "repoLink", "archiveBtn", "renderEmpty", "renderModal", "fetchJson", "url", "init", "res", "detail", "loadProjects", "cfg", "listEl", "projects", "err", "createProject", "body", "archiveProject", "id", "attachEvents", "ev", "target", "titleEl", "descEl", "engineEl", "licenseEl", "errEl", "modalEl", "GADashboard", "installClientErrorReporter", "me", "modalRoot", "dashboard_default"] + "sourcesContent": ["// Window onerror / unhandledrejection \u2192 POST /v1/internal/client-error.\n// Per-page de-dupe and 10-report cap; the Worker rate-limits per IP\n// and forwards to Sentry via SENTRY_DSN_PUBLIC server-side.\n//\n// Why not @sentry/browser? Bundle size is the deciding factor:\n// @sentry/browser min+gz is ~25KB, which is larger than every\n// per-page bundle this app ships (galleries 18KB, studio 100KB,\n// dashboard 7KB). The proxy pattern below has equivalent delivery\n// (the worker uses ctx.waitUntil for the forward), preserves stack\n// fidelity (we POST the raw `Error.stack` string verbatim), and\n// keeps the public DSN out of the client where it would otherwise\n// be visible to scrapers. The trade-off is that we don't get the\n// SDK's auto-capture of breadcrumbs / fetch/console hooks; for v1\n// observability that's an acceptable gap given the size budget.\n\nconst SEEN = new Set();\nconst MAX_REPORTS_PER_PAGE = 10;\nlet installed = false;\nlet configured: { apiBase: string; page: string } | null = null;\n\nexport interface ClientErrorReporterConfig {\n apiBase: string;\n /** Short page identifier \u2014 \"studio\", \"dashboard\", \"galleries\" etc. */\n page: string;\n}\n\nexport function installClientErrorReporter(cfg: ClientErrorReporterConfig): void {\n if (installed) return;\n installed = true;\n configured = cfg;\n window.addEventListener(\"error\", (ev) => {\n const message =\n (ev.error && ev.error.message) || ev.message || \"unknown_error\";\n const stack =\n (ev.error && ev.error.stack) ||\n `${ev.filename ?? \"\"}:${ev.lineno ?? 0}:${ev.colno ?? 0}`;\n void report(message, stack);\n });\n window.addEventListener(\"unhandledrejection\", (ev) => {\n const reason = (ev as PromiseRejectionEvent).reason;\n const message =\n reason instanceof Error\n ? reason.message\n : typeof reason === \"string\"\n ? reason\n : \"unhandled_rejection\";\n const stack = reason instanceof Error ? reason.stack ?? \"\" : \"\";\n void report(message, stack);\n });\n}\n\n// PII scrub: strip query string and hash from any URL we forward\n// so signed-upload tokens, ?email=, ?invite=, fragment-encoded\n// session bits, etc. never leave the browser. Also caps length.\nfunction scrubUrl(raw: string): string {\n try {\n const u = new URL(raw, location.origin);\n return `${u.origin}${u.pathname}`.slice(0, 200);\n } catch {\n return raw.split(\"?\")[0].split(\"#\")[0].slice(0, 200);\n }\n}\n\nasync function report(message: string, stack: string): Promise {\n if (!configured) return;\n // Per-page de-dupe + cap so a hot-loop error doesn't DoS the\n // /v1/internal/client-error endpoint.\n if (SEEN.size >= MAX_REPORTS_PER_PAGE) return;\n const key = `${message}::${stack.slice(0, 80)}`;\n if (SEEN.has(key)) return;\n SEEN.add(key);\n\n try {\n await fetch(`${configured.apiBase}/v1/internal/client-error`, {\n method: \"POST\",\n credentials: \"include\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n message: String(message).slice(0, 500),\n stack: String(stack).slice(0, 4000),\n page: configured.page,\n url: scrubUrl(location.href),\n ts: Date.now(),\n }),\n keepalive: true,\n });\n } catch {\n // never escalate a reporter failure into another error event\n }\n}\n", "import { installClientErrorReporter } from \"./lib/clientErrors\";\n\ninterface ProjectSummary {\n id: number;\n slug: string;\n title: string;\n description: string | null;\n engine: string;\n license: string;\n status: string;\n repo_url: string | null;\n repo_full: string | null;\n cover_url: string | null;\n created_at: number;\n updated_at: number;\n}\n\ninterface MeResponse {\n user: { id: number; address: string; handle: string };\n}\n\ninterface BootstrapModalInstance {\n show(): void;\n hide(): void;\n}\ninterface BootstrapModalCtor {\n getOrCreateInstance(el: Element): BootstrapModalInstance;\n}\ninterface BootstrapNamespace {\n Modal: BootstrapModalCtor;\n}\n\ndeclare global {\n interface Window {\n GADashboard?: typeof GADashboard;\n bootstrap?: BootstrapNamespace;\n }\n}\n\ninterface DashboardConfig {\n apiBase: string;\n rootEl: HTMLElement;\n}\n\nconst STATUS_LABELS: Record = {\n draft: \"Draft\",\n published: \"Published\",\n minted: \"Minted\",\n archived: \"Archived\",\n};\n\nfunction statusBadge(status: string): string {\n const cls = `ga-badge ga-badge-${status}`;\n return `${STATUS_LABELS[status] || status}`;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\": return \"&\";\n case \"<\": return \"<\";\n case \">\": return \">\";\n case '\"': return \""\";\n default: return \"'\";\n }\n });\n}\n\nfunction renderProjectCard(p: ProjectSummary): string {\n const isArchived = p.status === \"archived\";\n const repoLink = p.repo_url\n ? `View repo \u2192`\n : \"\";\n const archiveBtn = isArchived\n ? \"\"\n : ``;\n return `\n
\n
\n

${escapeHtml(p.title)}

\n

${escapeHtml(p.engine)} \u00B7 ${escapeHtml(p.license)}

\n
\n

${escapeHtml(p.description || \"No description yet.\")}

\n
\n
${statusBadge(p.status)}
\n
\n ${repoLink}\n ${archiveBtn}\n
\n
\n
\n `;\n}\n\nfunction renderEmpty(): string {\n return `\n
\n

No projects yet.

\n

Click \"New project\" to create your first generative-art repo.

\n
\n `;\n}\n\nfunction renderModal(): string {\n return `\n
\n
\n
\n
\n
New project
\n \n
\n
\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n
\n \n \n
\n
\n
\n
\n
\n `;\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise {\n const res = await fetch(url, { credentials: \"include\", ...init });\n if (!res.ok) {\n let detail = \"\";\n try { detail = JSON.stringify(await res.json()); } catch {}\n throw new Error(`${res.status}: ${detail || res.statusText}`);\n }\n return (await res.json()) as T;\n}\n\nasync function loadProjects(cfg: DashboardConfig): Promise {\n const listEl = cfg.rootEl.querySelector(\"#ga-project-list\");\n if (!listEl) return;\n listEl.innerHTML = `
Loading\u2026
`;\n try {\n const { projects } = await fetchJson<{ projects: ProjectSummary[] }>(\n `${cfg.apiBase}/v1/projects/mine`,\n );\n if (!projects.length) {\n listEl.innerHTML = renderEmpty();\n } else {\n listEl.innerHTML = projects.map(renderProjectCard).join(\"\");\n }\n } catch (err) {\n listEl.innerHTML = `
Failed to load projects: ${escapeHtml(String(err))}
`;\n }\n}\n\nasync function createProject(cfg: DashboardConfig, body: Record) {\n return fetchJson<{ project: ProjectSummary }>(`${cfg.apiBase}/v1/projects`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n}\n\nasync function archiveProject(cfg: DashboardConfig, id: number) {\n return fetchJson<{ project: ProjectSummary }>(\n `${cfg.apiBase}/v1/projects/${id}/archive`,\n { method: \"POST\" },\n );\n}\n\nfunction attachEvents(cfg: DashboardConfig) {\n cfg.rootEl.addEventListener(\"click\", async (ev) => {\n const target = ev.target as HTMLElement;\n if (target.matches(\".ga-archive-btn\")) {\n const id = parseInt(target.getAttribute(\"data-project-id\") || \"\", 10);\n if (!id) return;\n if (!confirm(\"Archive this project? The GitHub repo will be archived but its history is preserved.\")) return;\n try {\n await archiveProject(cfg, id);\n await loadProjects(cfg);\n } catch (err) {\n alert(\"Archive failed: \" + err);\n }\n }\n });\n\n const form = cfg.rootEl.querySelector(\"#ga-new-project-form\");\n form?.addEventListener(\"submit\", async (ev) => {\n ev.preventDefault();\n const titleEl = cfg.rootEl.querySelector(\"#ga-np-title\");\n const descEl = cfg.rootEl.querySelector(\"#ga-np-description\");\n const engineEl = cfg.rootEl.querySelector(\"#ga-np-engine\");\n const licenseEl = cfg.rootEl.querySelector(\"#ga-np-license\");\n const errEl = cfg.rootEl.querySelector(\"#ga-new-project-error\");\n if (!titleEl || !engineEl || !licenseEl || !errEl) return;\n errEl.classList.add(\"d-none\");\n try {\n await createProject(cfg, {\n title: titleEl.value,\n description: descEl?.value || null,\n engine: engineEl.value,\n license: licenseEl.value,\n });\n titleEl.value = \"\";\n if (descEl) descEl.value = \"\";\n const modalEl = document.getElementById(\"ga-new-project-modal\");\n if (modalEl && window.bootstrap?.Modal) {\n window.bootstrap.Modal.getOrCreateInstance(modalEl).hide();\n }\n await loadProjects(cfg);\n } catch (err) {\n errEl.textContent = \"Create failed: \" + String(err);\n errEl.classList.remove(\"d-none\");\n }\n });\n}\n\nconst GADashboard = {\n async mount(cfg: DashboardConfig & { onUnauthenticated?: () => void }) {\n installClientErrorReporter({ apiBase: cfg.apiBase, page: \"dashboard\" });\n let me: MeResponse | null = null;\n try {\n me = await fetchJson(`${cfg.apiBase}/v1/me`);\n } catch {\n me = null;\n }\n if (!me) {\n cfg.onUnauthenticated?.();\n return;\n }\n cfg.rootEl.querySelector(\"#ga-dashboard-handle\")!.textContent = me.user.handle;\n cfg.rootEl.querySelector(\"#ga-dashboard-address\")!.textContent = me.user.address;\n\n const modalRoot = cfg.rootEl.querySelector(\"#ga-modal-root\");\n if (modalRoot && !modalRoot.innerHTML.trim()) modalRoot.innerHTML = renderModal();\n attachEvents(cfg);\n await loadProjects(cfg);\n await loadWorkspaceTiles(cfg);\n },\n};\n\n/**\n * Workspace tie-together (design brief Step 9, simplified): quiet stat\n * tiles linking to Datasets/Models/Wallet from the project dashboard.\n * Each is best-effort \u2014 a failed fetch leaves that tile's \"\u2026\" rather\n * than blocking the rest of the dashboard.\n */\nasync function loadWorkspaceTiles(cfg: DashboardConfig): Promise {\n const datasetsEl = cfg.rootEl.querySelector(\"#ga-tile-datasets\");\n const modelsEl = cfg.rootEl.querySelector(\"#ga-tile-models\");\n const walletEl = cfg.rootEl.querySelector(\"#ga-tile-wallet\");\n\n if (datasetsEl) {\n try {\n const data = await fetchJson<{ datasets: unknown[] }>(`${cfg.apiBase}/v1/datasets/mine`);\n datasetsEl.textContent = String(data.datasets.length);\n } catch {\n datasetsEl.textContent = \"\u2014\";\n }\n }\n if (modelsEl) {\n try {\n const data = await fetchJson<{ models: unknown[] }>(`${cfg.apiBase}/v1/models/mine`);\n modelsEl.textContent = String(data.models.length);\n } catch {\n modelsEl.textContent = \"\u2014\";\n }\n }\n if (walletEl) {\n try {\n const data = await fetchJson<{ balance: number }>(`${cfg.apiBase}/v1/tokens/account`);\n walletEl.textContent = `${data.balance.toLocaleString()} tokens`;\n } catch {\n walletEl.textContent = \"\u2014\";\n }\n }\n}\n\nwindow.GADashboard = GADashboard;\nexport default GADashboard;\n"], + "mappings": "AAeA,IAAMA,EAAO,IAAI,IACXC,EAAuB,GACzBC,EAAY,GACZC,EAAuD,KAQpD,SAASC,EAA2BC,EAAsC,CAC3EH,IACJA,EAAY,GACZC,EAAaE,EACb,OAAO,iBAAiB,QAAUC,GAAO,CACvC,IAAMC,EACHD,EAAG,OAASA,EAA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,EAAS,YAAc,QACzB,CAEJ,CAEA,OAAO,YAAcP,EACrB,IAAOS,EAAQT", + "names": ["SEEN", "MAX_REPORTS_PER_PAGE", "installed", "configured", "installClientErrorReporter", "cfg", "ev", "message", "stack", "report", "reason", "scrubUrl", "raw", "u", "key", "STATUS_LABELS", "statusBadge", "status", "escapeHtml", "s", "ch", "renderProjectCard", "p", "isArchived", "repoLink", "archiveBtn", "renderEmpty", "renderModal", "fetchJson", "url", "init", "res", "detail", "loadProjects", "cfg", "listEl", "projects", "err", "createProject", "body", "archiveProject", "id", "attachEvents", "ev", "target", "titleEl", "descEl", "engineEl", "licenseEl", "errEl", "modalEl", "GADashboard", "installClientErrorReporter", "me", "modalRoot", "loadWorkspaceTiles", "datasetsEl", "modelsEl", "walletEl", "data", "dashboard_default"] } diff --git a/assets/js/ga-datasets.js b/assets/js/ga-datasets.js new file mode 100644 index 0000000..f214cd3 --- /dev/null +++ b/assets/js/ga-datasets.js @@ -0,0 +1,21 @@ +var T=Object.defineProperty;var L=(s,t,e)=>t in s?T(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var c=(s,t,e)=>L(s,typeof t!="symbol"?t+"":t,e);var m=new Set,w=10,v=!1,u=null;function y(s){v||(v=!0,u=s,window.addEventListener("error",t=>{let e=t.error&&t.error.message||t.message||"unknown_error",a=t.error&&t.error.stack||`${t.filename??""}:${t.lineno??0}:${t.colno??0}`;b(e,a)}),window.addEventListener("unhandledrejection",t=>{let e=t.reason,a=e instanceof Error?e.message:typeof e=="string"?e:"unhandled_rejection",i=e instanceof Error?e.stack??"":"";b(a,i)}))}function _(s){try{let t=new URL(s,location.origin);return`${t.origin}${t.pathname}`.slice(0,200)}catch{return s.split("?")[0].split("#")[0].slice(0,200)}}async function b(s,t){if(!u||m.size>=w)return;let e=`${s}::${t.slice(0,80)}`;if(!m.has(e)){m.add(e);try{await fetch(`${u.apiBase}/v1/internal/client-error`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:String(s).slice(0,500),stack:String(t).slice(0,4e3),page:u.page,url:_(location.href),ts:Date.now()}),keepalive:!0})}catch{}}}var g={"flux-dev":{label:"FLUX.1 [dev]"}};function n(s){return s.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}async function l(s,t){let e=await fetch(s,{credentials:"include",...t});if(!e.ok){let a="";try{a=JSON.stringify(await e.json())}catch{}throw new Error(`${e.status}: ${a||e.statusText}`)}return await e.json()}function S(s){return new Promise((t,e)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=()=>e(a.error??new Error("file read failed")),a.readAsDataURL(s)})}var E={own:"My own work",licensed:"Licensed to me",public_domain:"Public domain / CC0"};function H(s){return` + +
+

${n(s.title)}

+

${n(s.description||"No description yet.")}

+

${s.item_count} item${s.item_count===1?"":"s"} \xB7 ${n(E[s.rights_declaration]||s.rights_declaration)} \xB7 ${n(s.visibility)}

+
+
`}var p=class{constructor(){c(this,"cfg")}async mount(t){this.cfg=t;let e=null;try{e=await l(`${t.apiBase}/v1/me`)}catch{e=null}if(!e){t.onUnauthenticated?.();return}await this.loadDatasets(),this.attachEvents()}async loadDatasets(){let t=this.cfg.rootEl.querySelector("#ga-datasets-list");if(t)try{let e=await l(`${this.cfg.apiBase}/v1/datasets/mine`);t.innerHTML=e.datasets.length?e.datasets.map(H).join(""):'

No datasets yet. Your source material stays private \u2014 only the models you publish are public.

'}catch(e){t.innerHTML=`
Failed to load: ${n(String(e))}
`}}attachEvents(){this.cfg.rootEl.querySelector("#ga-new-dataset-form")?.addEventListener("submit",async e=>{e.preventDefault();let a=this.cfg.rootEl.querySelector("#ga-new-dataset-error");a?.classList.add("d-none");let i=this.cfg.rootEl.querySelector("#ga-nd-title").value.trim(),d=this.cfg.rootEl.querySelector("#ga-nd-description").value.trim(),r=this.cfg.rootEl.querySelector("#ga-nd-rights").value;try{let o=await l(`${this.cfg.apiBase}/v1/datasets`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:i,description:d||void 0,rights_declaration:r})});window.location.href=`/datasets/detail/?slug=${encodeURIComponent(o.dataset.slug)}`}catch(o){a&&(a.textContent=`Couldn't create dataset: ${String(o)}`,a.classList.remove("d-none"))}})}},h=class{constructor(){c(this,"cfg");c(this,"slug","");c(this,"dataset",null);c(this,"pollTimer",null)}async mount(t){this.cfg=t;let e=new URLSearchParams(window.location.search);if(this.slug=e.get("slug")||"",!this.slug){t.rootEl.innerHTML='

Bad URL \u2014 dataset pages look like /datasets/detail/?slug=your-dataset.

';return}try{let a=await l(`${t.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`);this.dataset=a.dataset}catch(a){if((a.message.startsWith("404")?404:0)===404){t.onUnauthenticated?.();return}t.rootEl.innerHTML=`

Failed to load dataset: ${n(String(a))}

`;return}this.renderHeader(),this.populateBaseModelOptions(),await this.loadItems(),await this.loadTrainingJobs(),this.attachEvents()}renderHeader(){let t=this.dataset,e=this.cfg.rootEl;e.querySelector("#ga-dataset-title").textContent=t.title,e.querySelector("#ga-dataset-desc").textContent=t.description||"No curatorial statement yet.",e.querySelector("#ga-dataset-meta").textContent=`${t.item_count} item${t.item_count===1?"":"s"} \xB7 ${E[t.rights_declaration]||t.rights_declaration} \xB7 ${t.visibility}`;let a=e.querySelector("#ga-train-submit");a&&(a.disabled=t.item_count<5);let i=e.querySelector("#ga-train-min-hint");i&&i.classList.toggle("d-none",t.item_count>=5)}populateBaseModelOptions(){let t=this.cfg.rootEl.querySelector("#ga-train-base-model");t&&(t.innerHTML=Object.entries(g).map(([e,a])=>``).join(""))}async loadItems(){let t=this.cfg.rootEl.querySelector("#ga-dataset-items");if(t)try{let e=await l(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items?limit=100`);t.innerHTML=e.items.length?e.items.map(a=>this.renderItem(a)).join(""):'

No items yet \u2014 drop images or video below.

'}catch(e){t.innerHTML=`
Failed to load items: ${n(String(e))}
`}}renderItem(t){let e=`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items/${t.id}/file`,a=t.status==="flagged",i=t.kind==="image"?`${n(t.caption||`:``;return` +
+ ${i} + ${a?`

${n(t.flag_reason||"flagged")}

`:""} + +
`}async loadTrainingJobs(){let t=this.cfg.rootEl.querySelector("#ga-training-jobs");if(t)try{let e=await l(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/training`);t.innerHTML=e.jobs.length?e.jobs.map(i=>this.renderTrainingJob(i)).join(""):'

No training runs yet.

';let a=e.jobs.some(i=>i.status==="queued"||i.status==="training");a&&!this.pollTimer?this.pollTimer=setInterval(()=>void this.loadTrainingJobs(),4e3):!a&&this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}catch(e){t.innerHTML=`
Failed to load: ${n(String(e))}
`}}renderTrainingJob(t){let e=g[t.base_model]?.label??t.base_model,a=new Date(t.created_at*1e3).toLocaleString(),i;return t.status==="succeeded"&&t.model_id?i=`View model \u2192`:t.status==="failed"?i=`Failed (${n(t.error_code||"unknown")}) \u2014 ${t.price_tokens} tokens refunded`:i="In progress\u2026",` +
  • +
    + ${n(e)} \xB7 ${n(t.training_method)} + ${n(t.status)} +
    +

    ${n(a)} \xB7 ${i}

    +
  • `}feedback(t,e){let a=this.cfg.rootEl.querySelector(t);a&&(a.textContent=e)}async uploadFiles(t){this.feedback("#ga-upload-feedback",`Uploading ${t.length} item(s)\u2026`);let e=0,a=0,i=0;for(let r of Array.from(t))try{let o=await S(r),f=await fetch(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({data_url:o})});f.status===201?e++:f.status===200?a++:i++}catch{i++}this.feedback("#ga-upload-feedback",`${e} added, ${a} duplicate${a===1?"":"s"} skipped, ${i} failed.`);let d=await l(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`);this.dataset=d.dataset,this.renderHeader(),await this.loadItems()}async deleteItem(t){if(confirm("Remove this item from the dataset?"))try{await l(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items/${t}`,{method:"DELETE"});let e=await l(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`);this.dataset=e.dataset,this.renderHeader(),await this.loadItems()}catch(e){alert(`Failed to remove item: ${e}`)}}async submitTraining(){let t=this.cfg.rootEl,e=t.querySelector("#ga-train-error");e?.classList.add("d-none");let a=t.querySelector("#ga-train-base-model").value,i=t.querySelector("#ga-train-method").value,d=parseInt(t.querySelector("#ga-train-render-price").value,10)||25,r=t.querySelector("#ga-train-submit");r&&(r.disabled=!0,r.textContent="Starting\u2026");try{await l(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/train`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({base_model:a,training_method:i,render_price_tokens:d})}),await this.loadTrainingJobs()}catch(o){e&&(e.textContent=`Couldn't start training: ${String(o)}`,e.classList.remove("d-none"))}finally{r&&(r.disabled=(this.dataset?.item_count??0)<5,r.textContent="Train")}}attachEvents(){let t=this.cfg.rootEl,e=t.querySelector("#ga-dataset-dropzone"),a=t.querySelector("#ga-dataset-file-input");e?.addEventListener("click",()=>a?.click()),a?.addEventListener("change",()=>{a.files?.length&&this.uploadFiles(a.files)}),e?.addEventListener("dragover",i=>{i.preventDefault(),e.classList.add("ga-dragover")}),e?.addEventListener("dragleave",()=>e.classList.remove("ga-dragover")),e?.addEventListener("drop",i=>{i.preventDefault(),e.classList.remove("ga-dragover"),i.dataTransfer?.files.length&&this.uploadFiles(i.dataTransfer.files)}),t.addEventListener("click",i=>{let r=i.target.closest(".ga-item-delete");if(r){let o=parseInt(r.dataset.itemId||"",10);o&&this.deleteItem(o)}}),t.querySelector("#ga-train-form")?.addEventListener("submit",i=>{i.preventDefault(),this.submitTraining()})}},$={async mount(s){y({apiBase:s.apiBase,page:`datasets-${s.mode}`}),s.mode==="library"?await new p().mount(s):await new h().mount(s)}};window.GADatasets=$;var R=$;export{R as default}; +//# sourceMappingURL=ga-datasets.js.map diff --git a/assets/js/ga-datasets.js.map b/assets/js/ga-datasets.js.map new file mode 100644 index 0000000..b0126f5 --- /dev/null +++ b/assets/js/ga-datasets.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../workers/api/client/lib/clientErrors.ts", "../../workers/api/client/lib/trainableBaseModels.ts", "../../workers/api/client/datasets.ts"], + "sourcesContent": ["// Window onerror / unhandledrejection \u2192 POST /v1/internal/client-error.\n// Per-page de-dupe and 10-report cap; the Worker rate-limits per IP\n// and forwards to Sentry via SENTRY_DSN_PUBLIC server-side.\n//\n// Why not @sentry/browser? Bundle size is the deciding factor:\n// @sentry/browser min+gz is ~25KB, which is larger than every\n// per-page bundle this app ships (galleries 18KB, studio 100KB,\n// dashboard 7KB). The proxy pattern below has equivalent delivery\n// (the worker uses ctx.waitUntil for the forward), preserves stack\n// fidelity (we POST the raw `Error.stack` string verbatim), and\n// keeps the public DSN out of the client where it would otherwise\n// be visible to scrapers. The trade-off is that we don't get the\n// SDK's auto-capture of breadcrumbs / fetch/console hooks; for v1\n// observability that's an acceptable gap given the size budget.\n\nconst SEEN = new Set();\nconst MAX_REPORTS_PER_PAGE = 10;\nlet installed = false;\nlet configured: { apiBase: string; page: string } | null = null;\n\nexport interface ClientErrorReporterConfig {\n apiBase: string;\n /** Short page identifier \u2014 \"studio\", \"dashboard\", \"galleries\" etc. */\n page: string;\n}\n\nexport function installClientErrorReporter(cfg: ClientErrorReporterConfig): void {\n if (installed) return;\n installed = true;\n configured = cfg;\n window.addEventListener(\"error\", (ev) => {\n const message =\n (ev.error && ev.error.message) || ev.message || \"unknown_error\";\n const stack =\n (ev.error && ev.error.stack) ||\n `${ev.filename ?? \"\"}:${ev.lineno ?? 0}:${ev.colno ?? 0}`;\n void report(message, stack);\n });\n window.addEventListener(\"unhandledrejection\", (ev) => {\n const reason = (ev as PromiseRejectionEvent).reason;\n const message =\n reason instanceof Error\n ? reason.message\n : typeof reason === \"string\"\n ? reason\n : \"unhandled_rejection\";\n const stack = reason instanceof Error ? reason.stack ?? \"\" : \"\";\n void report(message, stack);\n });\n}\n\n// PII scrub: strip query string and hash from any URL we forward\n// so signed-upload tokens, ?email=, ?invite=, fragment-encoded\n// session bits, etc. never leave the browser. Also caps length.\nfunction scrubUrl(raw: string): string {\n try {\n const u = new URL(raw, location.origin);\n return `${u.origin}${u.pathname}`.slice(0, 200);\n } catch {\n return raw.split(\"?\")[0].split(\"#\")[0].slice(0, 200);\n }\n}\n\nasync function report(message: string, stack: string): Promise {\n if (!configured) return;\n // Per-page de-dupe + cap so a hot-loop error doesn't DoS the\n // /v1/internal/client-error endpoint.\n if (SEEN.size >= MAX_REPORTS_PER_PAGE) return;\n const key = `${message}::${stack.slice(0, 80)}`;\n if (SEEN.has(key)) return;\n SEEN.add(key);\n\n try {\n await fetch(`${configured.apiBase}/v1/internal/client-error`, {\n method: \"POST\",\n credentials: \"include\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n message: String(message).slice(0, 500),\n stack: String(stack).slice(0, 4000),\n page: configured.page,\n url: scrubUrl(location.href),\n ts: Date.now(),\n }),\n keepalive: true,\n });\n } catch {\n // never escalate a reporter failure into another error event\n }\n}\n", "// Client-side mirror of TRAINABLE_BASE_MODELS in src/ai/training.ts.\n// Duplicated rather than imported because client/ bundles separately\n// from src/ (different esbuild entry points, no shared runtime) \u2014 this\n// is presentation-only (label text for the base-model picker); the\n// SERVER remains the source of truth and re-validates every value on\n// POST /v1/datasets/:slug/train regardless of what this list offers.\n// Keep in sync by hand when a new base model is verified end-to-end.\nexport interface TrainableBase {\n label: string;\n}\n\nexport const TRAINABLE_BASE_MODELS: Record = {\n \"flux-dev\": { label: \"FLUX.1 [dev]\" },\n};\n", "/**\n * /datasets/ \u2014 the Dataset Library: a creator's own curated\n * images/video, private by default.\n * /datasets/detail/?slug=X \u2014 one dataset: item grid, upload/import,\n * and the train-a-model flow that turns it into a fal_custom render\n * model version.\n *\n * Two Jekyll pages share this module (query-string routed like\n * /models/detail/?slug=X) \u2014 mount() reads cfg.mode to pick which one.\n */\nimport { installClientErrorReporter } from \"./lib/clientErrors\";\nimport { TRAINABLE_BASE_MODELS } from \"./lib/trainableBaseModels\";\n\ninterface DatasetsConfig {\n apiBase: string;\n rootEl: HTMLElement;\n mode: \"library\" | \"detail\";\n onUnauthenticated?: () => void;\n}\n\ninterface Dataset {\n id: number;\n slug: string;\n title: string;\n description: string | null;\n rights_declaration: string;\n visibility: string;\n item_count: number;\n created_at: number;\n updated_at: number;\n}\n\ninterface DatasetItem {\n id: number;\n kind: string;\n caption: string | null;\n byte_size: number;\n width: number | null;\n height: number | null;\n duration_seconds: number | null;\n status: string;\n flag_reason: string | null;\n created_at: number;\n}\n\ninterface TrainingJob {\n id: number;\n dataset_id: number;\n base_model: string;\n training_method: string;\n price_tokens: number;\n render_price_tokens: number;\n status: string;\n model_id: number | null;\n model_version_id: number | null;\n error_code: string | null;\n created_at: number;\n started_at: number | null;\n finished_at: number | null;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\": return \"&\";\n case \"<\": return \"<\";\n case \">\": return \">\";\n case '\"': return \""\";\n default: return \"'\";\n }\n });\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise {\n const res = await fetch(url, { credentials: \"include\", ...init });\n if (!res.ok) {\n let detail = \"\";\n try { detail = JSON.stringify(await res.json()); } catch {}\n throw new Error(`${res.status}: ${detail || res.statusText}`);\n }\n return (await res.json()) as T;\n}\n\nfunction readFileAsDataUrl(file: File): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = () => reject(reader.error ?? new Error(\"file read failed\"));\n reader.readAsDataURL(file);\n });\n}\n\nconst RIGHTS_LABELS: Record = {\n own: \"My own work\",\n licensed: \"Licensed to me\",\n public_domain: \"Public domain / CC0\",\n};\n\nfunction renderDatasetCard(d: Dataset): string {\n return `\n \n
    \n

    ${escapeHtml(d.title)}

    \n

    ${escapeHtml(d.description || \"No description yet.\")}

    \n

    ${d.item_count} item${d.item_count === 1 ? \"\" : \"s\"} \u00B7 ${escapeHtml(RIGHTS_LABELS[d.rights_declaration] || d.rights_declaration)} \u00B7 ${escapeHtml(d.visibility)}

    \n
    \n
    `;\n}\n\n// ---------------------------------------------------------------------------\n// Library page\n// ---------------------------------------------------------------------------\n\nclass LibraryPage {\n private cfg!: DatasetsConfig;\n\n async mount(cfg: DatasetsConfig): Promise {\n this.cfg = cfg;\n let me: unknown = null;\n try {\n me = await fetchJson(`${cfg.apiBase}/v1/me`);\n } catch {\n me = null;\n }\n if (!me) {\n cfg.onUnauthenticated?.();\n return;\n }\n await this.loadDatasets();\n this.attachEvents();\n }\n\n private async loadDatasets(): Promise {\n const el = this.cfg.rootEl.querySelector(\"#ga-datasets-list\");\n if (!el) return;\n try {\n const data = await fetchJson<{ datasets: Dataset[] }>(`${this.cfg.apiBase}/v1/datasets/mine`);\n el.innerHTML = data.datasets.length\n ? data.datasets.map(renderDatasetCard).join(\"\")\n : `

    No datasets yet. Your source material stays private \u2014 only the models you publish are public.

    `;\n } catch (err) {\n el.innerHTML = `
    Failed to load: ${escapeHtml(String(err))}
    `;\n }\n }\n\n private attachEvents(): void {\n const form = this.cfg.rootEl.querySelector(\"#ga-new-dataset-form\");\n form?.addEventListener(\"submit\", async (ev) => {\n ev.preventDefault();\n const errEl = this.cfg.rootEl.querySelector(\"#ga-new-dataset-error\");\n errEl?.classList.add(\"d-none\");\n const title = this.cfg.rootEl.querySelector(\"#ga-nd-title\")!.value.trim();\n const description = this.cfg.rootEl.querySelector(\"#ga-nd-description\")!.value.trim();\n const rights = this.cfg.rootEl.querySelector(\"#ga-nd-rights\")!.value;\n try {\n const data = await fetchJson<{ dataset: Dataset }>(`${this.cfg.apiBase}/v1/datasets`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ title, description: description || undefined, rights_declaration: rights }),\n });\n window.location.href = `/datasets/detail/?slug=${encodeURIComponent(data.dataset.slug)}`;\n } catch (err) {\n if (errEl) {\n errEl.textContent = `Couldn't create dataset: ${String(err)}`;\n errEl.classList.remove(\"d-none\");\n }\n }\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Detail page\n// ---------------------------------------------------------------------------\n\nclass DetailPage {\n private cfg!: DatasetsConfig;\n private slug = \"\";\n private dataset: Dataset | null = null;\n private pollTimer: ReturnType | null = null;\n\n async mount(cfg: DatasetsConfig): Promise {\n this.cfg = cfg;\n const params = new URLSearchParams(window.location.search);\n this.slug = params.get(\"slug\") || \"\";\n if (!this.slug) {\n cfg.rootEl.innerHTML = `

    Bad URL \u2014 dataset pages look like /datasets/detail/?slug=your-dataset.

    `;\n return;\n }\n try {\n const data = await fetchJson<{ dataset: Dataset }>(`${cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`);\n this.dataset = data.dataset;\n } catch (err) {\n const status = (err as Error).message.startsWith(\"404\") ? 404 : 0;\n if (status === 404) {\n cfg.onUnauthenticated?.();\n return;\n }\n cfg.rootEl.innerHTML = `

    Failed to load dataset: ${escapeHtml(String(err))}

    `;\n return;\n }\n\n this.renderHeader();\n this.populateBaseModelOptions();\n await this.loadItems();\n await this.loadTrainingJobs();\n this.attachEvents();\n }\n\n private renderHeader(): void {\n const d = this.dataset!;\n const root = this.cfg.rootEl;\n root.querySelector(\"#ga-dataset-title\")!.textContent = d.title;\n root.querySelector(\"#ga-dataset-desc\")!.textContent = d.description || \"No curatorial statement yet.\";\n root.querySelector(\"#ga-dataset-meta\")!.textContent =\n `${d.item_count} item${d.item_count === 1 ? \"\" : \"s\"} \u00B7 ${RIGHTS_LABELS[d.rights_declaration] || d.rights_declaration} \u00B7 ${d.visibility}`;\n const trainBtn = root.querySelector(\"#ga-train-submit\");\n if (trainBtn) trainBtn.disabled = d.item_count < 5;\n const trainHint = root.querySelector(\"#ga-train-min-hint\");\n if (trainHint) trainHint.classList.toggle(\"d-none\", d.item_count >= 5);\n }\n\n private populateBaseModelOptions(): void {\n const sel = this.cfg.rootEl.querySelector(\"#ga-train-base-model\");\n if (!sel) return;\n sel.innerHTML = Object.entries(TRAINABLE_BASE_MODELS)\n .map(([key, base]) => ``)\n .join(\"\");\n }\n\n private async loadItems(): Promise {\n const grid = this.cfg.rootEl.querySelector(\"#ga-dataset-items\");\n if (!grid) return;\n try {\n const data = await fetchJson<{ items: DatasetItem[] }>(\n `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items?limit=100`,\n );\n grid.innerHTML = data.items.length\n ? data.items.map((i) => this.renderItem(i)).join(\"\")\n : `

    No items yet \u2014 drop images or video below.

    `;\n } catch (err) {\n grid.innerHTML = `
    Failed to load items: ${escapeHtml(String(err))}
    `;\n }\n }\n\n private renderItem(i: DatasetItem): string {\n const fileUrl = `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items/${i.id}/file`;\n const flagged = i.status === \"flagged\";\n const thumb = i.kind === \"image\"\n ? `\"${escapeHtml(i.caption`\n : ``;\n return `\n
    \n ${thumb}\n ${flagged ? `

    ${escapeHtml(i.flag_reason || \"flagged\")}

    ` : \"\"}\n \n
    `;\n }\n\n private async loadTrainingJobs(): Promise {\n const el = this.cfg.rootEl.querySelector(\"#ga-training-jobs\");\n if (!el) return;\n try {\n const data = await fetchJson<{ jobs: TrainingJob[] }>(\n `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/training`,\n );\n el.innerHTML = data.jobs.length\n ? data.jobs.map((j) => this.renderTrainingJob(j)).join(\"\")\n : `

    No training runs yet.

    `;\n // Poll while any job is still in flight \u2014 training is genuinely\n // async at the provider (minutes to hours in production; instant\n // under TRAINING_MOCK).\n const inFlight = data.jobs.some((j) => j.status === \"queued\" || j.status === \"training\");\n if (inFlight && !this.pollTimer) {\n this.pollTimer = setInterval(() => void this.loadTrainingJobs(), 4000);\n } else if (!inFlight && this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n } catch (err) {\n el.innerHTML = `
    Failed to load: ${escapeHtml(String(err))}
    `;\n }\n }\n\n private renderTrainingJob(j: TrainingJob): string {\n const base = TRAINABLE_BASE_MODELS[j.base_model]?.label ?? j.base_model;\n const when = new Date(j.created_at * 1000).toLocaleString();\n let statusLine: string;\n if (j.status === \"succeeded\" && j.model_id) {\n statusLine = `View model \u2192`;\n } else if (j.status === \"failed\") {\n statusLine = `Failed (${escapeHtml(j.error_code || \"unknown\")}) \u2014 ${j.price_tokens} tokens refunded`;\n } else {\n statusLine = \"In progress\u2026\";\n }\n return `\n
  • \n
    \n ${escapeHtml(base)} \u00B7 ${escapeHtml(j.training_method)}\n ${escapeHtml(j.status)}\n
    \n

    ${escapeHtml(when)} \u00B7 ${statusLine}

    \n
  • `;\n }\n\n private feedback(id: string, msg: string): void {\n const el = this.cfg.rootEl.querySelector(id);\n if (el) el.textContent = msg;\n }\n\n private async uploadFiles(files: FileList): Promise {\n this.feedback(\"#ga-upload-feedback\", `Uploading ${files.length} item(s)\u2026`);\n let ok = 0;\n let dup = 0;\n let failed = 0;\n for (const file of Array.from(files)) {\n try {\n const dataUrl = await readFileAsDataUrl(file);\n const res = await fetch(\n `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items`,\n {\n method: \"POST\",\n credentials: \"include\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ data_url: dataUrl }),\n },\n );\n if (res.status === 201) ok++;\n else if (res.status === 200) dup++;\n else failed++;\n } catch {\n failed++;\n }\n }\n this.feedback(\n \"#ga-upload-feedback\",\n `${ok} added, ${dup} duplicate${dup === 1 ? \"\" : \"s\"} skipped, ${failed} failed.`,\n );\n const fresh = await fetchJson<{ dataset: Dataset }>(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`);\n this.dataset = fresh.dataset;\n this.renderHeader();\n await this.loadItems();\n }\n\n private async deleteItem(itemId: number): Promise {\n if (!confirm(\"Remove this item from the dataset?\")) return;\n try {\n await fetchJson(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items/${itemId}`, {\n method: \"DELETE\",\n });\n const fresh = await fetchJson<{ dataset: Dataset }>(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`);\n this.dataset = fresh.dataset;\n this.renderHeader();\n await this.loadItems();\n } catch (err) {\n alert(`Failed to remove item: ${err}`);\n }\n }\n\n private async submitTraining(): Promise {\n const root = this.cfg.rootEl;\n const errEl = root.querySelector(\"#ga-train-error\");\n errEl?.classList.add(\"d-none\");\n const baseModel = root.querySelector(\"#ga-train-base-model\")!.value;\n const method = root.querySelector(\"#ga-train-method\")!.value;\n const renderPrice = parseInt(root.querySelector(\"#ga-train-render-price\")!.value, 10) || 25;\n const btn = root.querySelector(\"#ga-train-submit\");\n if (btn) { btn.disabled = true; btn.textContent = \"Starting\u2026\"; }\n try {\n await fetchJson(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/train`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ base_model: baseModel, training_method: method, render_price_tokens: renderPrice }),\n });\n await this.loadTrainingJobs();\n } catch (err) {\n if (errEl) {\n errEl.textContent = `Couldn't start training: ${String(err)}`;\n errEl.classList.remove(\"d-none\");\n }\n } finally {\n if (btn) { btn.disabled = (this.dataset?.item_count ?? 0) < 5; btn.textContent = \"Train\"; }\n }\n }\n\n private attachEvents(): void {\n const root = this.cfg.rootEl;\n const dropzone = root.querySelector(\"#ga-dataset-dropzone\");\n const fileInput = root.querySelector(\"#ga-dataset-file-input\");\n dropzone?.addEventListener(\"click\", () => fileInput?.click());\n fileInput?.addEventListener(\"change\", () => {\n if (fileInput.files?.length) void this.uploadFiles(fileInput.files);\n });\n dropzone?.addEventListener(\"dragover\", (ev) => {\n ev.preventDefault();\n dropzone.classList.add(\"ga-dragover\");\n });\n dropzone?.addEventListener(\"dragleave\", () => dropzone.classList.remove(\"ga-dragover\"));\n dropzone?.addEventListener(\"drop\", (ev) => {\n ev.preventDefault();\n dropzone.classList.remove(\"ga-dragover\");\n if (ev.dataTransfer?.files.length) void this.uploadFiles(ev.dataTransfer.files);\n });\n\n root.addEventListener(\"click\", (ev) => {\n const target = ev.target as HTMLElement;\n const delBtn = target.closest(\".ga-item-delete\");\n if (delBtn) {\n const id = parseInt(delBtn.dataset.itemId || \"\", 10);\n if (id) void this.deleteItem(id);\n }\n });\n\n root.querySelector(\"#ga-train-form\")?.addEventListener(\"submit\", (ev) => {\n ev.preventDefault();\n void this.submitTraining();\n });\n }\n}\n\nconst GADatasets = {\n async mount(cfg: DatasetsConfig) {\n installClientErrorReporter({ apiBase: cfg.apiBase, page: `datasets-${cfg.mode}` });\n if (cfg.mode === \"library\") await new LibraryPage().mount(cfg);\n else await new DetailPage().mount(cfg);\n },\n};\n\ndeclare global {\n interface Window {\n GADatasets?: typeof GADatasets;\n }\n}\n\nwindow.GADatasets = GADatasets;\nexport default GADatasets;\n"], + "mappings": "oKAeA,IAAMA,EAAO,IAAI,IACXC,EAAuB,GACzBC,EAAY,GACZC,EAAuD,KAQpD,SAASC,EAA2BC,EAAsC,CAC3EH,IACJA,EAAY,GACZC,EAAaE,EACb,OAAO,iBAAiB,QAAUC,GAAO,CACvC,IAAMC,EACHD,EAAG,OAASA,EAAG,MAAM,SAAYA,EAAG,SAAW,gBAC5CE,EACHF,EAAG,OAASA,EAAG,MAAM,OACtB,GAAGA,EAAG,UAAY,EAAE,IAAIA,EAAG,QAAU,CAAC,IAAIA,EAAG,OAAS,CAAC,GACpDG,EAAOF,EAASC,CAAK,CAC5B,CAAC,EACD,OAAO,iBAAiB,qBAAuBF,GAAO,CACpD,IAAMI,EAAUJ,EAA6B,OACvCC,EACJG,aAAkB,MACdA,EAAO,QACP,OAAOA,GAAW,SAClBA,EACA,sBACAF,EAAQE,aA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C,GAAO,CAC7CA,EAAG,eAAe,EAClBoC,EAAS,UAAU,IAAI,aAAa,CACtC,CAAC,EACDA,GAAU,iBAAiB,YAAa,IAAMA,EAAS,UAAU,OAAO,aAAa,CAAC,EACtFA,GAAU,iBAAiB,OAASpC,GAAO,CACzCA,EAAG,eAAe,EAClBoC,EAAS,UAAU,OAAO,aAAa,EACnCpC,EAAG,cAAc,MAAM,QAAa,KAAK,YAAYA,EAAG,aAAa,KAAK,CAChF,CAAC,EAEDO,EAAK,iBAAiB,QAAUP,GAAO,CAErC,IAAMsC,EADStC,EAAG,OACI,QAA2B,iBAAiB,EAClE,GAAIsC,EAAQ,CACV,IAAMf,EAAK,SAASe,EAAO,QAAQ,QAAU,GAAI,EAAE,EAC/Cf,GAAS,KAAK,WAAWA,CAAE,CACjC,CACF,CAAC,EAEDhB,EAAK,cAA+B,gBAAgB,GAAG,iBAAiB,SAAWP,GAAO,CACxFA,EAAG,eAAe,EACb,KAAK,eAAe,CAC3B,CAAC,CACH,CACF,EAEMuC,EAAa,CACjB,MAAM,MAAM5C,EAAqB,CAC/B6C,EAA2B,CAAE,QAAS7C,EAAI,QAAS,KAAM,YAAYA,EAAI,IAAI,EAAG,CAAC,EAC7EA,EAAI,OAAS,UAAW,MAAM,IAAIF,EAAY,EAAE,MAAME,CAAG,EACxD,MAAM,IAAIU,EAAW,EAAE,MAAMV,CAAG,CACvC,CACF,EAQA,OAAO,WAAa4C,EACpB,IAAOE,EAAQF", + "names": ["SEEN", "MAX_REPORTS_PER_PAGE", "installed", "configured", "installClientErrorReporter", "cfg", "ev", "message", "stack", "report", "reason", "scrubUrl", "raw", "u", "key", "TRAINABLE_BASE_MODELS", "escapeHtml", "ch", "fetchJson", "url", "init", "res", "detail", "readFileAsDataUrl", "file", "resolve", "reject", "reader", "RIGHTS_LABELS", "renderDatasetCard", "d", "LibraryPage", "__publicField", "cfg", "me", "el", "data", "err", "ev", "errEl", "title", "description", "rights", "DetailPage", "params", "root", "trainBtn", "trainHint", "sel", "TRAINABLE_BASE_MODELS", "key", "base", "grid", "i", "fileUrl", "flagged", "thumb", "j", "inFlight", "when", "statusLine", "id", "msg", "files", "ok", "dup", "failed", "dataUrl", "fresh", "itemId", "baseModel", "method", "renderPrice", "btn", "dropzone", "fileInput", "delBtn", "GADatasets", "installClientErrorReporter", "datasets_default"] +} diff --git a/assets/js/ga-models.js b/assets/js/ga-models.js new file mode 100644 index 0000000..40e6341 --- /dev/null +++ b/assets/js/ga-models.js @@ -0,0 +1,20 @@ +var T=Object.defineProperty;var $=(n,e,t)=>e in n?T(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var d=(n,e,t)=>$(n,typeof e!="symbol"?e+"":e,t);var g=new Set,w=10,v=!1,m=null;function y(n){v||(v=!0,m=n,window.addEventListener("error",e=>{let t=e.error&&e.error.message||e.message||"unknown_error",r=e.error&&e.error.stack||`${e.filename??""}:${e.lineno??0}:${e.colno??0}`;f(t,r)}),window.addEventListener("unhandledrejection",e=>{let t=e.reason,r=t instanceof Error?t.message:typeof t=="string"?t:"unhandled_rejection",o=t instanceof Error?t.stack??"":"";f(r,o)}))}function k(n){try{let e=new URL(n,location.origin);return`${e.origin}${e.pathname}`.slice(0,200)}catch{return n.split("?")[0].split("#")[0].slice(0,200)}}async function f(n,e){if(!m||g.size>=w)return;let t=`${n}::${e.slice(0,80)}`;if(!g.has(t)){g.add(t);try{await fetch(`${m.apiBase}/v1/internal/client-error`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:String(n).slice(0,500),stack:String(e).slice(0,4e3),page:m.page,url:k(location.href),ts:Date.now()}),keepalive:!0})}catch{}}}function s(n){return n.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}async function c(n,e){let t=await fetch(n,{credentials:"include",...e});if(!t.ok){let r="";try{r=JSON.stringify(await t.json())}catch{}throw new Error(`${t.status}: ${r||t.statusText}`)}return await t.json()}var L={code:"Code",image:"Image"},_={anthropic:"Claude",workers_ai:"Workers AI",fal_custom:"Custom-trained",mock:"Mock"};function H(n){if(!n.base_model)return"";let e=n.training_method?` \xB7 ${s(n.training_method)}`:"";return`${s(n.base_model)}${e}`}function E(n){let e=n.owner?`@${s(n.owner.handle)}`:"",t=n.latest_price_tokens!==null?`${n.latest_price_tokens.toLocaleString()} tokens / run`:"unpublished";return` + +
    +

    ${s(L[n.kind]||n.kind)} \xB7 ${s(_[n.provider]||n.provider)}

    +

    ${s(n.title)}

    +

    ${s(n.description||"No description yet.")}

    +

    ${s(t)} \xB7 ${n.run_count} run${n.run_count===1?"":"s"}

    + ${e} +
    +
    `}function M(){return'

    No models yet.

    '}var p=class{constructor(){d(this,"cfg");d(this,"isAuthed",!1)}async mount(e){this.cfg=e;try{await c(`${e.apiBase}/v1/me`),this.isAuthed=!0}catch{this.isAuthed=!1}let t=e.rootEl.querySelector("#ga-models-mine-section");t&&t.classList.toggle("d-none",!this.isAuthed),await this.loadCatalogue(),this.isAuthed&&await this.loadMine(),this.attachEvents()}async loadCatalogue(e){let t=this.cfg.rootEl.querySelector("#ga-models-catalogue");if(t){t.innerHTML='
    Loading\u2026
    ';try{let r=e?`?kind=${encodeURIComponent(e)}`:"",o=await c(`${this.cfg.apiBase}/v1/models${r}`);t.innerHTML=o.models.length?o.models.map(E).join(""):M()}catch(r){t.innerHTML=`
    Failed to load: ${s(String(r))}
    `}}}async loadMine(){let e=this.cfg.rootEl.querySelector("#ga-models-mine");if(e)try{let t=await c(`${this.cfg.apiBase}/v1/models/mine`);e.innerHTML=t.models.length?t.models.map(E).join(""):M()}catch(t){e.innerHTML=`
    Failed to load: ${s(String(t))}
    `}}attachEvents(){this.cfg.rootEl.querySelectorAll("[data-ga-kind-filter]").forEach(t=>{t.addEventListener("click",()=>{this.cfg.rootEl.querySelectorAll("[data-ga-kind-filter]").forEach(o=>o.classList.toggle("active",o===t));let r=t.dataset.gaKindFilter||"";this.loadCatalogue(r||void 0)})}),this.cfg.rootEl.querySelector("#ga-new-model-form")?.addEventListener("submit",async t=>{t.preventDefault();let r=this.cfg.rootEl.querySelector("#ga-new-model-error");r?.classList.add("d-none");let o=this.cfg.rootEl.querySelector("#ga-nm-title").value.trim(),a=this.cfg.rootEl.querySelector("#ga-nm-kind").value,l=this.cfg.rootEl.querySelector("#ga-nm-provider").value,u=this.cfg.rootEl.querySelector("#ga-nm-description").value.trim();try{let i=await c(`${this.cfg.apiBase}/v1/models`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:o,kind:a,provider:l,description:u||void 0,visibility:"private"})});window.location.href=`/models/detail/?slug=${encodeURIComponent(i.model.slug)}`}catch(i){r&&(r.textContent=`Couldn't create model: ${String(i)}`,r.classList.remove("d-none"))}})}},h=class{constructor(){d(this,"cfg");d(this,"slug","");d(this,"model",null);d(this,"versions",[]);d(this,"isOwner",!1)}async mount(e){this.cfg=e;let t=new URLSearchParams(window.location.search);if(this.slug=t.get("slug")||"",!this.slug){e.rootEl.innerHTML='

    Bad URL \u2014 model pages look like /models/detail/?slug=your-model.

    ';return}let r=null;try{r=await c(`${e.apiBase}/v1/me`)}catch{r=null}try{let o=await c(`${e.apiBase}/v1/models/${encodeURIComponent(this.slug)}`);this.model=o.model,this.versions=o.versions}catch(o){e.rootEl.innerHTML=`

    Model not found: ${s(String(o))}

    `;return}this.isOwner=!!r&&!!this.model.owner&&r.user.handle===this.model.owner.handle,this.render(),this.attachEvents()}render(){let e=this.model,t=this.cfg.rootEl;t.querySelector("#ga-model-title").textContent=e.title,t.querySelector("#ga-model-desc").textContent=e.description||"No description yet.",t.querySelector("#ga-model-meta").textContent=`${L[e.kind]||e.kind} \xB7 ${_[e.provider]||e.provider} \xB7 ${e.visibility}`;let r=t.querySelector("#ga-model-versions");r&&(r.innerHTML=this.versions.length?this.versions.map(i=>` +
  • +
    + v${i.version} + ${i.price_tokens.toLocaleString()} tokens +
    +

    ${s(i.provider_model_id)}

    + ${H(i)} + ${i.dataset_note?`

    ${s(i.dataset_note)}

    `:""} +
  • `).join(""):'
  • No published versions yet.
  • '),t.querySelector("#ga-publish-version-section")?.classList.toggle("d-none",!this.isOwner);let a=t.querySelector("#ga-pv-provider-hint");a&&(a.textContent=e.provider==="fal_custom"?"This is a custom-trained model \u2014 base model, training method, and weights_ref are required.":e.provider==="anthropic"?"Provider model id, e.g. claude-opus-5.":"Provider model id from the Workers AI catalogue, e.g. @cf/black-forest-labs/flux-1-schnell."),t.querySelectorAll(".ga-fal-only").forEach(i=>i.classList.toggle("d-none",e.provider!=="fal_custom")),t.querySelectorAll(".ga-code-only").forEach(i=>i.classList.toggle("d-none",e.kind!=="code"));let l=this.versions[0],u=t.querySelector("#ga-render-section");if(u){u.classList.toggle("d-none",!l||e.status!=="active");let i=t.querySelector("#ga-render-price");i&&l&&(i.textContent=`${l.price_tokens.toLocaleString()} tokens`)}}async publishVersion(){let e=this.cfg.rootEl,t=e.querySelector("#ga-pv-error");t?.classList.add("d-none");let r=e.querySelector("#ga-pv-provider-model-id").value.trim(),o=parseInt(e.querySelector("#ga-pv-price").value,10),a={provider_model_id:r,price_tokens:o};this.model.provider==="fal_custom"?(a.training_method=e.querySelector("#ga-pv-training-method").value,a.base_model=e.querySelector("#ga-pv-base-model").value.trim(),a.dataset_note=e.querySelector("#ga-pv-dataset-note").value.trim(),a.weights_ref=e.querySelector("#ga-pv-weights-ref").value.trim()):this.model.kind==="code"&&(a.system_prompt=e.querySelector("#ga-pv-system-prompt")?.value.trim()||void 0);try{await c(`${this.cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}/versions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),window.location.reload()}catch(l){t&&(t.textContent=`Couldn't publish: ${String(l)}`,t.classList.remove("d-none"))}}async render_(e){let t=this.cfg.rootEl,r=t.querySelector("#ga-render-prompt").value.trim(),o=t.querySelector("#ga-render-result"),a=e.textContent;e.disabled=!0,e.textContent="Rendering\u2026",o.innerHTML="";try{let l=await c(`${this.cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}/render`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:r})});this.renderResult(l.job,o)}catch(l){o.innerHTML=`
    Render failed: ${s(String(l))}
    `}finally{e.disabled=!1,e.textContent=a}}renderResult(e,t){if(e.status==="failed"){t.innerHTML=`
    Render failed (${s(e.error_code||"unknown")}) \u2014 tokens refunded.
    `;return}let r=`

    seed ${s(e.seed)}

    `;if(e.output_kind==="code"&&e.output_text)t.innerHTML=`${r}
    ${s(e.output_text)}
    `;else if(e.output_kind==="image"&&e.output_key){let o=`${this.cfg.apiBase}/v1/captures/${e.output_key}`;t.innerHTML=`${r}Render result`}else t.innerHTML=`${r}

    Render succeeded with no returned output.

    `}attachEvents(){let e=this.cfg.rootEl;e.querySelector("#ga-publish-version-form")?.addEventListener("submit",t=>{t.preventDefault(),this.publishVersion()}),e.querySelector("#ga-render-btn")?.addEventListener("click",t=>{this.render_(t.currentTarget)})}},S={async mount(n){y({apiBase:n.apiBase,page:`models-${n.mode}`}),n.mode==="catalogue"?await new p().mount(n):await new h().mount(n)}};window.GAModels=S;var x=S;export{x as default}; +//# sourceMappingURL=ga-models.js.map diff --git a/assets/js/ga-models.js.map b/assets/js/ga-models.js.map new file mode 100644 index 0000000..3958018 --- /dev/null +++ b/assets/js/ga-models.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../workers/api/client/lib/clientErrors.ts", "../../workers/api/client/models.ts"], + "sourcesContent": ["// Window onerror / unhandledrejection \u2192 POST /v1/internal/client-error.\n// Per-page de-dupe and 10-report cap; the Worker rate-limits per IP\n// and forwards to Sentry via SENTRY_DSN_PUBLIC server-side.\n//\n// Why not @sentry/browser? Bundle size is the deciding factor:\n// @sentry/browser min+gz is ~25KB, which is larger than every\n// per-page bundle this app ships (galleries 18KB, studio 100KB,\n// dashboard 7KB). The proxy pattern below has equivalent delivery\n// (the worker uses ctx.waitUntil for the forward), preserves stack\n// fidelity (we POST the raw `Error.stack` string verbatim), and\n// keeps the public DSN out of the client where it would otherwise\n// be visible to scrapers. The trade-off is that we don't get the\n// SDK's auto-capture of breadcrumbs / fetch/console hooks; for v1\n// observability that's an acceptable gap given the size budget.\n\nconst SEEN = new Set();\nconst MAX_REPORTS_PER_PAGE = 10;\nlet installed = false;\nlet configured: { apiBase: string; page: string } | null = null;\n\nexport interface ClientErrorReporterConfig {\n apiBase: string;\n /** Short page identifier \u2014 \"studio\", \"dashboard\", \"galleries\" etc. */\n page: string;\n}\n\nexport function installClientErrorReporter(cfg: ClientErrorReporterConfig): void {\n if (installed) return;\n installed = true;\n configured = cfg;\n window.addEventListener(\"error\", (ev) => {\n const message =\n (ev.error && ev.error.message) || ev.message || \"unknown_error\";\n const stack =\n (ev.error && ev.error.stack) ||\n `${ev.filename ?? \"\"}:${ev.lineno ?? 0}:${ev.colno ?? 0}`;\n void report(message, stack);\n });\n window.addEventListener(\"unhandledrejection\", (ev) => {\n const reason = (ev as PromiseRejectionEvent).reason;\n const message =\n reason instanceof Error\n ? reason.message\n : typeof reason === \"string\"\n ? reason\n : \"unhandled_rejection\";\n const stack = reason instanceof Error ? reason.stack ?? \"\" : \"\";\n void report(message, stack);\n });\n}\n\n// PII scrub: strip query string and hash from any URL we forward\n// so signed-upload tokens, ?email=, ?invite=, fragment-encoded\n// session bits, etc. never leave the browser. Also caps length.\nfunction scrubUrl(raw: string): string {\n try {\n const u = new URL(raw, location.origin);\n return `${u.origin}${u.pathname}`.slice(0, 200);\n } catch {\n return raw.split(\"?\")[0].split(\"#\")[0].slice(0, 200);\n }\n}\n\nasync function report(message: string, stack: string): Promise {\n if (!configured) return;\n // Per-page de-dupe + cap so a hot-loop error doesn't DoS the\n // /v1/internal/client-error endpoint.\n if (SEEN.size >= MAX_REPORTS_PER_PAGE) return;\n const key = `${message}::${stack.slice(0, 80)}`;\n if (SEEN.has(key)) return;\n SEEN.add(key);\n\n try {\n await fetch(`${configured.apiBase}/v1/internal/client-error`, {\n method: \"POST\",\n credentials: \"include\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n message: String(message).slice(0, 500),\n stack: String(stack).slice(0, 4000),\n page: configured.page,\n url: scrubUrl(location.href),\n ts: Date.now(),\n }),\n keepalive: true,\n });\n } catch {\n // never escalate a reporter failure into another error event\n }\n}\n", "/**\n * /models/ \u2014 public catalogue + \"my models\" + publish flow.\n * /models/detail/?slug=X \u2014 one model: provenance, versions, publish a\n * new version (owner-only), and the render form (everyone, gated by\n * visibility/price).\n *\n * Two Jekyll pages share this module (query-string routed like\n * /p/?id=N and /t/?p=N&id=T) \u2014 `mount()` reads `cfg.mode` to pick\n * which one it's rendering into.\n */\nimport { installClientErrorReporter } from \"./lib/clientErrors\";\n\ninterface ModelsConfig {\n apiBase: string;\n rootEl: HTMLElement;\n mode: \"catalogue\" | \"detail\";\n}\n\ninterface Owner {\n handle: string;\n display_name: string | null;\n avatar_url: string | null;\n}\n\ninterface ModelSummary {\n id: number;\n slug: string;\n title: string;\n description: string | null;\n kind: string;\n provider: string;\n visibility: string;\n status: string;\n created_at: number;\n updated_at: number;\n latest_version: number | null;\n latest_price_tokens: number | null;\n run_count: number;\n owner?: Owner;\n}\n\ninterface ModelVersion {\n id: number;\n version: number;\n provider_model_id: string;\n system_prompt?: string;\n params_schema: unknown;\n price_tokens: number;\n training_method: string | null;\n base_model: string | null;\n dataset_note: string | null;\n weights_ref?: string;\n created_at: number;\n}\n\ninterface RenderJob {\n id: number;\n model_version_id: number;\n project_id: number | null;\n seed: string;\n params: Record | null;\n status: string;\n price_tokens: number;\n output_kind: string | null;\n output_text: string | null;\n output_key: string | null;\n output_hash: string | null;\n error_code: string | null;\n created_at: number;\n finished_at: number | null;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\": return \"&\";\n case \"<\": return \"<\";\n case \">\": return \">\";\n case '\"': return \""\";\n default: return \"'\";\n }\n });\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise {\n const res = await fetch(url, { credentials: \"include\", ...init });\n if (!res.ok) {\n let detail = \"\";\n try { detail = JSON.stringify(await res.json()); } catch {}\n throw new Error(`${res.status}: ${detail || res.statusText}`);\n }\n return (await res.json()) as T;\n}\n\nconst KIND_LABELS: Record = { code: \"Code\", image: \"Image\" };\nconst PROVIDER_LABELS: Record = {\n anthropic: \"Claude\",\n workers_ai: \"Workers AI\",\n fal_custom: \"Custom-trained\",\n mock: \"Mock\",\n};\n\nfunction provenanceTag(v: Pick): string {\n if (!v.base_model) return \"\";\n const method = v.training_method ? ` \u00B7 ${escapeHtml(v.training_method)}` : \"\";\n return `${escapeHtml(v.base_model)}${method}`;\n}\n\nfunction renderModelCard(m: ModelSummary): string {\n const owner = m.owner\n ? `@${escapeHtml(m.owner.handle)}`\n : \"\";\n const price =\n m.latest_price_tokens !== null\n ? `${m.latest_price_tokens.toLocaleString()} tokens / run`\n : \"unpublished\";\n return `\n \n
    \n

    ${escapeHtml(KIND_LABELS[m.kind] || m.kind)} \u00B7 ${escapeHtml(PROVIDER_LABELS[m.provider] || m.provider)}

    \n

    ${escapeHtml(m.title)}

    \n

    ${escapeHtml(m.description || \"No description yet.\")}

    \n

    ${escapeHtml(price)} \u00B7 ${m.run_count} run${m.run_count === 1 ? \"\" : \"s\"}

    \n ${owner}\n
    \n
    `;\n}\n\nfunction renderEmptyModels(): string {\n return `

    No models yet.

    `;\n}\n\n// ---------------------------------------------------------------------------\n// Catalogue page\n// ---------------------------------------------------------------------------\n\nclass CataloguePage {\n private cfg!: ModelsConfig;\n private isAuthed = false;\n\n async mount(cfg: ModelsConfig): Promise {\n this.cfg = cfg;\n try {\n await fetchJson(`${cfg.apiBase}/v1/me`);\n this.isAuthed = true;\n } catch {\n this.isAuthed = false;\n }\n const mineSection = cfg.rootEl.querySelector(\"#ga-models-mine-section\");\n if (mineSection) mineSection.classList.toggle(\"d-none\", !this.isAuthed);\n\n await this.loadCatalogue();\n if (this.isAuthed) await this.loadMine();\n this.attachEvents();\n }\n\n private async loadCatalogue(kind?: string): Promise {\n const el = this.cfg.rootEl.querySelector(\"#ga-models-catalogue\");\n if (!el) return;\n el.innerHTML = `
    Loading\u2026
    `;\n try {\n const qs = kind ? `?kind=${encodeURIComponent(kind)}` : \"\";\n const data = await fetchJson<{ models: ModelSummary[] }>(`${this.cfg.apiBase}/v1/models${qs}`);\n el.innerHTML = data.models.length ? data.models.map(renderModelCard).join(\"\") : renderEmptyModels();\n } catch (err) {\n el.innerHTML = `
    Failed to load: ${escapeHtml(String(err))}
    `;\n }\n }\n\n private async loadMine(): Promise {\n const el = this.cfg.rootEl.querySelector(\"#ga-models-mine\");\n if (!el) return;\n try {\n const data = await fetchJson<{ models: ModelSummary[] }>(`${this.cfg.apiBase}/v1/models/mine`);\n el.innerHTML = data.models.length ? data.models.map(renderModelCard).join(\"\") : renderEmptyModels();\n } catch (err) {\n el.innerHTML = `
    Failed to load: ${escapeHtml(String(err))}
    `;\n }\n }\n\n private attachEvents(): void {\n this.cfg.rootEl.querySelectorAll(\"[data-ga-kind-filter]\").forEach((btn) => {\n btn.addEventListener(\"click\", () => {\n this.cfg.rootEl\n .querySelectorAll(\"[data-ga-kind-filter]\")\n .forEach((b) => b.classList.toggle(\"active\", b === btn));\n const kind = btn.dataset.gaKindFilter || \"\";\n void this.loadCatalogue(kind || undefined);\n });\n });\n\n const form = this.cfg.rootEl.querySelector(\"#ga-new-model-form\");\n form?.addEventListener(\"submit\", async (ev) => {\n ev.preventDefault();\n const errEl = this.cfg.rootEl.querySelector(\"#ga-new-model-error\");\n errEl?.classList.add(\"d-none\");\n const title = this.cfg.rootEl.querySelector(\"#ga-nm-title\")!.value.trim();\n const kind = this.cfg.rootEl.querySelector(\"#ga-nm-kind\")!.value;\n const provider = this.cfg.rootEl.querySelector(\"#ga-nm-provider\")!.value;\n const description = this.cfg.rootEl.querySelector(\"#ga-nm-description\")!.value.trim();\n try {\n const data = await fetchJson<{ model: ModelSummary }>(`${this.cfg.apiBase}/v1/models`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ title, kind, provider, description: description || undefined, visibility: \"private\" }),\n });\n window.location.href = `/models/detail/?slug=${encodeURIComponent(data.model.slug)}`;\n } catch (err) {\n if (errEl) {\n errEl.textContent = `Couldn't create model: ${String(err)}`;\n errEl.classList.remove(\"d-none\");\n }\n }\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Detail page\n// ---------------------------------------------------------------------------\n\nclass DetailPage {\n private cfg!: ModelsConfig;\n private slug = \"\";\n private model: ModelSummary | null = null;\n private versions: ModelVersion[] = [];\n private isOwner = false;\n\n async mount(cfg: ModelsConfig): Promise {\n this.cfg = cfg;\n const params = new URLSearchParams(window.location.search);\n this.slug = params.get(\"slug\") || \"\";\n if (!this.slug) {\n cfg.rootEl.innerHTML = `

    Bad URL \u2014 model pages look like /models/detail/?slug=your-model.

    `;\n return;\n }\n\n let me: { user: { handle: string } } | null = null;\n try {\n me = await fetchJson(`${cfg.apiBase}/v1/me`);\n } catch {\n me = null;\n }\n\n try {\n const data = await fetchJson<{ model: ModelSummary; versions: ModelVersion[] }>(\n `${cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}`,\n );\n this.model = data.model;\n this.versions = data.versions;\n } catch (err) {\n cfg.rootEl.innerHTML = `

    Model not found: ${escapeHtml(String(err))}

    `;\n return;\n }\n\n this.isOwner = !!me && !!this.model.owner && me.user.handle === this.model.owner.handle;\n this.render();\n this.attachEvents();\n }\n\n private render(): void {\n const m = this.model!;\n const root = this.cfg.rootEl;\n root.querySelector(\"#ga-model-title\")!.textContent = m.title;\n root.querySelector(\"#ga-model-desc\")!.textContent = m.description || \"No description yet.\";\n root.querySelector(\"#ga-model-meta\")!.textContent =\n `${KIND_LABELS[m.kind] || m.kind} \u00B7 ${PROVIDER_LABELS[m.provider] || m.provider} \u00B7 ${m.visibility}`;\n\n const versionsEl = root.querySelector(\"#ga-model-versions\");\n if (versionsEl) {\n versionsEl.innerHTML = this.versions.length\n ? this.versions\n .map(\n (v) => `\n
  • \n
    \n v${v.version}\n ${v.price_tokens.toLocaleString()} tokens\n
    \n

    ${escapeHtml(v.provider_model_id)}

    \n ${provenanceTag(v)}\n ${v.dataset_note ? `

    ${escapeHtml(v.dataset_note)}

    ` : \"\"}\n
  • `,\n )\n .join(\"\")\n : `
  • No published versions yet.
  • `;\n }\n\n const publishSection = root.querySelector(\"#ga-publish-version-section\");\n publishSection?.classList.toggle(\"d-none\", !this.isOwner);\n const providerHint = root.querySelector(\"#ga-pv-provider-hint\");\n if (providerHint) {\n providerHint.textContent =\n m.provider === \"fal_custom\"\n ? \"This is a custom-trained model \u2014 base model, training method, and weights_ref are required.\"\n : m.provider === \"anthropic\"\n ? \"Provider model id, e.g. claude-opus-5.\"\n : \"Provider model id from the Workers AI catalogue, e.g. @cf/black-forest-labs/flux-1-schnell.\";\n }\n root.querySelectorAll(\".ga-fal-only\").forEach((el) =>\n el.classList.toggle(\"d-none\", m.provider !== \"fal_custom\"),\n );\n root.querySelectorAll(\".ga-code-only\").forEach((el) =>\n el.classList.toggle(\"d-none\", m.kind !== \"code\"),\n );\n\n const latest = this.versions[0];\n const renderSection = root.querySelector(\"#ga-render-section\");\n if (renderSection) {\n renderSection.classList.toggle(\"d-none\", !latest || m.status !== \"active\");\n const priceEl = root.querySelector(\"#ga-render-price\");\n if (priceEl && latest) priceEl.textContent = `${latest.price_tokens.toLocaleString()} tokens`;\n }\n }\n\n private async publishVersion(): Promise {\n const root = this.cfg.rootEl;\n const errEl = root.querySelector(\"#ga-pv-error\");\n errEl?.classList.add(\"d-none\");\n const providerModelId = root.querySelector(\"#ga-pv-provider-model-id\")!.value.trim();\n const priceTokens = parseInt(root.querySelector(\"#ga-pv-price\")!.value, 10);\n const body: Record = { provider_model_id: providerModelId, price_tokens: priceTokens };\n\n if (this.model!.provider === \"fal_custom\") {\n body.training_method = root.querySelector(\"#ga-pv-training-method\")!.value;\n body.base_model = root.querySelector(\"#ga-pv-base-model\")!.value.trim();\n body.dataset_note = root.querySelector(\"#ga-pv-dataset-note\")!.value.trim();\n body.weights_ref = root.querySelector(\"#ga-pv-weights-ref\")!.value.trim();\n } else if (this.model!.kind === \"code\") {\n body.system_prompt = root.querySelector(\"#ga-pv-system-prompt\")?.value.trim() || undefined;\n }\n\n try {\n await fetchJson(`${this.cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}/versions`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n window.location.reload();\n } catch (err) {\n if (errEl) {\n errEl.textContent = `Couldn't publish: ${String(err)}`;\n errEl.classList.remove(\"d-none\");\n }\n }\n }\n\n private async render_(button: HTMLButtonElement): Promise {\n const root = this.cfg.rootEl;\n const prompt = root.querySelector(\"#ga-render-prompt\")!.value.trim();\n const resultEl = root.querySelector(\"#ga-render-result\")!;\n const original = button.textContent;\n button.disabled = true;\n button.textContent = \"Rendering\u2026\";\n resultEl.innerHTML = \"\";\n try {\n const data = await fetchJson<{ job: RenderJob }>(\n `${this.cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}/render`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ prompt }),\n },\n );\n this.renderResult(data.job, resultEl);\n } catch (err) {\n resultEl.innerHTML = `
    Render failed: ${escapeHtml(String(err))}
    `;\n } finally {\n button.disabled = false;\n button.textContent = original;\n }\n }\n\n private renderResult(job: RenderJob, el: HTMLElement): void {\n if (job.status === \"failed\") {\n el.innerHTML = `
    Render failed (${escapeHtml(job.error_code || \"unknown\")}) \u2014 tokens refunded.
    `;\n return;\n }\n const seedLine = `

    seed ${escapeHtml(job.seed)}

    `;\n if (job.output_kind === \"code\" && job.output_text) {\n el.innerHTML = `${seedLine}
    ${escapeHtml(job.output_text)}
    `;\n } else if (job.output_kind === \"image\" && job.output_key) {\n const src = `${this.cfg.apiBase}/v1/captures/${job.output_key}`;\n el.innerHTML = `${seedLine}\"Render`;\n } else {\n el.innerHTML = `${seedLine}

    Render succeeded with no returned output.

    `;\n }\n }\n\n private attachEvents(): void {\n const root = this.cfg.rootEl;\n root.querySelector(\"#ga-publish-version-form\")?.addEventListener(\"submit\", (ev) => {\n ev.preventDefault();\n void this.publishVersion();\n });\n root.querySelector(\"#ga-render-btn\")?.addEventListener(\"click\", (ev) => {\n void this.render_(ev.currentTarget as HTMLButtonElement);\n });\n }\n}\n\nconst GAModels = {\n async mount(cfg: ModelsConfig) {\n installClientErrorReporter({ apiBase: cfg.apiBase, page: `models-${cfg.mode}` });\n if (cfg.mode === \"catalogue\") await new CataloguePage().mount(cfg);\n else await new DetailPage().mount(cfg);\n },\n};\n\ndeclare global {\n interface Window {\n GAModels?: typeof GAModels;\n }\n}\n\nwindow.GAModels = GAModels;\nexport default GAModels;\n"], + "mappings": "oKAeA,IAAMA,EAAO,IAAI,IACXC,EAAuB,GACzBC,EAAY,GACZC,EAAuD,KAQpD,SAASC,EAA2BC,EAAsC,CAC3EH,IACJA,EAAY,GACZC,EAAaE,EACb,OAAO,iBAAiB,QAAUC,GAAO,CACvC,IAAMC,EACHD,EAAG,OAASA,EAAG,MAAM,SAAYA,EAAG,SAAW,gBAC5CE,EACHF,EAAG,OAASA,EAAG,MAAM,OACtB,GAAGA,EAAG,UAAY,EAAE,IAAIA,EAAG,QAAU,CAAC,IAAIA,EAAG,OAAS,CAAC,GACpDG,EAAOF,EAASC,CAAK,CAC5B,CAAC,EACD,OAAO,iBAAiB,qBAAuBF,GAAO,CACpD,IAAMI,EAAUJ,EAA6B,OACvCC,EACJG,aAAkB,MACdA,EAAO,QACP,OAAOA,GAAW,SAClBA,EACA,sBACAF,EAAQE,aAAkB,MAAQA,EAAO,OAAS,GAAK,GACxDD,EAAOF,EAASC,CAAK,CAC5B,CAAC,EACH,CAKA,SAASG,EAASC,EAAqB,CACrC,GAAI,CACF,IAAMC,EAAI,IAAI,IAAID,EAAK,SAAS,MAAM,EAC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CAEQ,aAAaC,EAAgB3B,EAAuB,CAC1D,GAAI2B,EAAI,SAAW,SAAU,CAC3B3B,EAAG,UAAY,kDAAkDvB,EAAWkD,EAAI,YAAc,SAAS,CAAC,kCACxG,MACF,CACA,IAAMC,EAAW,wDAAwDnD,EAAWkD,EAAI,IAAI,CAAC,OAC7F,GAAIA,EAAI,cAAgB,QAAUA,EAAI,YACpC3B,EAAG,UAAY,GAAG4B,CAAQ,+BAA+BnD,EAAWkD,EAAI,WAAW,CAAC,iBAC3EA,EAAI,cAAgB,SAAWA,EAAI,WAAY,CACxD,IAAME,EAAM,GAAG,KAAK,IAAI,OAAO,gBAAgBF,EAAI,UAAU,GAC7D3B,EAAG,UAAY,GAAG4B,CAAQ,qCAAqCC,CAAG,0BACpE,MACE7B,EAAG,UAAY,GAAG4B,CAAQ,2EAE9B,CAEQ,cAAqB,CAC3B,IAAMd,EAAO,KAAK,IAAI,OACtBA,EAAK,cAA+B,0BAA0B,GAAG,iBAAiB,SAAWR,GAAO,CAClGA,EAAG,eAAe,EACb,KAAK,eAAe,CAC3B,CAAC,EACDQ,EAAK,cAAiC,gBAAgB,GAAG,iBAAiB,QAAUR,GAAO,CACpF,KAAK,QAAQA,EAAG,aAAkC,CACzD,CAAC,CACH,CACF,EAEMwB,EAAW,CACf,MAAM,MAAMjC,EAAmB,CAC7BkC,EAA2B,CAAE,QAASlC,EAAI,QAAS,KAAM,UAAUA,EAAI,IAAI,EAAG,CAAC,EAC3EA,EAAI,OAAS,YAAa,MAAM,IAAIF,EAAc,EAAE,MAAME,CAAG,EAC5D,MAAM,IAAIc,EAAW,EAAE,MAAMd,CAAG,CACvC,CACF,EAQA,OAAO,SAAWiC,EAClB,IAAOE,EAAQF", + "names": ["SEEN", "MAX_REPORTS_PER_PAGE", "installed", "configured", "installClientErrorReporter", "cfg", "ev", "message", "stack", "report", "reason", "scrubUrl", "raw", "u", "key", "escapeHtml", "s", "ch", "fetchJson", "url", "init", "res", "detail", "KIND_LABELS", "PROVIDER_LABELS", "provenanceTag", "v", "method", "renderModelCard", "m", "owner", "price", "renderEmptyModels", "CataloguePage", "__publicField", "cfg", "mineSection", "kind", "el", "qs", "data", "err", "btn", "b", "ev", "errEl", "title", "provider", "description", "DetailPage", "params", "me", "root", "versionsEl", "providerHint", "latest", "renderSection", "priceEl", "providerModelId", "priceTokens", "body", "button", "prompt", "resultEl", "original", "job", "seedLine", "src", "GAModels", "installClientErrorReporter", "models_default"] +} diff --git a/assets/js/ga-studio.js b/assets/js/ga-studio.js index 4e21304..6adf142 100644 --- a/assets/js/ga-studio.js +++ b/assets/js/ga-studio.js @@ -1,25 +1,30 @@ -var Nd=Object.defineProperty;var Gd=(n,e,t)=>e in n?Nd(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var De=(n,e,t)=>Gd(n,typeof e!="symbol"?e+"":e,t);var Qr=new Set,Ud=10,Wa=!1,Xn=null;function za(n){Wa||(Wa=!0,Xn=n,window.addEventListener("error",e=>{let t=e.error&&e.error.message||e.message||"unknown_error",i=e.error&&e.error.stack||`${e.filename??""}:${e.lineno??0}:${e.colno??0}`;Ba(t,i)}),window.addEventListener("unhandledrejection",e=>{let t=e.reason,i=t instanceof Error?t.message:typeof t=="string"?t:"unhandled_rejection",s=t instanceof Error?t.stack??"":"";Ba(i,s)}))}function Fd(n){try{let e=new URL(n,location.origin);return`${e.origin}${e.pathname}`.slice(0,200)}catch{return n.split("?")[0].split("#")[0].slice(0,200)}}async function Ba(n,e){if(!Xn||Qr.size>=Ud)return;let t=`${n}::${e.slice(0,80)}`;if(!Qr.has(t)){Qr.add(t);try{await fetch(`${Xn.apiBase}/v1/internal/client-error`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:String(n).slice(0,500),stack:String(e).slice(0,4e3),page:Xn.page,url:Fd(location.href),ts:Date.now()}),keepalive:!0})}catch{}}}var $r=[],Va=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l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,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(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n<$r[i])t=i;else if(n>=Va[i])e=i+1;else return!0;if(e==t)return!1}}function _a(n){return n>=127462&&n<=127487}var Ia=8205;function qa(n,e,t=!0,i=!0){return(t?ja:Kd)(n,e,i)}function ja(n,e,t){if(e==n.length)return e;e&&Na(n.charCodeAt(e))&&Ga(n.charCodeAt(e-1))&&e--;let i=vr(n,e);for(e+=Ya(i);e=0&&_a(vr(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function Kd(n,e,t){for(;e>0;){let i=ja(n,e-2,t);if(i=56320&&n<57344}function Ga(n){return n>=55296&&n<56320}function Ya(n){return n<65536?1:2}var E=class n{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,i){[e,t]=ci(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),li.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ci(this,e,t);let i=[];return this.decompose(e,t,i,0),li.from(i,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),i=this.length-this.scanIdentical(e,-1),s=new Wt(this),r=new Wt(e);for(let o=t,l=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(l+=s.value.length,s.done||l>=i)return!0}}iter(e=1){return new Wt(this,e)}iterRange(e,t=this.length){return new Bn(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new zn(i)}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]?n.empty:e.length<=32?new ve(e):li.from(ve.split(e,[]))}},ve=class n extends E{constructor(e,t=Jd(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],l=s+o.length;if((t?i:l)>=e)return new Tr(s,l,i,o);s=l+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new n(Ua(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),l=Wn(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new n(l,o.length+r.length));else{let a=l.length>>1;i.push(new n(l.slice(0,a)),new n(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof n))return super.replace(e,t,i);[e,t]=ci(this,e,t);let s=Wn(this.text,Wn(i.text,Ua(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new n(s,r):li.from(n.split(s,[]),r)}sliceString(e,t=this.length,i=` +var Gd=Object.defineProperty;var Ud=(n,e,t)=>e in n?Gd(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ce=(n,e,t)=>Ud(n,typeof e!="symbol"?e+"":e,t);var vr=new Set,Fd=10,Wa=!1,En=null;function za(n){Wa||(Wa=!0,En=n,window.addEventListener("error",e=>{let t=e.error&&e.error.message||e.message||"unknown_error",i=e.error&&e.error.stack||`${e.filename??""}:${e.lineno??0}:${e.colno??0}`;_a(t,i)}),window.addEventListener("unhandledrejection",e=>{let t=e.reason,i=t instanceof Error?t.message:typeof t=="string"?t:"unhandled_rejection",s=t instanceof Error?t.stack??"":"";_a(i,s)}))}function Hd(n){try{let e=new URL(n,location.origin);return`${e.origin}${e.pathname}`.slice(0,200)}catch{return n.split("?")[0].split("#")[0].slice(0,200)}}async function _a(n,e){if(!En||vr.size>=Fd)return;let t=`${n}::${e.slice(0,80)}`;if(!vr.has(t)){vr.add(t);try{await fetch(`${En.apiBase}/v1/internal/client-error`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:String(n).slice(0,500),stack:String(e).slice(0,4e3),page:En.page,url:Hd(location.href),ts:Date.now()}),keepalive:!0})}catch{}}}var Pr=[],Va=[];(()=>{let n="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(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Va[i])e=i+1;else return!0;if(e==t)return!1}}function Ia(n){return n>=127462&&n<=127487}var Ya=8205;function ja(n,e,t=!0,i=!0){return(t?Na:Jd)(n,e,i)}function Na(n,e,t){if(e==n.length)return e;e&&Ga(n.charCodeAt(e))&&Ua(n.charCodeAt(e-1))&&e--;let i=$r(n,e);for(e+=qa(i);e=0&&Ia($r(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function Jd(n,e,t){for(;e>0;){let i=Na(n,e-2,t);if(i=56320&&n<57344}function Ua(n){return n>=55296&&n<56320}function qa(n){return n<65536?1:2}var E=class n{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,i){[e,t]=ci(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),li.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ci(this,e,t);let i=[];return this.decompose(e,t,i,0),li.from(i,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),i=this.length-this.scanIdentical(e,-1),s=new Bt(this),r=new Bt(e);for(let o=t,l=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(l+=s.value.length,s.done||l>=i)return!0}}iter(e=1){return new Bt(this,e)}iterRange(e,t=this.length){return new zn(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new In(i)}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]?n.empty:e.length<=32?new $e(e):li.from($e.split(e,[]))}},$e=class n extends E{constructor(e,t=ep(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],l=s+o.length;if((t?i:l)>=e)return new Cr(s,l,i,o);s=l+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new n(Fa(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),l=_n(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new n(l,o.length+r.length));else{let a=l.length>>1;i.push(new n(l.slice(0,a)),new n(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof n))return super.replace(e,t,i);[e,t]=ci(this,e,t);let s=_n(this.text,_n(i.text,Fa(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new n(s,r):li.from(n.split(s,[]),r)}sliceString(e,t=this.length,i=` `){[e,t]=ci(this,e,t);let s="";for(let r=0,o=0;r<=t&&oe&&o&&(s+=i),er&&(s+=l.slice(Math.max(0,e-r),t-r)),r=a+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new n(i,s)),i=[],s=-1);return s>-1&&t.push(new n(i,s)),t}},li=class n extends E{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],l=s+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,s);s=l+1,i=a+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r=o){let h=s&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ci(this,e,t),i.lines=r&&t<=l){let a=o.replace(e-r,t-r,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[s]=a,new n(c,this.length-(t-e)+i.length)}return super.replace(r,l,a)}r=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` -`){[e,t]=ci(this,e,t);let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=l.sliceString(e-o,t-o,i)),o=a+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof n))return 0;let i=0,[s,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==l)return i;let a=this.children[s],h=e.children[r];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new ve(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,l=[],a=0,h=-1,c=[];function f(d){let p;if(d.lines>r&&d instanceof n)for(let O of d.children)f(O);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof ve&&a&&(p=c[c.length-1])instanceof ve&&d.lines+p.lines<=32?(a+=d.lines,h+=d.length+1,c[c.length-1]=new ve(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>s&&u(),a+=d.lines,h+=d.length+1,c.push(d))}function u(){a!=0&&(l.push(c.length==1?c[0]:n.from(c,h)),h=-1,a=c.length=0)}for(let d of e)f(d);return u(),l.length==1?l[0]:new n(l,t)}};E.empty=new ve([""],0);function Jd(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Wn(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(a>i&&(l=l.slice(0,i-s)),s0?1:(e instanceof ve?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,l=s instanceof ve?s.text.length:s.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` -`,this;e--}else if(s instanceof ve){let a=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=s.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ve?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Bn=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new Wt(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}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 i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),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!=""}},zn=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(E.prototype[Symbol.iterator]=function(){return this.iter()},Wt.prototype[Symbol.iterator]=Bn.prototype[Symbol.iterator]=zn.prototype[Symbol.iterator]=function(){return this});var Tr=class{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}};function ci(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function te(n,e,t=!0,i=!0){return qa(n,e,t,i)}function ep(n){return n>=56320&&n<57344}function tp(n){return n>=55296&&n<56320}function le(n,e){let t=n.charCodeAt(e);if(!tp(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return ep(i)?(t-55296<<10)+(i-56320)+65536:t}function Yi(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Pe(n){return n<65536?1:2}var Cr=/\r\n?|\n/,se=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(se||(se={})),ht=class n{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=l}else{if(i!=se.Simple&&h>=e&&(i==se.TrackDel&&se||i==se.TrackBefore&&se))return null;if(h>e||h==e&&t<0&&!l)return e==s||t<0?r:r+a;r+=a}s=h}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&l>=e)return st?"cover":!0;s=l}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}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 n(e)}static create(e){return new n(e)}},Oe=class n extends ht{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 Zr(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Ar(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=l,t[s+1]=o;let a=s>>1;for(;i.length0&&bt(i,t,r.text),r.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,l=null;function a(c=!1){if(!c&&!s.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let p=d?typeof d=="string"?E.of(d.split(i||Cr)):d:E.empty,O=p.length;if(f==u&&O==0)return;fo&&ce(s,f-o,-1),ce(s,u-f,O),bt(r,s,p),o=u}}return h(e),a(!l),l}static empty(e){return new n(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function bt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(s,h,r,c,f),s=h,r=c}}}function Ar(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Bt(n),l=new Bt(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(s,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),r.forward2(a),o.forward(a)}}}}var Bt=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?E.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?E.empty:t[i].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)}},oi=class n{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}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 i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new n(i,s,this.flags)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return b.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return b.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!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 b.range(e.anchor,e.head)}static create(e,t,i){return new n(e,t,i)}},b=class n{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:n.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.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 n(e.ranges.map(t=>oi.fromJSON(t)),e.main)}static single(e,t=e){return new n([n.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 i=0,s=0;ss.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?n.range(a,l):n.range(l,a))}}return new n(e,t)}};function th(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var _r=0,$=class n{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=_r++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new n(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ir),!!e.static,e.enables)}of(e){return new ai([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new ai(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new ai(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}};function Ir(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}var ai=class{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=_r++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Mr(f,c)){let d=i(f);if(l?!Fa(d,f.values[o],s):!s(d,f.values[o]))return f.values[o]=d,1}return 0},reconfigure:(f,u)=>{let d,p=u.config.address[r];if(p!=null){let O=Yn(u,p);if(this.dependencies.every(g=>g instanceof $?u.facet(g)===f.facet(g):g instanceof K?u.field(g,!1)==f.field(g,!1):!0)||(l?Fa(d=i(f),O,s):s(d=i(f),O)))return f.values[o]=O,0}else d=i(f);return f.values[o]=d,1}}}};function Fa(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),s=t.map(a=>a.type),r=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(Ln).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(Ln),o=s.facet(Ln),l;return(l=r.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,Ln.of({field:this,create:e})]}get extension(){return this}},Et={lowest:4,low:3,default:2,high:1,highest:0};function Wi(n){return e=>new _n(e,n)}var xe={highest:Wi(Et.highest),high:Wi(Et.high),default:Wi(Et.default),low:Wi(Et.low),lowest:Wi(Et.lowest)},_n=class{constructor(e,t){this.inner=e,this.prec=t}},fi=class n{of(e){return new zi(this,e)}reconfigure(e){return n.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},zi=class{constructor(e,t){this.compartment=e,this.inner=t}},In=class n{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let u of np(e,t,o))u instanceof K?s.push(u):(r[u.facet.id]||(r[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of s)l[u.id]=h.length<<1,h.push(d=>u.slot(d));let c=i?.config.facets;for(let u in r){let d=r[u],p=d[0].facet,O=c&&c[u]||[];if(d.every(g=>g.type==0))if(l[p.id]=a.length<<1|1,Ir(O,d))a.push(i.facet(p));else{let g=p.combine(d.map(y=>y.value));a.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(y=>g.dynamicSlot(y)));l[p.id]=h.length<<1,h.push(g=>ip(g,p,d))}}let f=h.map(u=>u(l));return new n(e,o,f,l,a,r)}};function np(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,l){let a=s.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zi&&t.delete(o.compartment)}if(s.set(o,l),Array.isArray(o))for(let h of o)r(h,l);else if(o instanceof zi){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),r(h,l)}else if(o instanceof _n)r(o.inner,o.prec);else if(o instanceof K)i[l].push(o),o.provides&&r(o.provides,l);else if(o instanceof ai)i[l].push(o),o.facet.extensions&&r(o.facet.extensions,Et.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.`);r(h,l)}}return r(n,Et.default),i.reduce((o,l)=>o.concat(l))}function Bi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function Yn(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}var ih=$.define(),Rr=$.define({combine:n=>n.some(e=>e),static:!0}),nh=$.define({combine:n=>n.length?n[0]:void 0,static:!0}),sh=$.define(),rh=$.define(),oh=$.define(),lh=$.define({combine:n=>n.length?n[0]:!1}),be=class{constructor(e,t){this.type=e,this.value=t}static define(){return new Xr}},Xr=class{of(e){return new be(this,e)}},Lr=class{constructor(e){this.map=e}of(e){return new A(this,e)}},A=class n{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 n(this.type,t)}is(e){return this.type==e}static define(e={}){return new Lr(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}};A.reconfigure=A.define();A.appendConfig=A.define();var ie=class n{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&th(i,t.newLength),r.some(l=>l.type==n.time)||(this.annotations=r.concat(n.time.of(Date.now())))}static create(e,t,i,s,r,o){return new n(e,t,i,s,r,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(n.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};ie.time=be.define();ie.userEvent=be.define();ie.addToHistory=be.define();ie.remote=be.define();function sp(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof ie?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof ie?n=r[0]:n=hh(e,hi(r),!1)}return n}function op(n){let e=n.startState,t=e.facet(oh),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=ah(i,Er(e,r,n.changes.newLength),!0))}return i==n?n:ie.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}var lp=[];function hi(n){return n==null?lp:Array.isArray(n)?n:[n]}var V=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(V||(V={})),ap=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Dr;try{Dr=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function hp(n){if(Dr)return Dr.test(n);for(let e=0;e"\x80"&&(t.toUpperCase()!=t.toLowerCase()||ap.test(t)))return!0}return!1}function cp(n){return e=>{if(!/\S/.test(e))return V.Space;if(hp(e))return V.Word;for(let t=0;t-1)return V.Word;return V.Other}}var Y=class n{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let l=0;ls.set(h,a)),t=null),s.set(l.value.compartment,l.value.extension)):l.is(A.reconfigure)?(t=null,i=l.value):l.is(A.appendConfig)&&(t=null,i=hi(i).concat(l.value));let r;t?r=e.startState.values.slice():(t=In.resolve(i,s,this),r=new n(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(Rr)?e.newSelection:e.newSelection.asSingle();new n(t,e.newDoc,o,r,(l,a)=>a.update(l,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:b.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=hi(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return n.create({doc:e.doc,selection:b.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=In.resolve(e.extensions||[],new Map),i=e.doc instanceof E?e.doc:E.of((e.doc||"").split(t.staticFacet(n.lineSeparator)||Cr)),s=e.selection?e.selection instanceof b?e.selection:b.single(e.selection.anchor,e.selection.head):b.single(0);return th(s,i.length),t.staticFacet(Rr)||(s=s.asSingle()),new n(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(n.tabSize)}get lineBreak(){return this.facet(n.lineSeparator)||` -`}get readOnly(){return this.facet(lh)}phrase(e,...t){for(let i of this.facet(n.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(ih))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return cp(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=te(t,o,!1);if(r(t.slice(a,o))!=V.Word)break;o=a}for(;ln.length?n[0]:4});Y.lineSeparator=nh;Y.readOnly=lh;Y.phrases=$.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});Y.languageData=ih;Y.changeFilter=sh;Y.transactionFilter=rh;Y.transactionExtender=oh;fi.reconfigure=A.define();function fe(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}var We=class{eq(e){return this==e}range(e,t=e){return _i.create(e,t,this)}};We.prototype.startSide=We.prototype.endSide=0;We.prototype.point=!1;We.prototype.mapMode=se.TrackDel;function Yr(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}var _i=class n{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new n(e,t,i)}};function Wr(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var Br=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,l=r.length;;){if(o==l)return o;let a=o+l>>1,h=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rd||u==d&&h.startSide>0&&h.endSide<=0)continue;(d-u||h.endSide-h.startSide)<0||(o<0&&(o=u),h.point&&(l=Math.max(l,d-u)),i.push(h),s.push(u-o),r.push(d-o))}return{mapped:i.length?new n(s,r,i,l):null,pos:o}}},W=class n{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new n(e,t,i,s)}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:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Wr)),this.isEmpty)return t.length?n.of(t):this;let l=new Vn(this,null,-1).goto(0),a=0,h=[],c=new $e;for(;l.value||a=0){let f=t[a++];c.addInner(f.from,f.to,f.value)||h.push(f)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||rl.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return Ii.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Ii.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),l=t.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),a=Ha(o,l,i),h=new Dt(o,a,r),c=new Dt(l,a,r);i.iterGaps((f,u,d)=>Ka(h,f,c,u,d,s)),i.empty&&i.length==0&&Ka(h,0,c,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let l=Ha(r,o),a=new Dt(r,l,0).goto(i),h=new Dt(o,l,0).goto(i);for(;;){if(a.to!=h.to||!zr(a.active,h.active)||a.point&&(!h.point||!Yr(a.point,h.point)))return!1;if(a.to>s)return!0;a.next(),h.next()}}static spans(e,t,i,s,r=-1){let o=new Dt(e,null,r).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let c=o.activeForPoint(o.to),f=o.pointFroml&&(s.span(l,h,o.active,a),a=o.openEnd(h));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new $e;for(let s of e instanceof _i?[e]:t?fp(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return n.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=n.empty;s=s.nextLayer)t=new n(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}};W.empty=new W([],[],null,-1);function fp(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Wr);e=i}return n}W.empty.nextLayer=W.empty;var $e=class n{finishChunk(e){this.chunks.push(new Br(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,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new n)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<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=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.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 i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(W.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=W.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function Ha(n,e,t){let i=new Map;for(let r of n)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=i&&s.push(new Vn(o,t,i,r));return s.length==1?s[0]:new n(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Pr(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Pr(this.heap,i);(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(),Pr(this.heap,0)}}};function Pr(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}var Dt=class{constructor(e,t,i){this.minPoint=i,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=Ii.from(e,t,i)}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){En(this.active,e),En(this.activeTo,e),En(this.activeRank,e),this.minActive=Ja(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t0;)t++;Dn(this.active,t,i),Dn(this.activeTo,t,s),Dn(this.activeRank,t,r),e&&Dn(e,t,this.cursor.from),this.minActive=Ja(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&En(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[s]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}};function Ka(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,l=i,a=i-e,h=!!r.boundChange;for(let c=!1;;){let f=n.to+a-t.to,u=f||n.endSide-t.endSide,d=u<0?n.to+a:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&Yr(n.point,t.point)&&zr(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(l,p,n.point,t.point),c=!1):(c&&r.boundChange(l),p>l&&!zr(n.active,t.active)&&r.compareRange(l,p,n.active,t.active),h&&po)break;l=d,u<=0&&n.next(),u>=0&&t.next()}}function zr(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function Ja(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=te(n,s)}return i===!0?-1:n.length}var ch=typeof Symbol>"u"?"__\u037C":Symbol.for("\u037C"),Vr=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),fh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},Be=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,l,a,h){let c=[],f=/^@(\w+)\b/.exec(o[0]),u=f&&f[1]=="keyframes";if(f&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))r(d.split(/,\s*/).map(O=>o.map(g=>O.replace(/&/,g))).reduce((O,g)=>O.concat(g)),p,a);else if(p&&typeof p=="object"){if(!f)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,c,u)}else p!=null&&c.push(d.replace(/_.*/,"").replace(/[A-Z]/g,O=>"-"+O.toLowerCase())+": "+p+";")}(c.length||u)&&a.push((i&&!f&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` -`)}static newName(){let e=fh[ch]||1;return fh[ch]=e+1,"\u037C"+e.toString(36)}static mount(e,t,i){let s=e[Vr],r=i&&i.nonce;s?r&&s.setNonce(r):s=new qr(e,r),s.mount(Array.isArray(t)?t:[t],e)}},uh=new Map,qr=class{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=uh.get(i);if(r)return e[Vr]=r;this.sheet=new s.CSSStyleSheet,uh.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Vr]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o-1&&(this.modules.splice(a,1),r--,a=-1),a==-1){if(this.modules.splice(r++,0,l),i)for(let h=0;h",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},up=typeof navigator<"u"&&/Mac/.test(navigator.platform),dp=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(ne=0;ne<10;ne++)ft[48+ne]=ft[96+ne]=String(ne);var ne;for(ne=1;ne<=24;ne++)ft[ne+111]="F"+ne;var ne;for(ne=65;ne<=90;ne++)ft[ne]=String.fromCharCode(ne+32),ui[ne]=String.fromCharCode(ne);var ne;for(jn in ft)ui.hasOwnProperty(jn)||(ui[jn]=ft[jn]);var jn;function dh(n){var e=up&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||dp&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?ui:ft)[n.keyCode]||n.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 B(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e2),T={mac:gh||/Mac/.test(me.platform),windows:/Win/.test(me.platform),linux:/Linux|X11/.test(me.platform),ie:vs,ie_version:Jh?to.documentMode||6:no?+no[1]:io?+io[1]:0,gecko:Oh,gecko_version:Oh?+(/Firefox\/(\d+)/.exec(me.userAgent)||[0,0])[1]:0,chrome:!!jr,chrome_version:jr?+jr[1]:0,ios:gh,android:/Android\b/.test(me.userAgent),webkit:mh,webkit_version:mh?+(/\bAppleWebKit\/(\d+)/.exec(me.userAgent)||[0,0])[1]:0,safari:so,safari_version:so?+(/\bVersion\/(\d+(\.\d+)?)/.exec(me.userAgent)||[0,0])[1]:0,tabSize:to.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Ho(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}var ls=Object.create(null);function Ko(n,e,t){if(n==e)return!0;n||(n=ls),e||(e=ls);let i=Object.keys(n),s=Object.keys(e);if(i.length-(t&&i.indexOf(t)>-1?1:0)!=s.length-(t&&s.indexOf(t)>-1?1:0))return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function pp(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function yh(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function Op(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new Yt(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=ec(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Yt(e,i,s,t,e.widget||null,!0)}static line(e){return new sn(e)}static set(e,t=!1){return W.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};Z.none=W.empty;var nn=class n extends Z{constructor(e){let{start:t,end:i}=ec(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Ho(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||ls}eq(e){return this==e||e instanceof n&&this.tagName==e.tagName&&Ko(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};nn.prototype.point=!1;var sn=class n extends Z{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof n&&this.spec.class==e.spec.class&&Ko(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)}};sn.prototype.mapMode=se.TrackBefore;sn.prototype.point=!0;var Yt=class n extends Z{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?se.TrackBefore:se.TrackAfter:se.TrackDel}get type(){return this.startSide!=this.endSide?he.WidgetRange:this.startSide<=0?he.WidgetBefore:he.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof n&&mp(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)}};Yt.prototype.point=!0;function ec(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function mp(n,e){return n==e||!!(n&&e&&n.compare(e))}function yi(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}var as=class n extends We{constructor(e,t){super(),this.tagName=e,this.attributes=t}eq(e){return e==this||e instanceof n&&this.tagName==e.tagName&&Ko(this.attributes,e.attributes)}static create(e){return new n(e.tagName,e.attributes||ls)}static set(e,t=!1){return W.of(e,t)}};as.prototype.startSide=as.prototype.endSide=-1;function rn(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function ro(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Ni(n,e){if(!e.anchorNode)return!1;try{return ro(n,e.anchorNode)}catch{return!1}}function is(n){return n.nodeType==3?on(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Gi(n,e,t,i){return t?bh(n,e,t,i,-1)||bh(n,e,t,i,1):!1}function wt(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function hs(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function bh(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:pt(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=wt(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?pt(n):0}else return!1}}function pt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function cs(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function gp(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function tc(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function yp(n,e,t,i,s,r,o,l){let a=n.ownerDocument,h=a.defaultView||window;for(let c=n,f=!1;c&&!f;)if(c.nodeType==1){let u,d=c==a.body,p=1,O=1;if(d)u=gp(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 x=c.getBoundingClientRect();({scaleX:p,scaleY:O}=tc(c,x)),u={left:x.left,right:x.left+c.clientWidth*p,top:x.top,bottom:x.top+c.clientHeight*O}}let g=0,y=0;if(s=="nearest")e.top0&&e.bottom>u.bottom+y&&(y=e.bottom-u.bottom+o)):e.bottom>u.bottom-o&&(y=e.bottom-u.bottom+o,t<0&&e.top-y0&&e.right>u.right+g&&(g=e.right-u.right+r)):e.right>u.right-r&&(g=e.right-u.right+r,t<0&&e.leftu.bottom||e.leftu.right)&&(e={left:Math.max(e.left,u.left),right:Math.min(e.right,u.right),top:Math.max(e.top,u.top),bottom:Math.min(e.bottom,u.bottom)}),c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function ic(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}var oo=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:i}=e;this.set(t,Math.min(e.anchorOffset,t?pt(t):0),i,Math.min(e.focusOffset,i?pt(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}},zt=null;T.safari&&T.safari_version>=26&&(zt=!1);function nc(n){if(n.setActive)return n.setActive();if(zt)return n.focus(zt);let e=[];for(let t=n;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(n.focus(zt==null?{get preventScroll(){return zt={preventScroll:!0},!0}}:void 0),!zt){zt=!1;for(let t=0;tMath.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function rc(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=pt(t)}else if(t.parentNode&&!hs(t))i=wt(t),t=t.parentNode;else return null}}function oc(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(l.level==i)return o;(r<0||(s!=0?s<0?l.fromt:e[r].level>l.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}};function hc(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;O-=3)if(nt[O+1]==-d){let g=nt[O+2],y=g&2?s:g&4?g&1?r:s:0;y&&(j[f]=j[nt[O]]=y),l=O;break}}else{if(nt.length==189)break;nt[l++]=f,nt[l++]=u,nt[l++]=a}else if((p=j[f])==2||p==1){let O=p==s;a=O?0:1;for(let g=l-3;g>=0;g-=3){let y=nt[g+2];if(y&2)break;if(O)nt[g+2]|=2;else{if(y&4)break;nt[g+2]|=4}}}}}function $p(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,l=sa;)p==g&&(p=t[--O].from,g=O?t[O-1].to:n),j[--p]=d;a=c}else r=h,a++}}}function ao(n,e,t,i,s,r,o){let l=i%2?2:1;if(i%2==s%2)for(let a=e,h=0;aa&&o.push(new Ie(a,O.from,d));let g=O.direction==Vt!=!(d%2);ho(n,g?i+1:i,s,O.inner,O.from,O.to,o),a=O.to}p=O.to}else{if(p==t||(c?j[p]!=l:j[p]==l))break;p++}u?ao(n,a,p,i+1,s,u,o):ae;){let c=!0,f=!1;if(!h||a>r[h-1].to){let O=j[a-1];O!=l&&(c=!1,f=O==16)}let u=!c&&l==1?[]:null,d=c?i:i+1,p=a;e:for(;;)if(h&&p==r[h-1].to){if(f)break e;let O=r[--h];if(!c)for(let g=O.from,y=h;;){if(g==e)break e;if(y&&r[y-1].to==g)g=r[--y].from;else{if(j[g-1]==l)break e;break}}if(u)u.push(O);else{O.toj.length;)j[j.length]=256;let i=[],s=e==Vt?0:1;return ho(n,s,s,t,0,n.length,i),i}function cc(n){return[new Ie(0,n,0)]}var fc="";function Tp(n,e,t,i,s){var r;let o=i.head-n.from,l=Ie.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),a=e[l],h=a.side(s,t);if(o==h){let u=l+=s?1:-1;if(u<0||u>=e.length)return null;a=e[l=u],o=a.side(!s,t),h=a.side(s,t)}let c=te(n.text,o,a.forward(s,t));(ca.to)&&(c=h),fc=n.text.slice(Math.min(o,c),Math.max(o,c));let f=l==(s?e.length-1:0)?null:e[l+(s?1:-1)];return f&&c==h&&f.level+(s?0:1)n.some(e=>e)}),bc=$.define({combine:n=>n.some(e=>e)}),xc=$.define(),Ui=class n{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new n(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 n(b.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},Nn=A.define({map:(n,e)=>n.map(e)}),Sc=A.define();function ae(n,e,t){let i=n.facet(Oc);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}var ut=$.define({combine:n=>n.length?n[0]:!0}),Zp=0,pi=$.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let a=[];return o&&a.push($s.of(h=>{let c=h.plugin(l);return c?o(c):Z.none})),r&&a.push(r(l)),a})}static fromClass(e,t){return n.define((i,s)=>new e(i,s),t)}},Fi=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}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(i){if(ae(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ae(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(i){ae(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},wc=$.define(),il=$.define(),$s=$.define(),kc=$.define(),nl=$.define(),ln=$.define(),Qc=$.define();function Sh(n,e){let t=n.state.facet(Qc);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return W.spans(i,e.from,e.to,{point(){},span(r,o,l,a){let h=r-e.from,c=o-e.from,f=s;for(let u=l.length-1;u>=0;u--,a--){let d=l[u].spec.bidiIsolate,p;if(d==null&&(d=Cp(e.text,h,c)),a>0&&f.length&&(p=f[f.length-1]).to==h&&p.direction==d)p.to=c,f=p.inner;else{let O={from:h,to:c,direction:d,inner:[]};f.push(O),f=O.inner}}}}),s}var vc=$.define();function sl(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(vc)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}var Vi=$.define(),Ne=class n{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new n(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,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAs.push(new Ne(r,o,l,a))),this.changedRanges=s}static create(e,t,i){return new n(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>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}},Ap=[],F=class{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Ap}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&pp(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t){return null}domPosFor(e,t){let i=wt(this.dom),s=this.length?e>0:t>0;return new st(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Si)return e;return null}static get(e){return e.cmTile}},xi=class extends F{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let l of this.children){if(l.sync(e),o+=l.length+l.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=l.dom&&(r.written=!0),l.dom.parentNode==t)for(;s&&s!=l.dom;)s=wh(s);else t.insertBefore(l.dom,s);i=l.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=wh(s);this.length=o}};function wh(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}var Si=class extends xi{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=F.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof dt)t.push(s),i=o,s=0;else{let l=r+o.length,a=e(o,r);if(a!==void 0)return a;r=l+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((l,a)=>{let h=a+l.length;if(e>=a&&e<=h){if(l.isWidget()&&t>=-1&&t<=1){if(l.flags&32)return!0;l.flags&16&&(i=void 0)}(ae||e==a&&(t>1?l.length:l.covers(-1)))&&(!r||!l.isWidget()&&r.isWidget())&&(r=l,o=e-a)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}},dt=class n extends xi{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new n(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}},wi=class n extends xi{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new n(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,l=-1;function a(c,f){for(let u=0,d=0;u=f&&(p.isComposite()?a(p,f-d):(!o||o.isHidden&&(t>0||i&&Rp(o,p)))&&(O>f||p.flags&32)?(o=p,l=f-d):(di&&(e=i);let s=e,r=e,o=0;e==0&&t<0||e==i&&t>=0?T.chrome||T.gecko||(e?(s--,o=1):r=0)?0:l.length-1];return T.safari&&!o&&a.width==0&&(a=Array.prototype.find.call(l,h=>h.width)||a),o?cs(a,o<0):a||null}static of(e,t){let i=new n(t||document.createTextNode(e),e);return t||(i.flags|=2),i}},qt=class n extends F{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return cs(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let l=this.flags&16?!0:this.flags&32?!1:e>0;for(let a=l?r.length-1:0;o=r[a],!(e>0?a==0:a==r.length-1||o.top0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!l.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=l.pop(),r++}else{let a=s.children[r],h=a.breakAfter;(t>0?a.length<=e:a.length=0;l--){let a=t.marks[l],h=s.lastChild;if(h instanceof Se&&h.mark.eq(a.mark))h.dom!=a.dom&&h.setDOM(Nr(a.dom)),s=h;else{if(this.cache.reused.get(a)){let f=F.get(a.dom);f&&f.setDOM(Nr(a.dom))}let c=Se.of(a.mark,a.dom);s.append(c),s=c}this.cache.reused.set(a,2)}let r=F.get(e.text);r&&this.cache.reused.set(r,2);let o=new _t(e.text,e.text.nodeValue);o.flags|=8,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=$c);let s=wi.start(e,t||((i=this.cache.find(wi))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],l;if(t>0&&(l=s.lastChild)&&l instanceof Se&&l.mark.eq(o))s=l,t--;else{let a=Se.of(o,(i=this.cache.find(Se,h=>h.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(a),s=a,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!kh(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(T.ios&&kh(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Gr,0,32)||new qt(Gr.toDOM(),0,Gr,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=new uo(e.from,e.to,e.value,e.rank),i=this.wrappers.length;for(;i>0&&(this.wrappers[i-1].rank-t.rank||this.wrappers[i-1].to-t.to)<0;)i--;this.wrappers.splice(i,0,t)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(ki,void 0,1);return i&&(i.flags=t),i||new ki(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},Oo=class{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let l=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}},us=[qt,wi,_t,Se,ki,dt,Si];for(let n=0;n[]),this.index=us.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let l=r.length-1;l>=0;l--){let a=(l+o)%r.length,h=r[a];if((!t||t(h))&&!this.reused.has(h))return r.splice(a,1),a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let l=os){let h=a-s;this.preserve(h,!o,!l),s=a,r+=h}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(this.forward(l.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let h=a>0||l{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Se&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof Se&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=0,o=W.spans(this.decorations,e,t,{point:(l,a,h,c,f,u)=>{if(h instanceof Yt){if(this.disallowBlockEffectsFor[u]){if(h.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=c.length,f>c.length)s.continueWidget(a-l);else{let d=h.widget||(h.block?kt.block:kt.inline),p=Xp(h),O=this.cache.findWidget(d,a-l,p)||qt.of(d,this.view,a-l,p);h.block?(h.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(O)):(s.ensureLine(i),s.addInlineWidget(O,c,f))}i=null}else i=Lp(i,h);a>l&&this.text.skip(a-l)},span:(l,a,h,c)=>{for(let f=l;fr,this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=F.get(s);if(s==this.view.contentDOM)break;r instanceof Se?t.push(r):r?.isLine()?i=r:r instanceof dt||(s.nodeName=="DIV"&&!i&&s!=this.view.contentDOM?i=new wi(s,$c):i||t.push(Se.of(new nn({tagName:s.nodeName.toLowerCase(),attributes:Op(s)}),s)))}return{line:i,marks:t}}};function kh(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function Xp(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}var $c={class:"cm-line"};function Lp(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&Ho(t,n),i&&(n.class+=" "+i)),n}function Ep(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof Se&&e.push(i.mark)}return e}function Nr(n){let e=F.get(n);return e&&e.setDOM(n.cloneNode()),n}var kt=class extends ge{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 Gr=new class extends ge{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}},ds=class{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=Z.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.updateDeco(),this.tile=new Si(e,e.contentDOM),this.updateInner([new Ne(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:c,toA:f})=>fthis.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 s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!Vp(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?Wp(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:c,to:f}=this.hasComposition;i=new Ne(c,f,e.changes.mapPos(c,-1),e.changes.mapPos(f,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(T.ie||T.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,l=this.blockWrappers;this.updateDeco();let a=_p(o,this.decorations,e.changes);a.length&&(i=Ne.extendWithRanges(i,a));let h=Ip(l,this.blockWrappers,e.changes);return h.length&&(i=Ne.extendWithRanges(i,h)),r&&!i.some(c=>c.fromA<=r.range.fromA&&c.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,l=new go(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&F.get(t.text)&&l.cache.reused.set(F.get(t.text),2),this.tile=l.run(e,t),yo(o,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=T.chrome||T.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Ni(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,h,c;if(a.empty?c=h=this.inlineDOMNearPos(a.anchor,a.assoc||1):(c=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),h=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),T.gecko&&a.empty&&!this.hasComposition&&Dp(h)){let u=document.createTextNode("");this.view.observer.ignore(()=>h.node.insertBefore(u,h.node.childNodes[h.offset]||null)),h=c=new st(u,0),l=!0}let f=this.view.observer.selectionRange;(l||!f.focusNode||(!Gi(h.node,h.offset,f.anchorNode,f.anchorOffset)||!Gi(c.node,c.offset,f.focusNode,f.focusOffset))&&!this.suppressWidgetCursorChange(f,a))&&(this.view.observer.ignore(()=>{T.android&&T.chrome&&i.contains(f.focusNode)&&Yp(f.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let u=rn(this.view.root);if(u)if(a.empty){if(T.gecko){let d=Bp(h.node,h.offset);if(d&&d!=3){let p=(d==1?rc:oc)(h.node,h.offset);p&&(h=new st(p.node,p.offset))}}u.collapse(h.node,h.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(h.node,h.offset);try{u.extend(c.node,c.offset)}catch{}}else{let d=document.createRange();a.anchor>a.head&&([h,c]=[c,h]),d.setEnd(c.node,c.offset),d.setStart(h.node,h.offset),u.removeAllRanges(),u.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(h,c)),this.impreciseAnchor=h.precise?null:new st(f.anchorNode,f.anchorOffset),this.impreciseHead=c.precise?null:new st(f.focusNode,f.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Gi(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,i=rn(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(c.node,c.offset),i.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&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=pt(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==i.dom)break;o==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?o=-1:o=1),e=l}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!F.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,l=s;;o++){let a=i.children[o];if(a.dom==r)return l;l+=a.length+a.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(e,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,l=-1,a=!1;return this.tile.blockTiles((h,c)=>{if(h.isWidget()){if(h.flags&32&&c>=e)return!0;h.flags&16&&(r=!0)}else{let f=c+h.length;if(c<=e&&(i=h,s=e-c,r=f=e&&!o&&(o=h,l=e-c,a=c>e),c>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:a&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(l,t))}coordsAt(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.widget instanceof Hi?null:i.coordsInWidget(s,t,!0):i.coordsIn(s,t)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let l of r.children){if(l.length>=o){let a=s(l,o);if(a)return a}if(o-=l.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==_.LTR,h=0,c=(f,u,d)=>{for(let p=0;ps);p++){let O=f.children[p],g=u+O.length,y=O.dom.getBoundingClientRect(),{height:x}=y;if(d&&!p&&(h+=y.top-d.top),O instanceof dt)g>i&&c(O,u,y);else if(u>=i&&(h>0&&t.push(-h),t.push(x+h),h=0,o)){let S=O.dom.lastChild,C=S?is(S):[];if(C.length){let w=C[C.length-1],k=a?w.right-y.left:y.right-w.left;k>l&&(l=k,this.minWidth=r,this.minWidthFrom=u,this.minWidthTo=g)}}d&&p==f.children.length-1&&(h+=d.bottom-y.bottom),u=g+O.breakAfter}};return c(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?_.RTL:_.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let l=0,a;for(let h of o.children){if(!h.isText()||/[^ -~]/.test(h.text))return;let c=is(h.dom);if(c.length!=1)return;l+=c[0].width,a=c[0].height}if(l)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:l/o.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=is(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let l=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(Z.replace({widget:new Hi(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return Z.set(e)}updateDeco(){let e=1,t=this.view.state.facet($s).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(nl).map((r,o)=>{let l=typeof r=="function";return l&&(i=!0),l?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(W.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){var t;if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(xc))try{if(c(this.view,e.range,e))return!0}catch(f){ae(this.view.state,f,"scroll handler")}let{range:i}=e,s=this.coordsAt(i.head,(t=i.assoc)!==null&&t!==void 0?t:i.empty?0:i.head>i.anchor?-1:1),r;if(!s)return;!i.empty&&(r=this.coordsAt(i.anchor,i.anchor>i.head?-1:1))&&(s={left:Math.min(s.left,r.left),top:Math.min(s.top,r.top),right:Math.max(s.right,r.right),bottom:Math.max(s.bottom,r.bottom)});let o=sl(this.view),l={left:s.left-o.left,top:s.top-o.top,right:s.right+o.right,bottom:s.bottom+o.bottom},{offsetWidth:a,offsetHeight:h}=this.view.scrollDOM;if(yp(this.view.scrollDOM,l,i.head1&&(s.top>window.pageYOffset+window.visualViewport.offsetTop+window.visualViewport.height||s.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){yo(this.tile)}};function yo(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)yo(i,e)}}function Dp(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function Pc(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=rc(t.focusNode,t.focusOffset),s=oc(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let l=F.get(s.node);if(!l||l.isText()&&l.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let a=F.get(i.node);!a||a.isText()&&a.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function Wp(n,e,t){let i=Pc(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,l=s.nodeValue;if(/[\n\r]/.test(l)||n.state.doc.sliceString(i.from,i.to)!=l)return null;let a=e.invertedDesc;return{range:new Ne(a.mapPos(r),a.mapPos(o),r,o),text:s}}function Bp(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}var Hi=class extends ge{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function qp(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return b.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,l=r;t<0?o=te(s.text,r,!1):l=te(s.text,r);let a=i(s.text.slice(o,l));for(;o>0;){let h=te(s.text,o,!1);if(i(s.text.slice(h,o))!=a)break;o=h}for(;ln.defaultLineHeight*1.5){let l=n.viewState.heightOracle.textHeight,a=Math.floor((s-t.top-(n.defaultLineHeight-l)*.5)/l);r+=a*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+qn(o,r,n.state.tabSize)}function xo(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!s||r.type==he.Text&&(s.type!=r.type||(t<0?r.frome)))&&(s=r)}}return s||i}return i}function Np(n,e,t,i){let s=xo(n,e.head,e.assoc||-1),r=!i||s.type!=he.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),l=n.textDirectionAt(s.from),a=n.posAtCoords({x:t==(l==_.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(a!=null)return b.cursor(a,t?-1:1)}return b.cursor(t?s.to:s.from,t?-1:1)}function Qh(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let l=e,a=null;;){let h=Tp(s,r,o,l,t),c=fc;if(!h){if(s.number==(t?n.state.doc.lines:1))return l;c=` -`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),h=n.visualLineSide(s,!t)}if(a){if(!a(c))return l}else{if(!i)return h;a=i(c)}l=h}}function Gp(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==V.Space&&(s=o),s==o}}function Up(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return b.cursor(s,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),c=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=r<0?h.top:h.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(s-p.from))),l=(r<0?p.top:p.bottom)+c}let f=a.left+o,u=n.viewState.heightOracle.textHeight>>1,d=i??u;for(let p=0;;p+=u){let O=l+(d+p)*r,g=So(n,{x:f,y:O},!1,r);if(t?O>a.bottom:Ol:x{if(e>r&&es(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:b.cursor(i,in.viewState.docHeight)return new _e(n.state.doc.length,-1);if(h=n.elementAtHeight(a),i==null)break;if(h.type==he.Text){if(i<0?h.ton.viewport.to)break;let u=n.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+r:u.bottom>=a+r))break}let f=n.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+f:h.top-f}if(n.viewport.from>=h.to||n.viewport.to<=h.from){if(t)return null;if(h.type==he.Text){let f=jp(n,s,h,o,l);return new _e(f,f==h.from?1:-1)}}if(h.type!=he.Text)return a<(h.top+h.bottom)/2?new _e(h.from,1):new _e(h.to,-1);let c=n.docView.lineAt(h.from,2);return(!c||c.length!=h.length)&&(c=n.docView.lineAt(h.from,-2)),new wo(n,o,l,n.textDirectionAt(h.from)).scanTile(c,h.from)}var wo=class{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from>1;t:if(r.has(p)){let g=i+Math.floor(Math.random()*d);for(let y=0;y1)){if(y.bottomthis.y)(!a||a.top>y.top)&&(a=y),x=-1;else{let S=y.left>this.x?this.x-y.left:y.right(d+d+p)/3)return this.y=l.bottom-1,this.scan(e,t);if(a&&a.top<(d+p+p)/3)return this.y=a.top+1,this.scan(e,t)}let u=(o?this.dirAt(e[h],1):this.baseDir)==_.LTR;return{i:h,after:this.x>(f.left+f.right)/2==u}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,l=i[r+1]-t;return on(e.dom,o,l).getClientRects()});return s.after?new _e(i[s.i+1],-1):new _e(i[s.i],1)}scanTile(e,t){if(!e.length)return new _e(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:on(a.dom,0,a.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new _e(i[s.i+1],-1):new _e(o,1)}},di="\uFFFF",ko=class{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(Y.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=di}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=F.get(s),l=s.nextSibling;if(l==t){o?.breakAfter&&!l&&i!=this.view.contentDOM&&this.lineBreak();break}let a=F.get(l);(o&&a?o.breakAfter:(o?o.breakAfter:hs(s))||hs(l)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!Hp(l,t)&&this.lineBreak(),s=l}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,l;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=s.exec(t))&&(r=l.index,o=l[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){let t=F.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.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 i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(Fp(e,i.node,i.offset)?t:0))}};function Fp(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Cc(e.docView.tile,t,i,0))){let a=r||o?[]:Jp(e),h=new ko(a,e);h.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=h.text,this.newSel=eO(a,this.bounds.from)}else{let a=e.observer.selectionRange,h=r&&r.node==a.focusNode&&r.offset==a.focusOffset||!ro(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),c=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!ro(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),f=e.viewport;if((T.ios||T.chrome)&&l.main.empty&&h!=c&&(f.from>0||f.to-1&&l.ranges.length>1)this.newSel=l.replaceRange(b.range(c,h));else if(e.lineWrapping&&c==h&&!(l.main.empty&&l.main.head==h)&&e.inputState.lastTouchTime>Date.now()-100){let u=e.coordsAtPos(h,-1),d=0;u&&(d=e.inputState.lastTouchY<=u.bottom?-1:1),this.newSel=b.create([b.cursor(h,d)])}else this.newSel=b.single(c,h)}}};function Cc(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,l=-1;for(let a=0,h=i,c=i;at)return Cc(f,e,t,h);if(u>=e&&s==-1&&(s=a,r=h),h>t&&f.dom.parentNode==n.dom){o=a,l=c;break}c=u,h=u+f.breakAfter}return{from:r,to:l<0?i+n.length:l,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function Zc(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,h=r.from,c=null;(o===8||T.android&&e.text.length=l&&r.to<=a&&(e.typeOver||f!=e.text)&&f.slice(0,r.from-l)==e.text.slice(0,r.from-l)&&f.slice(r.to-l)==e.text.slice(u=e.text.length-(f.length-(r.to-l)))?t={from:r.from,to:r.to,insert:E.of(e.text.slice(r.from-l,u).split(di))}:(d=Ac(f,e.text,h-l,c))&&(T.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==di+di&&d.toB--,t={from:l+d.from,to:l+d.toA,insert:E.of(e.text.slice(d.from,d.toB).split(di))})}else i&&(!n.hasFocus&&s.facet(ut)||Os(i,r))&&(i=null);if(!t&&!i)return!1;if((T.mac||T.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:E.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:T.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` - `&&n.lineWrapping&&(i&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:E.of([" "])}),t)return rl(n,t,i,o);if(i&&!Os(i,r)){let l=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(l=!0),a=n.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=Tc(s.facet(ln).map(h=>h(n)),i))),n.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function rl(n,e,t,i=-1){if(T.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(T.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&bi(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.lengths.head)&&bi(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&bi(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=Kp(n,e,t));return n.state.facet(mc).some(a=>a(n,e.from,e.to,r,l))||n.dispatch(l()),!0}function Kp(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let a=e.fromf(n)),h,a);e.from==c&&(o=c)}if(o>-1)i={changes:e,selection:b.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=r.frome.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let a=s.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let c=n.state.sliceDoc(e.from,e.to),f,u=t&&Pc(n,t.main.head);if(u){let p=e.insert.length-(e.to-e.from);f={from:u.from,to:u.to-p}}else f=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:a,range:h||p.map(a)};let O=p.to-d,g=O-c.length;if(n.state.sliceDoc(g,O)!=c||O>=f.from&&g<=f.to)return{range:p};let y=s.changes({from:g,to:O,insert:e.insert}),x=p.to-r.to;return{changes:y,range:h?b.range(Math.max(0,h.anchor+x),Math.max(0,h.head+x)):p.map(y)}})}else i={changes:a,selection:h&&s.selection.replaceRange(h)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:l,scrollIntoView:!0})}function Ac(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function Jp(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new ps(t,i)),(s!=t||r!=i)&&e.push(new ps(s,r))),e}function eO(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?b.single(t+e,i+e):null}function Os(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}var vo=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,T.safari&&e.contentDOM.addEventListener("input",()=>null),T.gecko&&pO(e.contentDOM.ownerDocument)}handleEvent(e){!lO(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=tO(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,l=i[r];l&&o!=!l.handlers.length&&(s.removeEventListener(r,this.handleEvent),l=null),l||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,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&&Rc.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),T.android&&T.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return T.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&!e.shiftKey&&((t=Mc.find(i=>i.keyCode==e.keyCode))&&!e.ctrlKey||iO.indexOf(e.key)>-1&&e.ctrlKey)?(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:T.safari&&!T.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!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 vh(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ae(t.state,s)}}}function tO(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let l in r){let a=r[l];a&&t(l).handlers.push(vh(i.value,a))}if(o)for(let l in o){let a=o[l];a&&t(l).observers.push(vh(i.value,a))}}for(let i in Ge)t(i).handlers.push(Ge[i]);for(let i in we)t(i).observers.push(we[i]);return e}var Mc=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],iO="dthko",Rc=[16,17,18,20,91,92,224,225],Gn=6;function Un(n){return Math.max(0,n)*.7+8}function nO(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}var $o=class{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=ic(e.contentDOM),this.atoms=e.state.facet(ln).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(Y.allowMultipleSelections)&&sO(e,t),this.dragging=oO(e,t)&&Ec(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&nO(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=sl(this.view);e.clientX-a.left<=s+Gn?t=-Un(s-e.clientX):e.clientX+a.right>=o-Gn&&(t=Un(e.clientX-o)),e.clientY-a.top<=r+Gn?i=-Un(r-e.clientY):e.clientY+a.bottom>=l-Gn&&(i=Un(e.clientY-l)),this.setScrollSpeed(t,i)}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(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=Tc(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function sO(n,e){let t=n.state.facet(uc);return t.length?t[0](e):T.mac?e.metaKey:e.ctrlKey}function rO(n,e){let t=n.state.facet(dc);return t.length?t[0](e):T.mac?!e.altKey:!e.ctrlKey}function oO(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=rn(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function lO(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=F.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}var Ge=Object.create(null),we=Object.create(null),Xc=T.ie&&T.ie_version<15||T.ios&&T.webkit_version<604;function aO(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),Lc(n,t.value)},50)}function Ps(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function Lc(n,e){e=Ps(n.state,el,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(Po!=null&&t.selection.ranges.every(a=>a.empty)&&Po==r.toString()){let a=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==a)return{range:h};a=c.from;let f=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:f},range:b.cursor(h.from+f.length)}})}else o?i=t.changeByRange(a=>{let h=r.line(s++);return{changes:{from:a.from,to:a.to,insert:h.text},range:b.cursor(a.from+h.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}we.scroll=n=>{n.inputState.lastScrollTop=n.scrollDOM.scrollTop,n.inputState.lastScrollLeft=n.scrollDOM.scrollLeft};we.wheel=we.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ge.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);we.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};we.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};Ge.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(pc))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=cO(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new $o(n,e,t,i)),i&&n.observer.ignore(()=>{nc(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function $h(n,e,t,i){if(i==1)return b.cursor(e,t);if(i==2)return qp(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,l=s?s.posAtEnd:r.to;return lDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Th+1)%3:1}function cO(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=Ec(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,l){let a=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),h,c=$h(n,a.pos,a.assoc,i);if(t.pos!=a.pos&&!o){let f=$h(n,t.pos,t.assoc,i),u=Math.min(f.from,c.from),d=Math.max(f.to,c.to);c=u1&&(h=fO(s,a.pos))?h:l?s.addRange(c):b.create([c])}}}function fO(n,e){for(let t=0;t=e)return b.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ge.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=b.range(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",Ps(n.state,tl,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ge.dragend=n=>(n.inputState.draggedContent=null,!1);function Zh(n,e,t,i){if(t=Ps(n.state,el,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&rO(n,e)?{from:r.from,to:r.to}:null,l={from:s,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(s,-1),head:a.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ge.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Zh(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),r()},l.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Zh(n,e,i,!0),!0}return!1};Ge.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=Xc?null:e.clipboardData;return t?(Lc(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(aO(n),!1)};function uO(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function dO(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:Ps(n,tl,e.join(n.lineBreak)),ranges:t,linewise:i}}var Po=null;Ge.copy=Ge.cut=(n,e)=>{if(!Ni(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=dO(n.state);if(!t&&!s)return!1;Po=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=Xc?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(uO(n,t),!1)};var Dc=be.define();function Wc(n,e){let t=[];for(let i of n.facet(gc)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:Dc.of(!0)}):null}function Bc(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=Wc(n.state,e);t?n.dispatch(t):n.update([])}},10)}we.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),Bc(n)};we.blur=n=>{n.observer.clearSelectionRange(),Bc(n)};we.compositionstart=we.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};we.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,T.chrome&&T.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};we.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ge.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let l=o[0],a=n.posAtDOM(l.startContainer,l.startOffset),h=n.posAtDOM(l.endContainer,l.endOffset);return rl(n,{from:a,to:h,insert:n.state.toText(r)},null),!0}}let s;if(T.chrome&&T.android&&(s=Mc.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return T.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),T.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>we.compositionend(n,e),20),!1};var Ah=new Set;function pO(n){Ah.has(n)||(Ah.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}var Mh=["pre-wrap","normal","pre-line","break-spaces"],Qi=!1;function Rh(){Qi=!1}var To=class{constructor(e){this.lineWrapping=e,this.doc=E.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Mh.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l||Math.abs(i-this.charWidth)>.1;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,a){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>ns&&(Qi=!0),this.height=e)}replace(e,t,i){return n.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let l=s.length-1;l>=0;l--){let{fromA:a,toA:h,fromB:c,toB:f}=s[l],u=r.lineAt(a,G.ByPosNoHeight,i.setDoc(t),0,0),d=u.to>=h?u:r.lineAt(h,G.ByPosNoHeight,i,0,0);for(f+=d.to-h,h=d.to;l>0&&u.from<=s[l-1].toA;)a=s[l-1].fromA,c=s[l-1].fromB,l--,ar*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,s-=l.size}else if(r>s*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,r-=l.size}else break;else if(s=r&&o(this.lineAt(0,G.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}},ze=class n extends gs{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new je(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof n||s instanceof St&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof St?s=new n(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):Te.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(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:""})`}},St=class n extends Te{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*r);o=a/r,this.length>r+1&&(l=(this.height-a)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:l}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,s);if(t.lineWrapping){let h=s+(e0){let r=i[i.length-1];r instanceof n?i[i.length-1]=new n(r.length+s):i.push(null,new n(s-1))}if(e>0){let r=i[0];r instanceof n?i[0]=new n(e+r.length):i.unshift(new n(e-1),null)}return Te.of(i)}decomposeLeft(e,t){t.push(new n(e-1),null)}decomposeRight(e,t){t.push(null,new n(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],l=Math.max(t,s.from),a=-1;for(s.from>t&&o.push(new n(s.from-t-1).updateHeight(e,t));l<=r&&s.more;){let c=e.doc.lineAt(l).length;o.length&&o.push(null);let f=s.heights[s.index++],u=0;f<0&&(u=-f,f=s.heights[s.index++]),a==-1?a=f:Math.abs(f-a)>=ns&&(a=-2);let d=new ze(c,f,u);d.outdated=!1,o.push(d),l+=c+1}l<=r&&o.push(null,new n(r-l).updateHeight(e,l));let h=Te.of(o);return(a<0||Math.abs(h.height-this.height)>=ns||Math.abs(a-this.heightMetrics(e,t).perLine)>=ns)&&(Qi=!0),ms(this,h)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},Zo=class extends Te{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return el))return h;let c=t==G.ByPosNoHeight?G.ByPosNoHeight:G.ByPos;return a?h.join(this.right.lineAt(l,c,i,o,l)):this.left.lineAt(l,c,i,s,r).join(h)}forEachLine(e,t,i,s,r,o){let l=s+this.left.height,a=r+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,G.ByPos,i,s,r);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,l,a,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let l of i)r.push(l);if(e>0&&Xh(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?Te.of(this.break?[e,null,t]:[e,t]):(this.left=ms(this.left,e),this.right=ms(this.right,t),this.setHeight(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,i=!1,s){let{left:r,right:o}=this,l=t+r.length+this.break,a=null;return s&&s.from<=t+r.length&&s.more?a=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=l+o.length&&s.more?a=o=o.updateHeight(e,l,i,s):o.updateHeight(e,l,i),a?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function Xh(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof St&&(i=n[e+1])instanceof St&&n.splice(e-1,3,new St(t.length+1+i.length))}var mO=5,Ao=class n{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 i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof ze?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new ze(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=mO)&&this.addLineDeco(s,r,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 ze(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new St(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof ze)return e;let t=new ze(0,-1,0);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,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof ze)&&!this.isCovered?this.nodes.push(new ze(0,-1,0)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&f.overflow!="visible"){let u=c.getBoundingClientRect();r=Math.max(r,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=Math.min(h==n.parentNode?s.innerHeight:a,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:r-t.left,right:Math.max(r,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function bO(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function xO(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var Ji=class{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new To(i),this.stateDeco=Eh(t),this.heightMap=Te.empty().applyChanges(this.stateDeco,E.empty,this.heightOracle.setDoc(t.doc),[new Ne(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Z.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new Oi(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?Lh:new Xo(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(qi(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=Eh(this.state);let s=e.changedRanges,r=Ne.extendWithRanges(s,gO(i,this.stateDeco,e?e.changes:Oe.empty(this.state.doc.length))),o=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);Rh(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||Qi)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let a=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.heada.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let h=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,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(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(bc)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?_.RTL:_.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let h=0,c=0;if(l.width&&l.height){let{scaleX:w,scaleY:k}=tc(t,l);(w>.005&&Math.abs(this.scaleX-w)>.005||k>.005&&Math.abs(this.scaleY-k)>.005)&&(this.scaleX=w,this.scaleY=k,h|=16,o=a=!0)}let f=(parseInt(i.paddingTop)||0)*this.scaleY,u=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=f||this.paddingBottom!=u)&&(this.paddingTop=f,this.paddingBottom=u,h|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=16);let d=ic(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=sc(this.scrollParent||e.win);let O=(this.printing?xO:yO)(t,this.paddingTop),g=O.top-this.pixelViewport.top,y=O.bottom-this.pixelViewport.bottom;this.pixelViewport=O;let x=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(x!=this.inView&&(this.inView=x,x&&(a=!0)),!this.inView&&!this.scrollTarget&&!bO(e.dom))return 0;let S=l.width;if((this.contentDOMWidth!=S||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,h|=16),a){let w=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(w)&&(o=!0),o||s.lineWrapping&&Math.abs(S-this.contentDOMWidth)>s.charWidth){let{lineHeight:k,charWidth:Q,textHeight:X}=e.docView.measureTextSize();o=k>0&&s.refresh(r,k,Q,X,Math.max(5,S/Q),w),o&&(e.docView.minWidth=0,h|=16)}g>0&&y>0?c=Math.max(g,y):g<0&&y<0&&(c=Math.min(g,y)),Rh();for(let k of this.viewports){let Q=k.from==this.viewport.from?w:e.docView.measureVisibleLineHeights(k);this.heightMap=(o?Te.empty().applyChanges(this.stateDeco,E.empty,this.heightOracle,[new Ne(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new Co(k.from,Q))}Qi&&(h|=2)}let C=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return C&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(c,this.scrollTarget),h|=this.updateForViewport()),(h&2||C)&&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 i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new Oi(s.lineAt(o-i*1e3,G.ByHeight,r,0,0).from,s.lineAt(l+(1-i)*1e3,G.ByHeight,r,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),f=s.lineAt(h,G.ByPos,r,0,0),u;t.y=="center"?u=(f.top+f.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=_.LTR&&!i)return[];let l=[],a=(c,f,u,d)=>{if(f-cc&&yy.from>=u.from&&y.to<=u.to&&Math.abs(y.from-c)y.fromx));if(!g){if(fS.from<=f&&S.to>=f)){let S=t.moveToLineBoundary(b.cursor(f),!1,!0).head;S>c&&(f=S)}let y=this.gapSize(u,c,f,d),x=i||y<2e6?y:2e6;g=new Ji(c,f,y,x)}l.push(g)},h=c=>{if(c.length2e6)for(let k of e)k.from>=c.from&&k.fromc.from&&a(c.from,d,c,f),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];W.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||qi(this.heightMap.lineAt(e,G.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)||qi(this.heightMap.lineAt(this.scaler.fromDOM(e),G.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}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 qi(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}},Oi=class{constructor(e,t){this.from=e,this.to=t}};function SO(n,e,t){let i=[],s=n,r=0;return W.spans(t,n,e,{span(){},point(o,l){o>s&&(i.push({from:s,to:o}),r+=o-s),s=l}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],l=o-r;if(i<=l)return r+i;i-=l}}function Hn(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function wO(n,e){for(let t of n)if(e(t))return t}var Lh={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function Eh(n){let e=n.facet($s).filter(i=>typeof i!="function"),t=n.facet(nl).filter(i=>typeof i!="function");return t.length&&e.push(W.join(t)),e}var Xo=class n{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,G.ByPos,e,0,0).top,c=t.lineAt(a,G.ByPos,e,0,0).bottom;return s+=c-h,{from:l,to:a,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let l of this.viewports)l.domTop=o+(l.top-r)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),r=l.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}};function qi(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new je(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>qi(s,e)):n._content)}var Kn=$.define({combine:n=>n.join(" ")}),Lo=$.define({combine:n=>n.indexOf(!0)>-1}),Eo=Be.newName(),zc=Be.newName(),_c=Be.newName(),Ic={"&light":"."+zc,"&dark":"."+_c};function Do(n,e,t){return new Be(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}var kO=Do("."+Eo,{"&":{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,overflowAnchor:"none"},".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:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".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",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&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,zIndex:300},"&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-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".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",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".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"}},Ic),QO={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Fr=T.ie&&T.ie_version<=11,Wo=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new oo,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 i of t)this.queue.push(i);(T.ie&&T.ie_version<=11||T.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&T.android&&e.constructor.EDIT_CONTEXT!==!1&&!(T.chrome&&T.chrome_version<126)&&(this.editContext=new Bo(e),e.state.facet(ut)&&(e.contentDOM.editContext=this.editContext.editContext)),Fr&&(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.type)&&!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,i)=>t!=e[i]))){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:i}=this,s=this.selectionRange;if(i.state.facet(ut)?i.root.activeElement!=this.dom:!Ni(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(T.ie&&T.ie_version<=11||T.android&&T.chrome)&&!i.state.selection.main.empty&&s.focusNode&&Gi(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=rn(e.root);if(!t)return!1;let i=T.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&vO(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=Ni(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&bi(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!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,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&Ni(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new Qo(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}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 i=this.view.state,s=Zc(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!Os(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Dh(t,e.previousSibling||e.target.previousSibling,-1),s=Dh(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):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?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(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?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(ut)!=e.state.facet(ut)&&(e.view.contentDOM.editContext=e.state.facet(ut)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function Dh(n,e,t){for(;e;){let i=F.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function Wh(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return Gi(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function vO(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return Wh(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?Wh(n,t):null}var Bo=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=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)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,l=this.toEditorPos(i.updateRangeStart),a=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:l,drifted:!1});let h=a-l>i.text.length;l==this.from&&rthis.to&&(a=r);let c=Ac(e.state.sliceDoc(l,a),i.text,(h?s.from:s.to)-l,h?"end":null);if(!c){let u=b.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));Os(u,s)||e.dispatch({selection:u,userEvent:"select"});return}let f={from:c.from+l,to:c.toA+l,insert:E.of(i.text.slice(c.from,c.toB).split(` -`))};if((T.mac||T.android)&&f.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(f={from:l,to:a,insert:E.of([i.text.replace("."," ")])}),this.pendingContextChange=f,!e.state.readOnly){let u=this.to-this.from+(f.to-f.from+f.insert.length);rl(e,f,b.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),f.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,l=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(r.rangeStart),h=this.toEditorPos(r.rangeEnd);if(a{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{this.editContext.updateControlBounds(i.contentDOM.getBoundingClientRect());let s=rn(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,l,a,h)=>{if(i)return;let c=h.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(h)){s=this.pendingContextChange=null,t+=c,this.to+=c;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=c,this.to+=c;else if(rthis.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),h.toString()),this.to+=c}t+=c}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&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)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},v=class n{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&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;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:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||bp(e.parent)||document,this.viewState=new ys(this,e.state||Y.create(e)),e.scrollTo&&e.scrollTo.is(Nn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(pi).map(s=>new Fi(s));for(let s of this.plugins)s.update(this);this.observer=new Wo(this),this.inputState=new vo(this),this.inputState.ensureHandlers(this.plugins),this.docView=new ds(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof ie?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,i=!1,s,r=this.state;for(let u of e){if(u.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=u.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,l=0,a=null;e.some(u=>u.annotation(Dc))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=Wc(r,o),a||(l=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(c=null)):this.observer.clear(),r.facet(Y.phrases)!=this.state.facet(Y.phrases))return this.setState(r);s=fs.create(this,r,e),s.flags|=l;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,{x:p,y:O}=this.state.facet(n.cursorScrollMargin);f=new Ui(d.empty?d:b.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",O,p)}for(let d of u.effects)d.is(Nn)&&(f=d.value.clip(this.state))}this.viewState.update(s,f),this.bidiCache=bs.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(Vi)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(Kn)!=s.state.facet(Kn)&&(this.viewState.mustMeasureContent=!0),(t||i||f||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let u of this.state.facet(co))try{u(s)}catch(d){ae(this.state,d,"update listener")}(a||c)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),c&&!Zc(this,c)&&h.force&&bi(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 i of this.plugins)i.destroy(this);this.viewState=new ys(this,e),this.plugins=e.facet(pi).map(i=>new Fi(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new ds(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(pi),i=e.state.facet(pi);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Fi(r));else{let l=this.plugins[o];l.mustUpdate=e,s.push(l)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-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,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let l=0;;l++){if(o<0)if(sc(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(s);r=d.from,o=d.top}this.updateState=1;let a=this.viewState.measure();if(!a&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let h=[];a&4||([this.measureRequests,h]=[h,this.measureRequests]);let c=h.map(d=>{try{return d.read(this)}catch(p){return ae(this.state,p),Bh}}),f=fs.create(this,this.state,[]),u=!1;f.flags|=a,t?t.flags|=a: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||p<-1)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let l of this.state.facet(co))l(t)}get themeClasses(){return Eo+" "+(this.state.facet(Lo)?_c:zc)+" "+this.state.facet(Kn)}updateAttrs(){let e=zh(this,wc,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(ut)?"true":"false",class:"cm-content",style:`${T.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),zh(this,il,t);let i=this.observer.ignore(()=>{let s=yh(this.contentDOM,this.contentAttrs,t),r=yh(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(n.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(Vi);let e=this.state.facet(n.cspNonce);Be.mount(this.root,this.styleModules.concat(kO).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;ti.plugin==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,i){return Ur(this,e,Qh(this,e,t,i))}moveByGroup(e,t){return Ur(this,e,Qh(this,e,t,i=>Gp(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),s=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return b.cursor(r.side(t,s)+e.from,r.forward(!t,s)?1:-1)}moveToLineBoundary(e,t,i=!0){return Np(this,e,t,i)}moveVertically(e,t,i){return Ur(this,e,Up(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=So(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),So(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let s=this.state.doc.lineAt(e),r=this.bidiSpans(s),o=r[Ie.find(r,e-s.from,-1,t)];return cs(i,o.dir==_.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(yc)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>$O)return cc(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||hc(r.isolates,i=Sh(this,e))))return r.order;i||(i=Sh(this,e));let s=Pp(e.text,t,i);return this.bidiCache.push(new bs(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||T.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{nc(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={}){var i,s,r,o;return Nn.of(new Ui(typeof e=="number"?b.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Nn.of(new Ui(b.cursor(i.from),"start","start",i.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 H.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return H.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=Be.newName(),s=[Kn.of(i),Vi.of(Do(`.${i}`,e))];return t&&t.dark&&s.push(Lo.of(!0)),s}static baseTheme(e){return xe.lowest(Vi.of(Do("."+Eo,e,Ic)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&F.get(i)||F.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}};v.styleModule=Vi;v.inputHandler=mc;v.clipboardInputFilter=el;v.clipboardOutputFilter=tl;v.scrollHandler=xc;v.focusChangeEffect=gc;v.perLineTextDirection=yc;v.exceptionSink=Oc;v.updateListener=co;v.editable=ut;v.mouseSelectionStyle=pc;v.dragMovesSelection=dc;v.clickAddsSelectionRange=uc;v.decorations=$s;v.blockWrappers=kc;v.outerDecorations=nl;v.atomicRanges=ln;v.bidiIsolatedRanges=Qc;v.cursorScrollMargin=$.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});v.scrollMargins=vc;v.darkTheme=Lo;v.cspNonce=$.define({combine:n=>n.length?n[0]:""});v.contentAttributes=il;v.editorAttributes=wc;v.lineWrapping=v.contentAttributes.of({class:"cm-lineWrapping"});v.announce=A.define();var $O=4096,Bh={},bs=class n{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:_.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&Ho(o,t)}return t}var PO=T.mac?"mac":T.windows?"win":T.linux?"linux":"key";function TO(n,e){let t=n.split(/-(?!$)/),i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,l;for(let a=0;ai.concat(s),[]))),t}function Vc(n,e,t){return qc(Yc(n.state),e,n,t)}var xt=null,ZO=4e3;function AO(n,e=PO){let t=Object.create(null),i=Object.create(null),s=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,l,a,h,c)=>{var f,u;let d=t[o]||(t[o]=Object.create(null)),p=l.split(/ (?!$)/).map(y=>TO(y,e));for(let y=1;y{let C=xt={view:S,prefix:x,scope:o};return setTimeout(()=>{xt==C&&(xt=null)},ZO),!0}]})}let O=p.join(" ");s(O,!1);let g=d[O]||(d[O]={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())||[]});a&&g.run.push(a),h&&(g.preventDefault=!0),c&&(g.stopPropagation=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){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,zo))}let a=o[e]||o.key;if(a)for(let h of l)r(h,a,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(h,"Shift-"+a,o.shift,o.preventDefault,o.stopPropagation)}return t}var zo=null;function qc(n,e,t,i){zo=e;let s=dh(e),r=le(s,0),o=Pe(r)==s.length&&s!=" ",l="",a=!1,h=!1,c=!1;xt&&xt.view==t&&xt.scope==i&&(l=xt.prefix+" ",Rc.indexOf(e.keyCode)<0&&(h=!0,xt=null));let f=new Set,u=g=>{if(g){for(let y of g.run)if(!f.has(y)&&(f.add(y),y(t)))return g.stopPropagation&&(c=!0),!0;g.preventDefault&&(g.stopPropagation&&(c=!0),h=!0)}return!1},d=n[i],p,O;return d&&(u(d[l+Jn(s,e,!o)])?a=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(T.windows&&e.ctrlKey&&e.altKey)&&!(T.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=ft[e.keyCode])&&p!=s?(u(d[l+Jn(p,e,!0)])||e.shiftKey&&(O=ui[e.keyCode])!=s&&O!=p&&u(d[l+Jn(O,e,!1)]))&&(a=!0):o&&e.shiftKey&&u(d[l+Jn(s,e,!0)])&&(a=!0),!a&&u(d._any)&&(a=!0)),h&&(a=!0),a&&c&&e.stopPropagation(),zo=null,a}var It=class n{constructor(e,t,i,s,r){this.className=e,this.left=t,this.top=i,this.width=s,this.height=r}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,i){if(i.empty){let s=e.coordsAtPos(i.head,i.assoc||1);if(!s)return[];let r=jc(e);return[new n(t,s.left-r.left,s.top-r.top,null,s.bottom-s.top)]}else return MO(e,t,i)}};function jc(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==_.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function Ih(n,e,t,i){let s=n.coordsAtPos(e,t*2);if(!s)return i;let r=n.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,l=n.posAtCoords({x:r.left+1,y:o}),a=n.posAtCoords({x:r.right-1,y:o});return l==null||a==null?i:{from:Math.max(i.from,Math.min(l,a)),to:Math.min(i.to,Math.max(l,a))}}function MO(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),s=Math.min(t.to,n.viewport.to),r=n.textDirection==_.LTR,o=n.contentDOM,l=o.getBoundingClientRect(),a=jc(n),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),f=l.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),u=l.right-(c?parseInt(c.paddingRight):0),d=xo(n,i,1),p=xo(n,s,-1),O=d.type==he.Text?d:null,g=p.type==he.Text?p:null;if(O&&(n.lineWrapping||d.widgetLineBreaks)&&(O=Ih(n,i,1,O)),g&&(n.lineWrapping||p.widgetLineBreaks)&&(g=Ih(n,s,-1,g)),O&&g&&O.from==g.from&&O.to==g.to)return x(S(t.from,t.to,O));{let w=O?S(t.from,null,O):C(d,!1),k=g?S(null,t.to,g):C(p,!0),Q=[];return(O||d).to<(g||p).from-(O&&g?1:0)||d.widgetLineBreaks>1&&w.bottom+n.defaultLineHeight/2M&&z.from=pe)break;Le>N&&L(Math.max(oe,N),w==null&&oe<=M,Math.min(Le,pe),k==null&&Le>=I,tt.dir)}if(N=Qe.to+1,N>=pe)break}return q.length==0&&L(M,w==null,I,k==null,n.textDirection),{top:X,bottom:D,horizontal:q}}function C(w,k){let Q=l.top+(k?w.top:w.bottom);return{top:Q,bottom:Q,horizontal:[]}}}function RO(n,e){return n.constructor==e.constructor&&n.eq(e)}var _o=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(ss)!=e.state.facet(ss)&&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,i=e.facet(ss);for(;t!RO(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let s of e)s.update&&t&&s.constructor&&this.drawn[i].constructor&&s.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(s.draw(),t);for(;t;){let s=t.nextSibling;t.remove(),t=s}this.drawn=e,T.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},ss=$.define();function Nc(n){return[H.define(e=>new _o(e,n)),ss.of(n)]}var vi=$.define({combine(n){return fe(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function Gc(n={}){return[vi.of(n),XO,LO,EO,bc.of(!0)]}function Uc(n){return n.startState.facet(vi)!=n.state.facet(vi)}var XO=Nc({above:!0,markers(n){let{state:e}=n,t=e.facet(vi),i=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty||t.drawRangeCursor&&!(r&&T.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",l=s.empty?s:b.cursor(s.head,s.assoc);for(let a of It.forRange(n,o,l))i.push(a)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Uc(n);return t&&Yh(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){Yh(e.state,n)},class:"cm-cursorLayer"});function Yh(n,e){e.style.animationDuration=n.facet(vi).cursorBlinkRate+"ms"}var LO=Nc({above:!1,markers(n){let e=[],{main:t,ranges:i}=n.state.selection;for(let s of i)if(!s.empty)for(let r of It.forRange(n,"cm-selectionBackground",s))e.push(r);if(T.ios&&!t.empty&&n.state.facet(vi).iosSelectionHandles){for(let s of It.forRange(n,"cm-selectionHandle cm-selectionHandle-start",b.cursor(t.from,1)))e.push(s);for(let s of It.forRange(n,"cm-selectionHandle cm-selectionHandle-end",b.cursor(t.to,1)))e.push(s)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||Uc(n)},class:"cm-selectionLayer"}),EO=xe.highest(v.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),Fc=A.define({map(n,e){return n==null?null:e.mapPos(n)}}),ji=K.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(Fc)?i.value:t,n)}}),DO=H.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(ji);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"),(n.startState.field(ji)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(ji),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(ji)!=n&&this.view.dispatch({effects:Fc.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Hc(){return[ji,DO]}function Vh(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,l;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;l=e.exec(r.value);)s(o+l.index,l)}function WO(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}var Io=class{constructor(e){let{regexp:t,decoration:i,decorate:s,boundary:r,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,s)this.addMatch=(l,a,h,c)=>s(c,h,h+l[0].length,l,a);else if(typeof i=="function")this.addMatch=(l,a,h,c)=>{let f=i(l,a,h);f&&c(h,h+l[0].length,f)};else if(i)this.addMatch=(l,a,h,c)=>c(h,h+l[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new $e,i=t.add.bind(t);for(let{from:s,to:r}of WO(e,this.maxLength))Vh(e.state.doc,this.regexp,s,r,(o,l)=>this.addMatch(l,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,l,a)=>{a>=e.view.viewport.from&&l<=e.view.viewport.to&&(i=Math.min(l,i),s=Math.max(a,s))}),e.viewportMoved||s-i>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),l=Math.min(r.to,s);if(l>=o){let a=e.state.doc.lineAt(o),h=a.toa.from;o--)if(this.boundary.test(a.text[o-1-a.from])){c=o;break}for(;lu.push(y.range(O,g));if(a==h)for(this.regexp.lastIndex=c-a.from;(d=this.regexp.exec(a.text))&&d.indexthis.addMatch(g,e,O,p));t=t.update({filterFrom:c,filterTo:f,filter:(O,g)=>Of,add:u})}}return t}},Yo=/x/.unicode!=null?"gu":"g",BO=new RegExp(`[\0-\b --\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,Yo),zO={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"},Hr=null;function _O(){var n;if(Hr==null&&typeof document<"u"&&document.body){let e=document.body.style;Hr=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Hr||!1}var rs=$.define({combine(n){let e=fe(n,{render:null,specialChars:BO,addSpecialChars:null});return(e.replaceTabs=!_O())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Yo)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Yo)),e}});function Kc(n={}){return[rs.of(n),IO()]}var qh=null;function IO(){return qh||(qh=H.fromClass(class{constructor(n){this.view=n,this.decorations=Z.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(rs)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Io({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=le(e[0],0);if(r==9){let o=s.lineAt(i),l=t.state.tabSize,a=ct(o.text,l,i-o.from);return Z.replace({widget:new qo((l-a%l)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=Z.replace({widget:new Vo(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(rs);n.startState.facet(rs)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}var YO="\u2022";function VO(n){return n>=32?YO:n==10?"\u2424":String.fromCharCode(9216+n)}var Vo=class extends ge{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=VO(this.code),i=e.state.phrase("Control character")+" "+(zO[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}},qo=class extends ge{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 Jc(){return jO}var qO=Z.line({class:"cm-activeLine"}),jO=H.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(qO.range(s.from)),e=s.from)}return Z.set(t)}},{decorations:n=>n.decorations});var jo=2e3;function NO(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>jo||t.off>jo||e.col<0||t.col<0){let o=Math.min(e.off,t.off),l=Math.max(e.off,t.off);for(let a=i;a<=s;a++){let h=n.doc.line(a);h.length<=l&&r.push(b.range(h.from+o,h.to+l))}}else{let o=Math.min(e.col,t.col),l=Math.max(e.col,t.col);for(let a=i;a<=s;a++){let h=n.doc.line(a),c=qn(h.text,o,n.tabSize,!0);if(c<0)r.push(b.cursor(h.to));else{let f=qn(h.text,l,n.tabSize);r.push(b.range(h.from+c,h.from+f))}}}return r}function GO(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function jh(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>jo?-1:s==i.length?GO(n,e.clientX):ct(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function UO(n,e){let t=jh(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let l=jh(n,s);if(!l)return i;let a=NO(n.state,t,l);return a.length?o?b.create(a.concat(i.ranges)):b.create(a):i}}:null}function ef(n){let e=n?.eventFilter||(t=>t.altKey&&t.button==0);return v.mouseSelectionStyle.of((t,i)=>e(i)?UO(t,i):null)}var FO={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},HO={style:"cursor: crosshair"};function tf(n={}){let[e,t]=FO[n.key||"Alt"],i=H.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,v.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?HO:null})]}var es="-10000px",xs=class{constructor(e,t,i,s){this.facet=t,this.createTooltipView=i,this.removeTooltipView=s,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let s=e.state.facet(this.facet),r=s.filter(a=>a);if(s===this.input){for(let a of this.tooltipViews)a.update&&a.update(e);return!1}let o=[],l=t?[]:null;for(let a=0;at[h]=a),t.length=l.length),this.input=s,this.tooltips=r,this.tooltipViews=o,!0}};function KO(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}var Kr=$.define({combine:n=>{var e,t,i;return{position:T.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||KO}}}),Nh=new WeakMap,ol=H.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Kr);this.position=e.position,this.parent=e.parent,this.classes=n.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 xs(n,an,(t,i)=>this.createTooltip(t,i),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(),n.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 n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Kr);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",t.dom.appendChild(s)}return t.dom.style.position=this.position,t.dom.style.top=es,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);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 n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(T.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(n=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),s=sl(this.view);return{visible:{left:i.left+s.left,top:i.top+s.top,right:i.right-s.right,bottom:i.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let l=this.manager.tooltipViews[o];return l.getCoords?l.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Kr).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let l of this.manager.tooltipViews)l.dom.style.position="absolute"}let{visible:t,space:i,scaleX:s,scaleY:r}=n,o=[];for(let l=0;l=Math.min(t.bottom,i.bottom)||f.rightMath.min(t.right,i.right)+.1)){c.style.top=es;continue}let d=a.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,O=u.right-u.left,g=(e=Nh.get(h))!==null&&e!==void 0?e:u.bottom-u.top,y=h.offset||em,x=this.view.textDirection==_.LTR,S=u.width>i.right-i.left?x?i.left:i.right-u.width:x?Math.max(i.left,Math.min(f.left-(d?14:0)+y.x,i.right-O)):Math.min(Math.max(i.left,f.left-O+(d?14:0)-y.x),i.right-O),C=this.above[l];!a.strictSide&&(C?f.top-g-p-y.yi.bottom)&&C==i.bottom-f.bottom>f.top-i.top&&(C=this.above[l]=!C);let w=(C?f.top-i.top:i.bottom-f.bottom)-p;if(wS&&X.topk&&(k=C?X.top-g-2-p:X.bottom+p+2);if(this.position=="absolute"?(c.style.top=(k-n.parent.top)/r+"px",Gh(c,(S-n.parent.left)/s)):(c.style.top=k/r+"px",Gh(c,S/s)),d){let X=f.left+(x?y.x:-y.x)-(S+14-7);d.style.left=X/s+"px"}h.overlap!==!0&&o.push({left:S,top:k,right:Q,bottom:k+g}),c.classList.toggle("cm-tooltip-above",C),c.classList.toggle("cm-tooltip-below",!C),h.positioned&&h.positioned(n.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 n of this.manager.tooltipViews)n.dom.style.top=es}},{eventObservers:{scroll(){this.maybeMeasure()}}});function Gh(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}var JO=v.baseTheme({".cm-tooltip":{zIndex:500,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:"14px",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"}}}),em={x:0,y:0},an=$.define({enables:[ol,JO]}),Ss=$.define({combine:n=>n.reduce((e,t)=>e.concat(t),[])}),ws=class n{static create(e){return new n(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new xs(e,Ss,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}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 i of this.manager.tooltipViews){let s=i[e];if(s!==void 0){if(t===void 0)t=s;else if(t!==s)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")}},tm=an.compute([Ss],n=>{let e=n.facet(Ss);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:ws.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),No=class{constructor(e,t,i,s,r){this.view=e,this.source=t,this.field=i,this.setHover=s,this.hoverTime=r,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;el.bottom||t.xl.right+e.defaultCharacterWidth)return;let a=e.bidiSpans(e.state.doc.lineAt(s)).find(c=>c.from<=s&&c.to>=s),h=a&&a.dir==_.RTL?-1:1;r=t.x{this.pending==l&&(this.pending=null,a&&!(Array.isArray(a)&&!a.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(a)?a:[a])}))},a=>ae(e.state,a,"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(ol),t=e?e.manager.tooltips.findIndex(i=>i.create==ws.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;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:s,tooltip:r}=this;if(s.length&&r&&!im(r.dom,e)||this.pending){let{pos:o}=s[0]||this.pending,l=(i=(t=s[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==l?this.view.posAtCoords(this.lastMove)!=o:!nm(this.view,o,l,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:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t),this.active.length&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}},ts=4;function im(n,e){let{left:t,right:i,top:s,bottom:r}=n.getBoundingClientRect(),o;if(o=n.querySelector(".cm-tooltip-arrow")){let l=o.getBoundingClientRect();s=Math.min(l.top,s),r=Math.max(l.bottom,r)}return e.clientX>=t-ts&&e.clientX<=i+ts&&e.clientY>=s-ts&&e.clientY<=r+ts}function nm(n,e,t,i,s,r){let o=n.scrollDOM.getBoundingClientRect(),l=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.rights||Math.min(o.bottom,l)=e&&a<=t}function nf(n,e={}){let t=A.define(),i=K.define({create(){return[]},update(s,r){if(s.length&&(e.hideOnChange&&(r.docChanged||r.selection)?s=[]:e.hideOn&&(s=s.filter(o=>!e.hideOn(r,o))),r.docChanged)){let o=[];for(let l of s){let a=r.changes.mapPos(l.pos,-1,se.TrackDel);if(a!=null){let h=Object.assign(Object.create(null),l);h.pos=a,h.end!=null&&(h.end=r.changes.mapPos(h.end)),o.push(h)}}s=o}for(let o of r.effects)o.is(t)&&(s=o.value),o.is(sm)&&(s=[]);return s},provide:s=>Ss.from(s)});return{active:i,extension:[i,H.define(s=>new No(s,n,i,t,e.hoverTime||300)),tm]}}function ll(n,e){let t=n.plugin(ol);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}var sm=A.define();var Uh=$.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function hn(n,e){let t=n.plugin(sf),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}var sf=H.fromClass(class{constructor(n){this.input=n.state.facet(jt),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(Uh);this.top=new mi(n,!0,e.topContainer),this.bottom=new mi(n,!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(n){let e=n.state.facet(Uh);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new mi(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new mi(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(jt);if(t!=this.input){let i=t.filter(a=>a),s=[],r=[],o=[],l=[];for(let a of i){let h=this.specs.indexOf(a),c;h<0?(c=a(n.view),l.push(c)):(c=this.panels[h],c.update&&c.update(n)),s.push(c),(c.top?r:o).push(c)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let a of l)a.dom.classList.add("cm-panel"),a.mount&&a.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>v.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})}),mi=class{constructor(e,t,i){this.view=e,this.top=t,this.container=i,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=Fh(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=Fh(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 Fh(n){let e=n.nextSibling;return n.remove(),e}var jt=$.define({enables:sf});function rf(n,e){let t,i=new Promise(o=>t=o),s=o=>rm(o,e,t);n.state.field(Jr,!1)?n.dispatch({effects:of.of(s)}):n.dispatch({effects:A.appendConfig.of(Jr.init(()=>[s]))});let r=lf.of(s);return{close:r,result:i.then(o=>((n.win.queueMicrotask||(a=>n.win.setTimeout(a,10)))(()=>{n.state.field(Jr).indexOf(s)>-1&&n.dispatch({effects:r})}),o))}}var Jr=K.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(of)?n=[t.value].concat(n):t.is(lf)&&(n=n.filter(i=>i!=t.value));return n},provide:n=>jt.computeN([n],e=>e.field(n))}),of=A.define(),lf=A.define();function rm(n,e,t){let i=e.content?e.content(n,()=>o(null)):null;if(!i){if(i=B("form"),e.input){let l=B("input",e.input);/^(text|password|number|email|tel|url)$/.test(l.type)&&l.classList.add("cm-textfield"),l.name||(l.name="input"),i.appendChild(B("label",(e.label||"")+": ",l))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(B("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let l=0;l{h.keyCode==27?(h.preventDefault(),o(null)):h.keyCode==13&&(h.preventDefault(),o(a))}),a.addEventListener("submit",h=>{h.preventDefault(),o(a)})}let r=B("div",i,B("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["\xD7"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(l){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(l)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let l;typeof e.focus=="string"?l=i.querySelector(e.focus):l=i.querySelector("input")||i.querySelector("button"),l&&"select"in l?l.select():l&&"focus"in l&&l.focus()}}}}var Ce=class extends We{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};Ce.prototype.elementClass="";Ce.prototype.toDOM=void 0;Ce.prototype.mapMode=se.TrackBefore;Ce.prototype.startSide=Ce.prototype.endSide=-1;Ce.prototype.point=!0;var os=$.define(),om=$.define(),lm={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>W.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},en=$.define();function al(n){return[af(),en.of({...lm,...n})]}var Go=$.define({combine:n=>n.some(e=>e)});function af(n){let e=[am];return n&&n.fixed===!1&&e.push(Go.of(!0)),e}var am=H.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(en).map(e=>new ks(n,e)),this.fixed=!n.state.facet(Go);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(Go)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=W.iter(this.view.state.facet(os),this.view.viewport.from),i=[],s=this.gutters.map(r=>new Fo(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let l of r.type)if(l.type==he.Text&&o){Uo(t,i,l.from);for(let a of s)a.line(this.view,l,i);o=!1}else if(l.widget)for(let a of s)a.widget(this.view,l)}else if(r.type==he.Text){Uo(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(en),t=n.state.facet(en),i=n.docChanged||n.heightChanged||n.viewportChanged||!W.eq(n.startState.facet(os),n.state.facet(os),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new ks(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>v.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==_.LTR?{left:i,right:s}:{right:i,left:s}})});function Hh(n){return Array.isArray(n)?n:[n]}function Uo(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}var Fo=class{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=W.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let l=new Qs(e,o,r,i);s.elements.push(l),s.dom.appendChild(l.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Uo(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(om)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},ks=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 i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let a=r.getBoundingClientRect();o=(a.top+a.bottom)/2}else o=s.clientY;let l=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,l,s)&&s.preventDefault()});this.markers=Hh(t.markers(e)),t.initialSpacer&&(this.spacer=new Qs(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=Hh(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!W.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},Qs=class{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),hm(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let l=o,a=rr(l,a,h)||o(l,a,h):o}return i}})}}),tn=class extends Ce{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function eo(n,e){return n.state.facet(gi).formatNumber(e,n.state)}var um=en.compute([gi],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(cm)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new tn(eo(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(fm)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(gi)!=e.state.facet(gi),initialSpacer(e){return new tn(eo(e,Kh(e.state.doc.lines)))},updateSpacer(e,t){let i=eo(t.view,Kh(t.view.state.doc.lines));return i==e.number?e:new tn(i)},domEventHandlers:n.facet(gi).domEventHandlers,side:"before"}));function hf(n={}){return[gi.of(n),af(),um]}function Kh(n){let e=9;for(;e{let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.head).from;s>t&&(t=s,e.push(dm.range(s)))}return W.of(e)});function cf(){return pm}var Om=0,cn=class{constructor(e,t){this.from=e,this.to=t}},R=class{constructor(e={}){this.id=Om++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=ue.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}};R.closedBy=new R({deserialize:n=>n.split(" ")});R.openedBy=new R({deserialize:n=>n.split(" ")});R.group=new R({deserialize:n=>n.split(" ")});R.isolate=new R({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});R.contextHash=new R({perNode:!0});R.lookAhead=new R({perNode:!0});R.mounted=new R({perNode:!0});var Nt=class{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[R.mounted.id]}},mm=Object.create(null),ue=class n{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):mm,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new n(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}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(R.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(R.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}};ue.none=new ue("",Object.create(null),0,8);var fn=class n{constructor(e){this.types=e;for(let t=0;t0;for(let a=this.cursor(o|U.IncludeAnonymous);;){let h=!1;if(a.from<=r&&a.to>=s&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;h=!0}for(;h&&i&&(l||!a.type.isAnonymous)&&i(a),!a.nextSibling();){if(!a.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:Ol(ue.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new n(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new n(ue.none,t,i,s)))}static build(e){return ym(e)}};J.empty=new J(ue.none,[],[],0);var hl=class n{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 n(this.buffer,this.index)}},vt=class n{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return ue.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function un(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?l.length:-1;e!=h;e+=t){let c=l[e],f=a[e]+o.from,u;if(!(!(r&U.EnterBracketed&&c instanceof J&&(u=Nt.get(c))&&!u.overlay&&u.bracketed&&i>=f&&i<=f+c.length)&&!pf(s,i,f,f+c.length))){if(c instanceof vt){if(r&U.ExcludeBuffers)continue;let d=c.findChild(0,c.buffer.length,t,i-f,s);if(d>-1)return new Gt(new fl(o,c,e,f),null,d)}else if(r&U.IncludeAnonymous||!c.type.isAnonymous||pl(c)){let d;if(!(r&U.IgnoreMounts)&&(d=Nt.get(c))&&!d.overlay)return new n(d.tree,f,e,o);let p=new n(c,f,e,o);return r&U.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?c.children.length-1:0,t,i,s,r)}}}if(r&U.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)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&U.IgnoreOverlays)&&(s=Nt.get(this._tree))&&s.overlay){let r=e-this.from,o=i&U.EnterBracketed&&s.bracketed;for(let{from:l,to:a}of s.overlay)if((t>0||o?l<=r:l=r:a>r))return new n(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}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 uf(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function cl(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}var fl=class{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}},Gt=class n extends Zs{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,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new n(this.context,this,r)}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)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&U.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new n(this.context,this,r)}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 n(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 n(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new J(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function Of(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let l=new Ye(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(un(l,e,t,!1))}}return s?Of(s):i}var dn=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~U.EnterBracketed,e instanceof Ye)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.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:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof Ye?(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,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}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,i=this.mode){return this.buffer?i&U.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&U.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&U.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,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<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,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let l=i._tree.children[r];if(this.mode&U.IncludeAnonymous||l instanceof vt||!l.type.isAnonymous||pl(l))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==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return cl(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}};function pl(n){return n.children.some(e=>e instanceof vt||!e.type.isAnonymous||pl(e))}function ym(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=1024,reused:r=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new hl(t,t.length):t,a=i.types,h=0,c=0;function f(w,k,Q,X,D,q){let{id:L,start:M,end:I,size:z}=l,N=c,pe=h;if(z<0)if(l.next(),z==-1){let at=r[L];Q.push(at),X.push(M-w);return}else if(z==-3){h=L;return}else if(z==-4){c=L;return}else throw new RangeError(`Unrecognized record size: ${z}`);let Qe=a[L],tt,oe,Le=M-w;if(I-M<=s&&(oe=g(l.pos-k,D))){let at=new Uint16Array(oe.size-oe.skip),Ee=l.pos-oe.size,it=at.length;for(;l.pos>Ee;)it=y(oe.start,at,it);tt=new vt(at,I-oe.start,i),Le=oe.start-w}else{let at=l.pos-z;l.next();let Ee=[],it=[],Lt=L>=o?L:-1,ri=0,Rn=I;for(;l.pos>at;)Lt>=0&&l.id==Lt&&l.size>=0?(l.end<=Rn-s&&(p(Ee,it,M,ri,l.end,Rn,Lt,N,pe),ri=Ee.length,Rn=l.end),l.next()):q>2500?u(M,at,Ee,it):f(M,at,Ee,it,Lt,q+1);if(Lt>=0&&ri>0&&ri-1&&ri>0){let Da=d(Qe,pe);tt=Ol(Qe,Ee,it,0,Ee.length,0,I-M,Da,Da)}else tt=O(Qe,Ee,it,I-M,N-I,pe)}Q.push(tt),X.push(Le)}function u(w,k,Q,X){let D=[],q=0,L=-1;for(;l.pos>k;){let{id:M,start:I,end:z,size:N}=l;if(N>4)l.next();else{if(L>-1&&I=0;z-=3)M[N++]=D[z],M[N++]=D[z+1]-I,M[N++]=D[z+2]-I,M[N++]=N;Q.push(new vt(M,D[2]-I,i)),X.push(I-w)}}function d(w,k){return(Q,X,D)=>{let q=0,L=Q.length-1,M,I;if(L>=0&&(M=Q[L])instanceof J){if(!L&&M.type==w&&M.length==D)return M;(I=M.prop(R.lookAhead))&&(q=X[L]+M.length+I)}return O(w,Q,X,D,q,k)}}function p(w,k,Q,X,D,q,L,M,I){let z=[],N=[];for(;w.length>X;)z.push(w.pop()),N.push(k.pop()+Q-D);w.push(O(i.types[L],z,N,q-D,M-q,I)),k.push(D-Q)}function O(w,k,Q,X,D,q,L){if(q){let M=[R.contextHash,q];L=L?[M].concat(L):[M]}if(D>25){let M=[R.lookAhead,D];L=L?[M].concat(L):[M]}return new J(w,k,Q,X,L)}function g(w,k){let Q=l.fork(),X=0,D=0,q=0,L=Q.end-s,M={size:0,start:0,skip:0};e:for(let I=Q.pos-w;Q.pos>I;){let z=Q.size;if(Q.id==k&&z>=0){M.size=X,M.start=D,M.skip=q,q+=4,X+=4,Q.next();continue}let N=Q.pos-z;if(z<0||N=o?4:0,Qe=Q.start;for(Q.next();Q.pos>N;){if(Q.size<0)if(Q.size==-3||Q.size==-4)pe+=4;else break e;else Q.id>=o&&(pe+=4);Q.next()}D=Qe,X+=z,q+=pe}return(k<0||X==w)&&(M.size=X,M.start=D,M.skip=q),M.size>4?M:void 0}function y(w,k,Q){let{id:X,start:D,end:q,size:L}=l;if(l.next(),L>=0&&X4){let I=l.pos-(L-4);for(;l.pos>I;)Q=y(w,k,Q)}k[--Q]=M,k[--Q]=q-w,k[--Q]=D-w,k[--Q]=X}else L==-3?h=X:L==-4&&(c=X);return Q}let x=[],S=[];for(;l.pos>0;)f(n.start||0,n.bufferStart||0,x,S,-1,0);let C=(e=n.length)!==null&&e!==void 0?e:x.length?S[0]+x[0].length:0;return new J(a[n.topID],x.reverse(),S.reverse(),C)}var df=new WeakMap;function Cs(n,e){if(!n.isAnonymous||e instanceof vt||e.type!=n)return 1;let t=df.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof J)){t=1;break}t+=Cs(n,i)}df.set(e,t)}return t}function Ol(n,e,t,i,s,r,o,l,a){let h=0;for(let p=i;p=c)break;k+=Q}if(S==C+1){if(k>c){let Q=p[C];d(Q.children,Q.positions,0,Q.children.length,O[C]+x);continue}f.push(p[C])}else{let Q=O[S-1]+p[S-1].length-w;f.push(Ol(n,p,O,C,S,w,Q,null,a))}u.push(w+x-r)}}return d(e,t,i,s,0),(l||a)(f,u,o)}var As=class{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Gt?this.setBuffer(e.context.buffer,e.index,t):e instanceof Ye&&this.map.set(e.tree,t)}get(e){return e instanceof Gt?this.getBuffer(e.context.buffer,e.index):e instanceof Ye?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)}},Ut=class n{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new n(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let c=l=i)for(;o&&o.from=u.from||f<=u.to||h){let d=Math.max(u.from,a)-h,p=Math.min(u.to,f)-h;u=d>=p?null:new n(d,p,u.tree,u.offset+h,l>0,!!c)}if(u&&s.push(u),o.to>f)break;o=rnew cn(s.from,s.to)):[new cn(0,0)]:[new cn(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}},dl=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 sb=new R({perNode:!0});var yl=class n{constructor(e,t,i,s,r,o,l,a,h,c=0,f){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=l,this.bufferBase=a,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,i=0){let s=e.parser.context;return new n(e,[],t,i,i,0,[],0,s?new Ms(s,s.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 i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(s,h)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)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,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let l=o.stateFlag(r,1);!l&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let s=this.pos;this.reducePos=this.pos=s+e.length,this.pushState(t,s),this.buffer.push(i,s,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&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new n(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new bl(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}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 s=[];for(let r=0,o;ra&1&&l==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!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=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-r;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,r+1);if(l!=null)return l}})};return i(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;t0&&this.emitLookAhead()}},Ms=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},bl=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,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}},xl=class n{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new n(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 n(this.stack,this.pos,this.index)}};function pn(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),r+=a,l)break;r*=46}t?t[s++]=r:t=new e(r)}return t}var Pi=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},mf=new Pi,Sl=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=mf,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 i=this.range,s=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=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=mf,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 i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}},$t=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;Sf(this.data,e,t,this.id,i.data,i.tokenPrecTable)}};$t.prototype.contextual=$t.prototype.fallback=$t.prototype.extend=!1;var Ti=class{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?pn(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(Sf(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}};Ti.prototype.contextual=$t.prototype.fallback=$t.prototype.extend=!1;var Pt=class{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}};function Sf(n,e,t,i,s,r){let o=0,l=1<0){let p=n[d];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||xm(p,e.token.value,s,r))){e.acceptToken(p);break}}let c=e.next,f=0,u=n[o+2];if(e.next<0&&u>f&&n[h+u*3-3]==65535){o=n[h+u*3-1];continue e}for(;f>1,p=h+d+(d<<1),O=n[p],g=n[p+1]||65536;if(c=g)f=d+1;else{o=n[p+2],e.advance();continue e}}break}}function gf(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function xm(n,e,t,i){let s=gf(t,i,e);return s<0||gf(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}var wl=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?yf(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?yf(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(r instanceof J){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}},kl=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Pi)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hf.end+25&&(a=Math.max(f.lookAhead,a)),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&&(i=f,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new Pi,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Pi,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;re.bufferLength*4?new wl(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;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)i.push(l);else{if(this.advanceStack(l,i,e))continue;{s||(s=[],r=[]),s.push(l);let a=this.tokens.getMainToken(l);r.push(a.value,a.end)}}break}}if(!i.length){let o=s&&Sm(s);if(o)return Ze&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw Ze&&s&&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&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return Ze&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&s>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(s);f;){let u=this.parser.nodeSet.types[f.type.id]==f.type?r.getGoto(e.state,f.type.id):-1;if(u>-1&&f.length&&(!h||(f.prop(R.contextHash)||0)==c))return e.useNode(f,u),Ze&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(f.type.id)})`),!0;if(!(f instanceof J)||f.children.length==0||f.positions[0]>0)break;let d=f.children[0];if(d instanceof J&&f.positions[0]==0)f=d;else break}}let l=r.stateSlot(e.state,4);if(l>0)return e.reduce(l),Ze&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hs?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return bf(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o ":"";if(l.deadEnd&&(r||(r=!0,l.restart(),Ze&&console.log(c+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let f=l.split(),u=c;for(let d=0;d<10&&f.forceReduce()&&(Ze&&console.log(u+this.stackID(f)+" (via force-reduce)"),!this.advanceFully(f,i));d++)Ze&&(u=this.stackID(f)+" -> ");for(let d of l.recoverByInsert(a))Ze&&console.log(c+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),Ze&&console.log(c+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),bf(l,i)):(!s||s.scoren,Rs=class{constructor(e){this.start=e.start,this.shift=e.shift||gl,this.reduce=e.reduce||gl,this.reuse=e.reuse||gl,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}},Xs=class n extends $i{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 l=0;le.topRules[l][1]),s=[];for(let l=0;l=0)r(c,a,l[h++]);else{let f=l[h+-c];for(let u=-c;u>0;u--)r(l[h++],a,f);h++}}}this.nodeSet=new fn(t.map((l,a)=>ue.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:s[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=pn(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new $t(o,l):l),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,i){let s=new Ql(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],l=o&1,a=s[r++];if(l&&i)return a;for(let h=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Ot(this.data,r+2);else break;s=t(Ot(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Ot(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(n.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(l=>l.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=xf(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),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}var wm=0,Ue=class n{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=wm++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof n&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new n(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new Ws(e);return i=>i.modified.indexOf(t)>-1?i:Ws.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}},km=0,Ws=class n{constructor(e){this.name=e,this.instances=[],this.id=km++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&Qm(t,l.modified));if(i)return i;let s=[],r=new Ue(e.name,s,e,t);for(let l of t)l.instances.push(r);let o=vm(t);for(let l of e.set)if(!l.modified.length)for(let a of o)s.push(n.get(l,a));return r}};function Qm(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function vm(n){let e=[[]];for(let t=0;ti.length-t.length)}function Bs(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,l=s;for(let f=0;;){if(l=="..."&&f>0&&f+3==s.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+s);if(r.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),f+=u[0].length,f==s.length)break;let d=s[f++];if(f==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);l=s.slice(f)}let a=r.length-1,h=r[a];if(!h)throw new RangeError("Invalid path: "+s);let c=new Ht(i,o,a>0?r.slice(0,a):null);e[h]=c.sort(e[h])}}return Qf.add(e)}var Qf=new R({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth>=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Ht(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}}),Ht=class{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let l of r)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function $m(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function vf(n,e,t,i=0,s=n.length){let r=new Pl(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}var Pl=class{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,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,i,s,r){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=s,c=Pm(e)||Ht.empty,f=$m(r,c.tags);if(f&&(h&&(h+=" "),h+=f,c.mode==1&&(s+=(s?" ":"")+f)),this.startSpan(Math.max(t,l),h),c.opaque)return;let u=e.tree&&e.tree.prop(R.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+l,1),p=this.highlighters.filter(g=>!g.scope||g.scope(u.tree.type)),O=e.firstChild();for(let g=0,y=l;;g++){let x=g=S||!e.nextSibling())););if(!x||S>i)break;y=x.to+l,y>t&&(this.highlightRange(d.cursor(),Math.max(t,x.from+l),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),h))}O&&e.parent()}else if(e.firstChild()){u&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}};function Pm(n){let e=n.type.prop(Qf);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}var P=Ue.define,Ls=P(),Tt=P(),wf=P(Tt),kf=P(Tt),Ct=P(),Es=P(Ct),$l=P(Ct),lt=P(),Ft=P(lt),rt=P(),ot=P(),Tl=P(),On=P(Tl),Ds=P(),m={comment:Ls,lineComment:P(Ls),blockComment:P(Ls),docComment:P(Ls),name:Tt,variableName:P(Tt),typeName:wf,tagName:P(wf),propertyName:kf,attributeName:P(kf),className:P(Tt),labelName:P(Tt),namespace:P(Tt),macroName:P(Tt),literal:Ct,string:Es,docString:P(Es),character:P(Es),attributeValue:P(Es),number:$l,integer:P($l),float:P($l),bool:P(Ct),regexp:P(Ct),escape:P(Ct),color:P(Ct),url:P(Ct),keyword:rt,self:P(rt),null:P(rt),atom:P(rt),unit:P(rt),modifier:P(rt),operatorKeyword:P(rt),controlKeyword:P(rt),definitionKeyword:P(rt),moduleKeyword:P(rt),operator:ot,derefOperator:P(ot),arithmeticOperator:P(ot),logicOperator:P(ot),bitwiseOperator:P(ot),compareOperator:P(ot),updateOperator:P(ot),definitionOperator:P(ot),typeOperator:P(ot),controlOperator:P(ot),punctuation:Tl,separator:P(Tl),bracket:On,angleBracket:P(On),squareBracket:P(On),paren:P(On),brace:P(On),content:lt,heading:Ft,heading1:P(Ft),heading2:P(Ft),heading3:P(Ft),heading4:P(Ft),heading5:P(Ft),heading6:P(Ft),contentSeparator:P(lt),list:P(lt),quote:P(lt),emphasis:P(lt),strong:P(lt),link:P(lt),monospace:P(lt),strikethrough:P(lt),inserted:P(),deleted:P(),changed:P(),invalid:P(),meta:Ds,documentMeta:P(Ds),annotation:P(Ds),processingInstruction:P(Ds),definition:Ue.defineModifier("definition"),constant:Ue.defineModifier("constant"),function:Ue.defineModifier("function"),standard:Ue.defineModifier("standard"),local:Ue.defineModifier("local"),special:Ue.defineModifier("special")};for(let n in m){let e=m[n];e instanceof Ue&&(e.name=n)}var hb=Cl([{tag:m.link,class:"tok-link"},{tag:m.heading,class:"tok-heading"},{tag:m.emphasis,class:"tok-emphasis"},{tag:m.strong,class:"tok-strong"},{tag:m.keyword,class:"tok-keyword"},{tag:m.atom,class:"tok-atom"},{tag:m.bool,class:"tok-bool"},{tag:m.url,class:"tok-url"},{tag:m.labelName,class:"tok-labelName"},{tag:m.inserted,class:"tok-inserted"},{tag:m.deleted,class:"tok-deleted"},{tag:m.literal,class:"tok-literal"},{tag:m.string,class:"tok-string"},{tag:m.number,class:"tok-number"},{tag:[m.regexp,m.escape,m.special(m.string)],class:"tok-string2"},{tag:m.variableName,class:"tok-variableName"},{tag:m.local(m.variableName),class:"tok-variableName tok-local"},{tag:m.definition(m.variableName),class:"tok-variableName tok-definition"},{tag:m.special(m.variableName),class:"tok-variableName2"},{tag:m.definition(m.propertyName),class:"tok-propertyName tok-definition"},{tag:m.typeName,class:"tok-typeName"},{tag:m.namespace,class:"tok-namespace"},{tag:m.className,class:"tok-className"},{tag:m.macroName,class:"tok-macroName"},{tag:m.propertyName,class:"tok-propertyName"},{tag:m.operator,class:"tok-operator"},{tag:m.comment,class:"tok-comment"},{tag:m.meta,class:"tok-meta"},{tag:m.invalid,class:"tok-invalid"},{tag:m.punctuation,class:"tok-punctuation"}]);var Tm=316,Cm=317,$f=1,Zm=2,Am=3,Mm=4,Rm=318,Xm=320,Lm=321,Em=5,Dm=6,Wm=0,Al=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],Pf=125,Bm=59,Ml=47,zm=42,_m=43,Im=45,Ym=60,Vm=44,qm=63,jm=46,Nm=91,Gm=new Rs({start:!1,shift(n,e){return e==Em||e==Dm||e==Xm?n:e==Lm},strict:!1}),Um=new Pt((n,e)=>{let{next:t}=n;(t==Pf||t==-1||e.context)&&n.acceptToken(Rm)},{contextual:!0,fallback:!0}),Fm=new Pt((n,e)=>{let{next:t}=n,i;Al.indexOf(t)>-1||t==Ml&&((i=n.peek(1))==Ml||i==zm)||t!=Pf&&t!=Bm&&t!=-1&&!e.context&&n.acceptToken(Tm)},{contextual:!0}),Hm=new Pt((n,e)=>{n.next==Nm&&!e.context&&n.acceptToken(Cm)},{contextual:!0}),Km=new Pt((n,e)=>{let{next:t}=n;if(t==_m||t==Im){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift($f);n.acceptToken(i?$f:Zm)}}else t==qm&&n.peek(1)==jm&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(Am))},{contextual:!0});function Zl(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}var Jm=new Pt((n,e)=>{if(n.next!=Ym||!e.dialectEnabled(Wm)||(n.advance(),n.next==Ml))return;let t=0;for(;Al.indexOf(n.next)>-1;)n.advance(),t++;if(Zl(n.next,!0)){for(n.advance(),t++;Zl(n.next,!1);)n.advance(),t++;for(;Al.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==Vm)return;for(let i=0;;i++){if(i==7){if(!Zl(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(Mm,-t)}),eg=Bs({"get set async static":m.modifier,"for while do if else switch try catch finally return throw break continue default case defer":m.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":m.operatorKeyword,"let var const using function class extends":m.definitionKeyword,"import export from":m.moduleKeyword,"with debugger new":m.keyword,TemplateString:m.special(m.string),super:m.atom,BooleanLiteral:m.bool,this:m.self,null:m.null,Star:m.modifier,VariableName:m.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":m.function(m.variableName),VariableDefinition:m.definition(m.variableName),Label:m.labelName,PropertyName:m.propertyName,PrivatePropertyName:m.special(m.propertyName),"CallExpression/MemberExpression/PropertyName":m.function(m.propertyName),"FunctionDeclaration/VariableDefinition":m.function(m.definition(m.variableName)),"ClassDeclaration/VariableDefinition":m.definition(m.className),"NewExpression/VariableName":m.className,PropertyDefinition:m.definition(m.propertyName),PrivatePropertyDefinition:m.definition(m.special(m.propertyName)),UpdateOp:m.updateOperator,"LineComment Hashbang":m.lineComment,BlockComment:m.blockComment,Number:m.number,String:m.string,Escape:m.escape,ArithOp:m.arithmeticOperator,LogicOp:m.logicOperator,BitOp:m.bitwiseOperator,CompareOp:m.compareOperator,RegExp:m.regexp,Equals:m.definitionOperator,Arrow:m.function(m.punctuation),": Spread":m.punctuation,"( )":m.paren,"[ ]":m.squareBracket,"{ }":m.brace,"InterpolationStart InterpolationEnd":m.special(m.brace),".":m.derefOperator,", ;":m.separator,"@":m.meta,TypeName:m.typeName,TypeDefinition:m.definition(m.typeName),"type enum interface implements namespace module declare":m.definitionKeyword,"abstract global Privacy readonly override":m.modifier,"is keyof unique infer asserts":m.operatorKeyword,JSXAttributeValue:m.attributeValue,JSXText:m.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":m.angleBracket,"JSXIdentifier JSXNameSpacedName":m.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":m.attributeName,"JSXBuiltin/JSXIdentifier":m.standard(m.tagName)}),tg={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},ig={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},ng={__proto__:null,"<":193},Tf=Xs.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}Q!L^O'#DvO:UQlO'#EOO:]QlO'#EQO9kQ`O'#GsO:dQMhO'#CoO:rQ`O'#EnO:}Q`O'#EyO;hQMhO'#FeO;xQ`O'#GsOOQO'#K`'#K`O;}Q`O'#K`O<]Q`O'#G{O<]Q`O'#G|O<]Q`O'#HOO9kQ`O'#HRO=SQ`O'#HUO>kQ`O'#CeO>{Q`O'#HcO?TQ`O'#HiO?TQ`O'#HkO`QlO'#HmO?TQ`O'#HoO?TQ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PQ9^7OQ:W8cQ:b8vQ:g8|Q:n9]Q;U:XQ;]:cQ;a:oQ;l;VR;o;^Q%zyQ'd!iQ'o!uU+m%{%|%}Q-W'VU-k'e'f'gS-o'k'uQ0Q*jS1Q+n+oQ2o-YS2{-l-mQ3S-tS4p0R0UQ5b1RQ6v2uQ6y2|Q7O3TU7{4r4s4vQ9z7}R;O9{S$wi>PR*{%VU%Ui%V>PR0f*yQ$viS(u#v+iS)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.lPQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.nSR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:Gm,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[eg],sk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OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",tokenizers:[Fm,Hm,Km,Jm,2,3,4,5,6,7,8,9,10,11,12,13,14,Um,new Ti("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new Ti("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>tg[n]||-1},{term:343,get:n=>ig[n]||-1},{term:95,get:n=>ng[n]||-1}],tokenPrec:15201});var Rl,Ci=new R;function ql(n){return $.define({combine:n?e=>e.concat(n):void 0})}var Vs=new R,Ae=class{constructor(e,t,i=[],s=""){this.data=e,this.name=s,Y.prototype.hasOwnProperty("tree")||Object.defineProperty(Y.prototype,"tree",{get(){return ee(this)}}),this.parser=t,this.extension=[Zt.of(this),Y.languageData.of((r,o,l)=>{let a=Cf(r,o,l),h=a.type.prop(Ci);if(!h)return[];let c=r.facet(h),f=a.type.prop(Vs);if(f){let u=a.resolve(o-a.from,l);for(let d of f)if(d.test(u,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(c)}}return c})].concat(i)}isActiveAt(e,t,i=-1){return Cf(e,t,i).type.prop(Ci)==this.data}findRegions(e){let t=e.facet(Zt);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop(Ci)==this.data){i.push({from:o,to:o+r.length});return}let l=r.prop(R.mounted);if(l){if(l.tree.prop(Ci)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+r.length});return}else if(l.overlay){let a=i.length;if(s(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new n(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function ee(n){let e=n.field(Ae.state,!1);return e?e.tree:J.empty}var Dl=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 i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}},mn=null,Wl=class n{constructor(e,t,i=[],s,r,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new n(e,t,[],J.empty,0,i,[],null)}startParse(){return this.parser.startParse(new Dl(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=J.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}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(Ut.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=mn;mn=this;try{return e()}finally{mn=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Zf(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,c,f,u)=>a.push({fromA:h,toA:c,fromB:f,toB:u})),i=Ut.applyChanges(i,a),s=J.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),f=e.mapPos(h.to,-1);ce.from&&(this.fragments=Zf(this.fragments,s,r),this.skipped.splice(i--,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 $i{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let a=mn;if(a){for(let h of s)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new J(ue.none,[],[],o-r)},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 mn}};function Zf(n,e,t){return Ut.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}var yn=class n{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),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new n(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=Wl.create(e.facet(Zt).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new n(i)}};Ae.state=K.define({create:yn.init,update(n,e){for(let t of e.effects)if(t.is(Ae.setState))return t.value;return e.startState.facet(Zt)!=e.state.facet(Zt)?yn.init(e.state):n.apply(e)}});var Df=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Df=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var Xl=typeof navigator<"u"&&(!((Rl=navigator.scheduling)===null||Rl===void 0)&&Rl.isInputPending)?()=>navigator.scheduling.isInputPending():null,sg=H.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(Ae.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(Ae.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Df(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,a=r.context.work(()=>Xl&&Xl()||Date.now()>o,s+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:Ae.setState.of(new yn(r.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ae(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()}}}),Zt=$.define({combine(n){return n.length?n[0]:null},enables:n=>[Ae.state,sg,v.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]}),_s=class{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}};var rg=$.define(),Ai=$.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function bn(n){let e=n.facet(Ai);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Mi(n,e){let t="",i=n.tabSize,s=n.facet(Ai)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=e?og(n,t,e):null}var Kt=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=bn(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return ct(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},jl=new R;function og(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return Wf(i,n,t)}function Wf(n,e,t){for(let i=n;i;i=i.next){let s=ag(i.node);if(s)return s(Bl.create(e,t,i))}return 0}function lg(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function ag(n){let e=n.type.prop(jl);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(R.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>zf(o,!0,1,void 0,r&&!lg(o)?s.from:void 0)}return n.parent==null?hg:null}function hg(){return 0}var Bl=class n extends Kt{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new n(e,t,i)}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 i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(cg(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return Wf(this.context.next,this.base,this.pos)}};function cg(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function fg(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped){if(a.from>=o)return null;let h=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+h}}l=a.to}}function Bf({closing:n,align:e=!0,units:t=1}){return i=>zf(i,e,t,n)}function zf(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,l=i&&r.slice(o,o+i.length)==i||s==n.pos+o,a=e?fg(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}var _f=n=>n.baseIndent;function js({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}var ug=200;function If(){return Y.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+ug)return n;let r=t.sliceString(s.from,i);if(!e.some(h=>h.test(r)))return n;let{state:o}=n,l=-1,a=[];for(let{head:h}of o.selection.ranges){let c=o.doc.lineAt(h);if(c.from==l)continue;l=c.from;let f=qs(o,c.from);if(f==null)continue;let u=/^\s*/.exec(c.text)[0],d=Mi(o,f);u!=d&&a.push({from:c.from,to:c.from+u.length,insert:d})}return a.length?[n,{changes:a,sequential:!0}]:n})}var dg=$.define(),Nl=new R;function Yf(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(r&&l.from=e&&h.to>t&&(r=h)}}return r}function Og(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function Is(n,e,t){for(let i of n.facet(dg)){let s=i(n,e,t);if(s)return s}return pg(n,e,t)}function Vf(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}var Ns=A.define({map:Vf}),xn=A.define({map:Vf});function qf(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}var Jt=K.define({create(){return Z.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((t,i)=>n=Af(n,t,i)),n=n.map(e.changes);for(let t of e.effects)if(t.is(Ns)&&!mg(n,t.value.from,t.value.to)){let{preparePlaceholder:i}=e.state.facet(Gl),s=i?Z.replace({widget:new zl(i(e.state,t.value))}):Mf;n=n.update({add:[s.range(t.value.from,t.value.to)]})}else t.is(xn)&&(n=n.update({filter:(i,s)=>t.value.from!=i||t.value.to!=s,filterFrom:t.value.from,filterTo:t.value.to}));return e.selection&&(n=Af(n,e.selection.main.head)),n},provide:n=>v.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{se&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(s,r)=>s>=t||r<=e}):n}function Ys(n,e,t){var i;let s=null;return(i=n.field(Jt,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!s||s.from>r)&&(s={from:r,to:o})}),s}function mg(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function jf(n,e){return n.field(Jt,!1)?e:e.concat(A.appendConfig.of(Uf()))}var gg=n=>{for(let e of qf(n)){let t=Is(n.state,e.from,e.to);if(t)return n.dispatch({effects:jf(n.state,[Ns.of(t),Nf(n,t)])}),!0}return!1},yg=n=>{if(!n.state.field(Jt,!1))return!1;let e=[];for(let t of qf(n)){let i=Ys(n.state,t.from,t.to);i&&e.push(xn.of(i),Nf(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function Nf(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return v.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}var bg=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(Jt,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(xn.of({from:i,to:s}))}),n.dispatch({effects:t}),!0};var Gf=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:gg},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:yg},{key:"Ctrl-Alt-[",run:bg},{key:"Ctrl-Alt-]",run:xg}],Sg={placeholderDOM:null,preparePlaceholder:null,placeholderText:"\u2026"},Gl=$.define({combine(n){return fe(n,Sg)}});function Uf(n){let e=[Jt,kg];return n&&e.push(Gl.of(n)),e}function Ff(n,e){let{state:t}=n,i=t.facet(Gl),s=o=>{let l=n.lineBlockAt(n.posAtDOM(o.target)),a=Ys(n.state,l.from,l.to);a&&n.dispatch({effects:xn.of(a)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,s,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}var Mf=Z.replace({widget:new class extends ge{toDOM(n){return Ff(n,null)}}}),zl=class extends ge{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return Ff(e,this.value)}},wg={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},gn=class extends Ce{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 Hf(n={}){let e={...wg,...n},t=new gn(e,!0),i=new gn(e,!1),s=H.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(Zt)!=o.state.facet(Zt)||o.startState.field(Jt,!1)!=o.state.field(Jt,!1)||ee(o.startState)!=ee(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let l=new $e;for(let a of o.viewportLineBlocks){let h=Ys(o.state,a.from,a.to)?i:Is(o.state,a.from,a.to)?t:null;h&&l.add(a.from,a.from,h)}return l.finish()}}),{domEventHandlers:r}=e;return[s,al({class:"cm-foldGutter",markers(o){var l;return((l=o.plugin(s))===null||l===void 0?void 0:l.markers)||W.empty},initialSpacer(){return new gn(e,!1)},domEventHandlers:{...r,click:(o,l,a)=>{if(r.click&&r.click(o,l,a))return!0;let h=Ys(o.state,l.from,l.to);if(h)return o.dispatch({effects:xn.of(h)}),!0;let c=Is(o.state,l.from,l.to);return c?(o.dispatch({effects:Ns.of(c)}),!0):!1}}}),Uf()]}var kg=v.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"}}),Zi=class n{constructor(e,t){this.specs=e;let i;function s(l){let a=Be.newName();return(i||(i=Object.create(null)))["."+a]=l,a}let r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof Ae?l=>l.prop(Ci)==o.data:o?l=>l==o:void 0,this.style=Cl(e.map(l=>({tag:l.tag,class:l.class||s(Object.assign({},l,{tag:null}))})),{all:r}).style,this.module=i?new Be(i):null,this.themeType=t.themeType}static define(e,t){return new n(e,t||{})}},_l=$.define(),Kf=$.define({combine(n){return n.length?[n[0]]:null}});function Ll(n){let e=n.facet(_l);return e.length?e:n.facet(Kf)}function Gs(n,e){let t=[Qg],i;return n instanceof Zi&&(n.module&&t.push(v.styleModule.of(n.module)),i=n.themeType),e?.fallback?t.push(Kf.of(n)):i?t.push(_l.computeN([v.darkTheme],s=>s.facet(v.darkTheme)==(i=="dark")?[n]:[])):t.push(_l.of(n)),t}var Il=class{constructor(e){this.markCache=Object.create(null),this.tree=ee(e.state),this.decorations=this.buildDeco(e,Ll(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=ee(e.state),i=Ll(e.state),s=i!=Ll(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return Z.none;let i=new $e;for(let{from:s,to:r}of e.visibleRanges)vf(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=Z.mark({class:a})))},s,r);return i.finish()}},Qg=xe.high(H.fromClass(Il,{decorations:n=>n.decorations})),Jf=Zi.define([{tag:m.meta,color:"#404740"},{tag:m.link,textDecoration:"underline"},{tag:m.heading,textDecoration:"underline",fontWeight:"bold"},{tag:m.emphasis,fontStyle:"italic"},{tag:m.strong,fontWeight:"bold"},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.keyword,color:"#708"},{tag:[m.atom,m.bool,m.url,m.contentSeparator,m.labelName],color:"#219"},{tag:[m.literal,m.inserted],color:"#164"},{tag:[m.string,m.deleted],color:"#a11"},{tag:[m.regexp,m.escape,m.special(m.string)],color:"#e40"},{tag:m.definition(m.variableName),color:"#00f"},{tag:m.local(m.variableName),color:"#30a"},{tag:[m.typeName,m.namespace],color:"#085"},{tag:m.className,color:"#167"},{tag:[m.special(m.variableName),m.macroName],color:"#256"},{tag:m.definition(m.propertyName),color:"#00c"},{tag:m.comment,color:"#940"},{tag:m.invalid,color:"#f00"}]),vg=v.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),eu=1e4,tu="()[]{}",iu=$.define({combine(n){return fe(n,{afterCursor:!0,brackets:tu,maxScanDistance:eu,renderMatch:Tg})}}),$g=Z.mark({class:"cm-matchingBracket"}),Pg=Z.mark({class:"cm-nonmatchingBracket"});function Tg(n){let e=[],t=n.matched?$g:Pg;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function Rf(n){let e=[],t=n.facet(iu);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Fe(n,i.head,-1,t)||i.head>0&&Fe(n,i.head-1,1,t)||t.afterCursor&&(Fe(n,i.head,1,t)||i.headn.decorations}),Zg=[Cg,vg];function nu(n={}){return[iu.of(n),Zg]}var Ag=new R;function Yl(n,e,t){let i=n.prop(e<0?R.openedBy:R.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function Vl(n){let e=n.type.prop(Ag);return e?e(n.node):n}function Fe(n,e,t,i={}){let s=i.maxScanDistance||eu,r=i.brackets||tu,o=ee(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=Yl(a.type,t,r);if(h&&a.from0?e>=c.from&&ec.from&&e<=c.to))return Mg(n,e,t,a,c,h,r)}}return Rg(n,e,t,o,l.type,s,r)}function Mg(n,e,t,i,s,r,o){let l=i.parent,a={from:s.from,to:s.to},h=0,c=l?.cursor();if(c&&(t<0?c.childBefore(i.from):c.childAfter(i.to)))do if(t<0?c.to<=i.from:c.from>=i.to){if(h==0&&r.indexOf(c.type.name)>-1&&c.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=n.doc.iterRange(e,t>0?n.doc.length:0),f=0;for(let u=0;!c.next().done&&u<=r;){let d=c.value;t<0&&(u+=d.length);let p=e+u*t;for(let O=t>0?0:d.length-1,g=t>0?d.length:-1;O!=g;O+=t){let y=o.indexOf(d[O]);if(!(y<0||i.resolveInner(p+O,1).type!=s))if(y%2==0==t>0)f++;else{if(f==1)return{start:h,end:{from:p+O,to:p+O+1},matched:y>>1==a>>1};f--}}t>0&&(u+=d.length)}return c.done?{start:h,matched:!1}:null}var Xg=Object.create(null),Xf=[ue.none];var Lf=[],Ef=Object.create(null),Lg=Object.create(null);for(let[n,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"]])Lg[n]=Eg(Xg,e);function El(n,e){Lf.indexOf(n)>-1||(Lf.push(n),console.warn(e))}function Eg(n,e){let t=[];for(let l of e.split(" ")){let a=[];for(let h of l.split(".")){let c=n[h]||m[h];c?typeof c=="function"?a.length?a=a.map(c):El(h,`Modifier ${h} used at start of tag`):a.length?El(h,`Tag ${h} used as modifier`):a=Array.isArray(c)?c:[c]:El(h,`Unknown highlighting tag ${h}`)}for(let h of a)t.push(h)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(l=>l.id),r=Ef[s];if(r)return r.id;let o=Ef[s]=ue.define({id:Xf.length,name:i,props:[Bs({[i]:t})]});return Xf.push(o),o.id}var xb={rtl:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:_.RTL}),ltr:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:_.LTR}),auto:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};var Fs=class{constructor(e,t,i,s){this.state=e,this.pos=t,this.explicit=i,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=ee(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),i=Math.max(t.from,this.pos-250),s=t.text.slice(i-t.from,this.pos-t.from),r=s.search(du(e,!1));return r<0?null:{from:i+r,to:this.pos,text:s.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}};function su(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Dg(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Dg(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function uu(n,e){return t=>{for(let i=ee(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}var Hs=class{constructor(e,t,i,s){this.completion=e,this.source=t,this.match=i,this.score=s}};function ti(n){return n.selection.main.from}function du(n,e){var t;let{source:i}=n,s=e&&i[0]!="^",r=i[i.length-1]!="$";return!s&&!r?n:new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}var aa=be.define();function Wg(n,e,t,i){let{main:s}=n.selection,r=t-s.from,o=i-s.from;return{...n.changeByRange(l=>{if(l!=s&&t!=i&&n.sliceDoc(l.from+r,l.from+o)!=n.sliceDoc(t,i))return{range:l};let a=n.toText(e);return{changes:{from:l.from+r,to:i==s.from?l.to:l.from+o,insert:a},range:b.cursor(l.from+r+a.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}var ru=new WeakMap;function Bg(n){if(!Array.isArray(n))return n;let e=ru.get(n);return e||ru.set(n,e=la(n)),e}var Ks=A.define(),Sn=A.define(),Kl=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:(k=Yi(w))!=k.toLowerCase()?1:k!=k.toUpperCase()?2:0;(!x||Q==1&&g||C==0&&Q!=0)&&(t[f]==w||i[f]==w&&(u=!0)?o[f++]=x:o.length&&(y=!1)),C=Q,x+=Pe(w)}return f==a&&o[0]==0&&y?this.result(-100+(u?-200:0),o,e):d==a&&p==0?this.ret(-200-e.length+(O==e.length?0:-100),[0,O]):l>-1?this.ret(-700-e.length,[l,l+this.pattern.length]):d==a?this.ret(-900-e.length,[p,O]):f==a?this.result(-100+(u?-200:0)+-700+(y?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[],r=0;for(let o of t){let l=o+(this.astral?Pe(le(i,o)):1);r&&s[r-1]==o?s[r-1]=l:(s[r++]=o,s[r++]=l)}return this.ret(e-i.length,s)}},Jl=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:zg,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>ou(e(i),t(i)),optionClass:(e,t)=>i=>ou(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function ou(n,e){return n?e?n+" "+e:n:e}function zg(n,e,t,i,s,r){let o=n.textDirection==_.RTL,l=o,a=!1,h="top",c,f,u=e.left-s.left,d=s.right-e.right,p=i.right-i.left,O=i.bottom-i.top;if(l&&u=O||x>e.top?c=t.bottom-e.top:(h="bottom",c=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,y=(e.right-e.left)/r.offsetWidth;return{style:`${h}: ${c/g}px; max-width: ${f/y}px`,class:"cm-completionInfo-"+(a?o?"left-narrow":"right-narrow":l?"left":"right")}}var ha=A.define();function _g(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s,r){let o=document.createElement("span");o.className="cm-completionLabel";let l=t.displayLabel||t.label,a=0;for(let h=0;ha&&o.appendChild(document.createTextNode(l.slice(a,c)));let u=o.appendChild(document.createElement("span"));u.appendChild(document.createTextNode(l.slice(c,f))),u.className="cm-completionMatchedText",a=f}return at.position-i.position).map(t=>t.render)}function Ul(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.floor((n-e)/t);return{from:n-(i+1)*t,to:n-i*t}}var ea=class{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:a=>this.placeInfo(a),key:this},this.space=null,this.currentClass="";let s=e.state.field(t),{options:r,selected:o}=s.open,l=e.state.facet(re);this.optionContent=_g(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=Ul(r.length,o,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",a=>{let{options:h}=e.state.field(t).open;for(let c=a.target,f;c&&c!=this.dom;c=c.parentNode)if(c.nodeName=="LI"&&(f=/-(\d+)$/.exec(c.id))&&+f[1]this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;c!=null&&(e.dispatch({effects:ha.of(c)}),a.preventDefault())}}),this.dom.addEventListener("focusout",a=>{let h=e.state.field(this.stateField,!1);h&&h.tooltip&&e.state.facet(re).closeOnBlur&&a.relatedTarget!=e.contentDOM&&e.dispatch({effects:Sn.of(null)})}),this.showOptions(r,s.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 i=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=s){let{options:r,selected:o,disabled:l}=i.open;(!s.open||s.open.options!=r)&&(this.range=Ul(r.length,o,e.state.facet(re).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),l!=((t=s.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);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;(t.selected>-1&&t.selected=this.range.to)&&(this.range=Ul(t.options.length,t.selected,this.view.state.facet(re).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:s}=t.options[t.selected],{info:r}=s;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(s);if(!o)return;"then"in o?o.then(l=>{l&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(l,s)}).catch(l=>ae(this.view.state,l,"completion info")):(this.addInfoPane(o,s),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:r}=e;i.appendChild(s),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)i.nodeName!="LI"||!i.id?s--:s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&Yg(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return s.top>Math.min(r.bottom,t.bottom)-10||s.bottom{o.target==s&&o.preventDefault()});let r=null;for(let o=i.from;oi.from||i.from==0))if(r=u,typeof h!="string"&&h.header)s.appendChild(h.header(h));else{let d=s.appendChild(document.createElement("completion-section"));d.textContent=u}}let c=s.appendChild(document.createElement("li"));c.id=t+"-"+o,c.setAttribute("role","option");let f=this.optionClass(l);f&&(c.className=f);for(let u of this.optionContent){let d=u(l,this.view.state,this.view,a);d&&c.appendChild(d)}}return i.from&&s.classList.add("cm-completionListIncompleteTop"),i.tonew ea(t,n,e)}function Yg(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),s=t.height/n.offsetHeight;i.topt.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/s)}function lu(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function Vg(n,e){let t=[],i=null,s=null,r=c=>{t.push(c);let{section:f}=c.completion;if(f){i||(i=[]);let u=typeof f=="string"?f:f.name;i.some(d=>d.name==u)||i.push(typeof f=="string"?{name:u}:f)}},o=e.facet(re);for(let c of n)if(c.hasResult()){let f=c.result.getMatch;if(c.result.filter===!1)for(let u of c.result.options)r(new Hs(u,c.source,f?f(u):[],1e9-t.length));else{let u=e.sliceDoc(c.from,c.to),d,p=o.filterStrict?new Jl(u):new Kl(u);for(let O of c.result.options)if(d=p.match(O.label)){let g=O.displayLabel?f?f(O,d.matched):[]:d.matched,y=d.score+(O.boost||0);if(r(new Hs(O,c.source,g,y)),typeof O.section=="object"&&O.section.rank==="dynamic"){let{name:x}=O.section;s||(s=Object.create(null)),s[x]=Math.max(y,s[x]||-1e9)}}}}if(i){let c=Object.create(null),f=0,u=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?s[p.name]-s[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.nameu.score-f.score||h(f.completion,u.completion))){let f=c.completion;!a||a.label!=f.label||a.detail!=f.detail||a.type!=null&&f.type!=null&&a.type!=f.type||a.apply!=f.apply||a.boost!=f.boost?l.push(c):lu(c.completion)>lu(a)&&(l[l.length-1]=c),a=c.completion}return l}var ta=class n{constructor(e,t,i,s,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new n(this.options,au(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,s,r,o){if(s&&!o&&e.some(h=>h.isPending))return s.setDisabled();let l=Vg(e,t);if(!l.length)return s&&e.some(h=>h.isPending)?s.setDisabled():null;let a=t.facet(re).selectOnOpen?0:-1;if(s&&s.selected!=a&&s.selected!=-1){let h=s.options[s.selected].completion;for(let c=0;cc.hasResult()?Math.min(h,c.from):h,1e8),create:Fg,above:r.aboveCursor},s?s.timestamp:Date.now(),a,!1)}map(e){return new n(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new n(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}},ia=class n{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new n(Gg,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(re),r=(i.override||t.languageDataAt("autocomplete",ti(t)).map(Bg)).map(a=>(this.active.find(c=>c.source==a)||new mt(a,this.active.some(c=>c.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((a,h)=>a==this.active[h])&&(r=this.active);let o=this.open,l=e.effects.some(a=>a.is(ca));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(a=>a.hasResult()&&e.changes.touchesRange(a.from,a.to))||!qg(r,this.active)||l?o=ta.build(r,t,this.id,o,i,l):o&&o.disabled&&!r.some(a=>a.isPending)&&(o=null),!o&&r.every(a=>!a.isPending)&&r.some(a=>a.hasResult())&&(r=r.map(a=>a.hasResult()?new mt(a.source,0):a));for(let a of e.effects)a.is(ha)&&(o=o&&o.setSelected(a.value,this.id));return r==this.active&&o==this.open?this:new n(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?jg:Ng}};function qg(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}var Gg=[];function pu(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(aa);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}var mt=class n{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=pu(e,t),s=this;(i&8||i&16&&this.touches(e))&&(s=new n(s.source,0)),i&4&&s.state==0&&(s=new n(this.source,1)),s=s.updateFor(e,i);for(let r of e.effects)if(r.is(Ks))s=new n(s.source,1,r.value);else if(r.is(Sn))s=new n(s.source,0);else if(r.is(ca))for(let o of r.value)o.source==s.source&&(s=o);return s}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(ti(e.state))}},Js=class n extends mt{constructor(e,t,i,s,r,o){super(e,3,t),this.limit=i,this.result=s,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),l=ti(e.state);if(l>o||!s||t&2&&(ti(e.startState)==this.from||lt.map(e))}}),ke=K.define({create(){return ia.start()},update(n,e){return n.update(e)},provide:n=>[an.from(n,e=>e.tooltip),v.contentAttributes.from(n,e=>e.attrs)]});function fa(n,e){let t=e.completion.apply||e.completion.label,i=n.state.field(ke).active.find(s=>s.source==e.source);return i instanceof Js?(typeof t=="string"?n.dispatch({...Wg(n.state,t,i.from,i.to),annotations:aa.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}var Fg=Ig(ke,fa);function Us(n,e="option"){return t=>{let i=t.state.field(ke,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+s*(n?1:-1):n?0:o-1;return l<0?l=e=="page"?0:o-1:l>=o&&(l=e=="page"?o-1:0),t.dispatch({effects:ha.of(l)}),!0}}var Hg=n=>{let e=n.state.field(ke,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestampn.state.field(ke,!1)?(n.dispatch({effects:Ks.of(!0)}),!0):!1,Kg=n=>{let e=n.state.field(ke,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Sn.of(null)}),!0)},na=class{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}},Jg=50,e0=1e3,t0=H.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(ke).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(ke),t=n.state.facet(re);if(!n.selectionSet&&!n.docChanged&&n.startState.field(ke)==e)return;let i=n.transactions.some(r=>{let o=pu(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;rJg&&Date.now()-o.time>e0){for(let l of o.context.abortListeners)try{l()}catch(a){ae(this.view.state,a)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(r=>r.effects.some(o=>o.is(Ks)))&&(this.pendingStart=!0);let s=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let r of n.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(ke);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(re).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=ti(e),i=new Fs(e,t,n.explicit,this.view),s=new na(n,i);this.running.push(s),Promise.resolve(n.source(i)).then(r=>{s.context.aborted||(s.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:Sn.of(null)}),ae(this.view.state,r)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(re).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(re),i=this.view.state.field(ke);for(let s=0;sl.source==r.active.source);if(o&&o.isPending)if(r.done==null){let l=new mt(r.active.source,0);for(let a of r.updates)l=l.update(a,t);l.isPending||e.push(l)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:ca.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(ke,!1);if(e&&e.tooltip&&this.view.state.facet(re).closeOnBlur){let t=e.open&&ll(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Sn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:Ks.of(!1)}),20),this.composing=0}}}),i0=typeof navigator=="object"&&/Win/.test(navigator.platform),n0=xe.highest(v.domEventHandlers({keydown(n,e){let t=e.state.field(ke,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(i0&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],s=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||s.result.commitCharacters;return r&&r.indexOf(n.key)>-1&&fa(e,i),!1}})),Ou=v.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",whiteSpace:"pre-line"},".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"}}}),sa=class{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}},ra=class n{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,se.TrackDel),i=e.mapPos(this.to,1,se.TrackDel);return t==null||i==null?null:new n(this.field,t,i)}},oa=class n{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let a of this.lines){if(i.length){let h=o,c=/^\t*/.exec(a)[0].length;for(let f=0;fnew ra(a.field,s[a.line]+a.from,s[a.line]+a.to));return{text:i,ranges:l}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let l=r[1]?+r[1]:null,a=r[2]||r[3]||"",h=-1,c=a.replace(/\\[{}]/g,f=>f[1]);for(let f=0;f=h&&u.field++}for(let f of s)if(f.line==i.length&&f.from>r.index){let u=r[2]?3+(r[1]||"").length:2;f.from-=u,f.to-=u}s.push(new sa(h,i.length,r.index,r.index+c.length)),o=o.slice(0,r.index)+a+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(l,a,h)=>{for(let c of s)c.line==i.length&&c.from>h&&(c.from--,c.to--);return a}),i.push(o)}return new n(i,s)}},s0=Z.widget({widget:new class extends ge{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),r0=Z.mark({class:"cm-snippetField"}),Ri=class n{constructor(e,t){this.ranges=e,this.active=t,this.deco=Z.set(e.map(i=>(i.from==i.to?s0:r0).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new n(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}},Qn=A.define({map(n,e){return n&&n.map(e)}}),o0=A.define(),wn=K.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(Qn))return t.value;if(t.is(o0)&&n)return new Ri(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>v.decorations.from(n,e=>e?e.deco:Z.none)});function ua(n,e){return b.create(n.filter(t=>t.field==e).map(t=>b.range(t.from,t.to)))}function l0(n){let e=oa.parse(n);return(t,i,s,r)=>{let{text:o,ranges:l}=e.instantiate(t.state,s),{main:a}=t.state.selection,h={changes:{from:s,to:r==a.from?a.to:r,insert:E.of(o)},scrollIntoView:!0,annotations:i?[aa.of(i),ie.userEvent.of("input.complete")]:void 0};if(l.length&&(h.selection=ua(l,0)),l.some(c=>c.field>0)){let c=new Ri(l,0),f=h.effects=[Qn.of(c)];t.state.field(wn,!1)===void 0&&f.push(A.appendConfig.of([wn,u0,d0,Ou]))}t.dispatch(t.state.update(h))}}function mu(n){return({state:e,dispatch:t})=>{let i=e.field(wn,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:ua(i.ranges,s),effects:Qn.of(r?null:new Ri(i.ranges,s)),scrollIntoView:!0})),!0}}var a0=({state:n,dispatch:e})=>n.field(wn,!1)?(e(n.update({effects:Qn.of(null)})),!0):!1,h0=mu(1),c0=mu(-1);var f0=[{key:"Tab",run:h0,shift:c0},{key:"Escape",run:a0}],hu=$.define({combine(n){return n.length?n[0]:f0}}),u0=xe.highest(Qt.compute([hu],n=>n.facet(hu)));function ye(n,e){return{...e,apply:l0(n)}}var d0=v.domEventHandlers({mousedown(n,e){let t=e.state.field(wn,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:ua(t.ranges,s.field),effects:Qn.of(t.ranges.some(r=>r.field>s.field)?new Ri(t.ranges,s.field):null),scrollIntoView:!0}),!0)}});var kn={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},ei=A.define({map(n,e){let t=e.mapPos(n,-1,se.TrackAfter);return t??void 0}}),da=new class extends We{};da.startSide=1;da.endSide=-1;var gu=K.define({create(){return W.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(ei)&&(n=n.update({add:[da.range(t.value,t.value+1)]}));return n}});function yu(){return[O0,gu]}var Hl="()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";function bu(n){for(let e=0;e{if((p0?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Pe(le(i,0))==1||e!=s.from||t!=s.to)return!1;let r=g0(n.state,i);return r?(n.dispatch(r),!0):!1}),m0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=xu(n,n.selection.main.head).brackets||kn.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let l=y0(n.doc,o.head);for(let a of i)if(a==l&&er(n.doc,o.head)==bu(le(a,0)))return{changes:{from:o.head-a.length,to:o.head+a.length},range:b.cursor(o.head-a.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},Su=[{key:"Backspace",run:m0}];function g0(n,e){let t=xu(n,n.selection.main.head),i=t.brackets||kn.brackets;for(let s of i){let r=bu(le(s,0));if(e==s)return r==s?S0(n,s,i.indexOf(s+s+s)>-1,t):b0(n,s,r,t.before||kn.before);if(e==r&&wu(n,n.selection.main.from))return x0(n,s,r)}return null}function wu(n,e){let t=!1;return n.field(gu).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function er(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Pe(le(t,0)))}function y0(n,e){let t=n.sliceString(e-2,e);return Pe(le(t,0))==t.length?t:t.slice(1)}function b0(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:ei.of(o.to+e.length),range:b.range(o.anchor+e.length,o.head+e.length)};let l=er(n.doc,o.head);return!l||/\s/.test(l)||i.indexOf(l)>-1?{changes:{insert:e+t,from:o.head},effects:ei.of(o.head+e.length),range:b.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function x0(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&er(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:b.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function S0(n,e,t,i){let s=i.stringPrefixes||kn.stringPrefixes,r=null,o=n.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:ei.of(l.to+e.length),range:b.range(l.anchor+e.length,l.head+e.length)};let a=l.head,h=er(n.doc,a),c;if(h==e){if(cu(n,a))return{changes:{insert:e+e,from:a},effects:ei.of(a+e.length),range:b.cursor(a+e.length)};if(wu(n,a)){let u=t&&n.sliceDoc(a,a+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:a,to:a+u.length,insert:u},range:b.cursor(a+u.length)}}}else{if(t&&n.sliceDoc(a-2*e.length,a)==e+e&&(c=fu(n,a-2*e.length,s))>-1&&cu(n,c))return{changes:{insert:e+e+e+e,from:a},effects:ei.of(a+e.length),range:b.cursor(a+e.length)};if(n.charCategorizer(a)(h)!=V.Word&&fu(n,a,s)>-1&&!w0(n,a,e,s))return{changes:{insert:e+e,from:a},effects:ei.of(a+e.length),range:b.cursor(a+e.length)}}return{range:r=l}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function cu(n,e){let t=ee(n).resolveInner(e+1);return t.parent&&t.from==e}function w0(n,e,t,i){let s=ee(n).resolveInner(e,-1),r=i.reduce((o,l)=>Math.max(o,l.length),0);for(let o=0;o<5;o++){let l=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),a=l.indexOf(t);if(!a||a>-1&&i.indexOf(l.slice(0,a))>-1){let c=s.firstChild;for(;c&&c.from==s.from&&c.to-c.from>t.length+a;){if(n.sliceDoc(c.to-t.length,c.to)==t)return!1;c=c.firstChild}return!0}let h=s.to==e&&s.parent;if(!h)break;s=h}return!1}function fu(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=V.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=V.Word)return r}return-1}function ku(n={}){return[n0,ke,re.of(n),t0,k0,Ou]}var pa=[{key:"Ctrl-Space",run:Fl},{mac:"Alt-`",run:Fl},{mac:"Alt-i",run:Fl},{key:"Escape",run:Kg},{key:"ArrowDown",run:Us(!0)},{key:"ArrowUp",run:Us(!1)},{key:"PageDown",run:Us(!0,"page")},{key:"PageUp",run:Us(!1,"page")},{key:"Enter",run:Hg}],k0=xe.highest(Qt.computeN([re],n=>n.facet(re).defaultKeymap?[pa]:[]));var Pu=[ye("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),ye("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),ye("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),ye("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),ye("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),ye(`try { +`){[e,t]=ci(this,e,t);let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=l.sliceString(e-o,t-o,i)),o=a+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof n))return 0;let i=0,[s,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==l)return i;let a=this.children[s],h=e.children[r];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new $e(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,l=[],a=0,h=-1,c=[];function f(d){let p;if(d.lines>r&&d instanceof n)for(let O of d.children)f(O);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof $e&&a&&(p=c[c.length-1])instanceof $e&&d.lines+p.lines<=32?(a+=d.lines,h+=d.length+1,c[c.length-1]=new $e(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>s&&u(),a+=d.lines,h+=d.length+1,c.push(d))}function u(){a!=0&&(l.push(c.length==1?c[0]:n.from(c,h)),h=-1,a=c.length=0)}for(let d of e)f(d);return u(),l.length==1?l[0]:new n(l,t)}};E.empty=new $e([""],0);function ep(n){let e=-1;for(let t of n)e+=t.length+1;return e}function _n(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(a>i&&(l=l.slice(0,i-s)),s0?1:(e instanceof $e?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,l=s instanceof $e?s.text.length:s.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(s instanceof $e){let a=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=s.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof $e?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},zn=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new Bt(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}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 i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),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!=""}},In=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(E.prototype[Symbol.iterator]=function(){return this.iter()},Bt.prototype[Symbol.iterator]=zn.prototype[Symbol.iterator]=In.prototype[Symbol.iterator]=function(){return this});var Cr=class{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}};function ci(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function te(n,e,t=!0,i=!0){return ja(n,e,t,i)}function tp(n){return n>=56320&&n<57344}function ip(n){return n>=55296&&n<56320}function le(n,e){let t=n.charCodeAt(e);if(!ip(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return tp(i)?(t-55296<<10)+(i-56320)+65536:t}function Yi(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Te(n){return n<65536?1:2}var Zr=/\r\n?|\n/,se=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(se||(se={})),ht=class n{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=l}else{if(i!=se.Simple&&h>=e&&(i==se.TrackDel&&se||i==se.TrackBefore&&se))return null;if(h>e||h==e&&t<0&&!l)return e==s||t<0?r:r+a;r+=a}s=h}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&l>=e)return st?"cover":!0;s=l}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}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 n(e)}static create(e){return new n(e)}},me=class n extends ht{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 Ar(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Mr(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=l,t[s+1]=o;let a=s>>1;for(;i.length0&&bt(i,t,r.text),r.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,l=null;function a(c=!1){if(!c&&!s.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let p=d?typeof d=="string"?E.of(d.split(i||Zr)):d:E.empty,O=p.length;if(f==u&&O==0)return;fo&&fe(s,f-o,-1),fe(s,u-f,O),bt(r,s,p),o=u}}return h(e),a(!l),l}static empty(e){return new n(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function bt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(s,h,r,c,f),s=h,r=c}}}function Mr(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Wt(n),l=new Wt(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);fe(s,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),r.forward2(a),o.forward(a)}}}}var Wt=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?E.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?E.empty:t[i].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)}},oi=class n{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}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 i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new n(i,s,this.flags)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return b.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return b.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!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 b.range(e.anchor,e.head)}static create(e,t,i){return new n(e,t,i)}},b=class n{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:n.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.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 n(e.ranges.map(t=>oi.fromJSON(t)),e.main)}static single(e,t=e){return new n([n.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 i=0,s=0;ss.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?n.range(a,l):n.range(l,a))}}return new n(e,t)}};function ih(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var Ir=0,$=class n{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=Ir++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new n(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Yr),!!e.static,e.enables)}of(e){return new ai([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new ai(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new ai(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}};function Yr(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}var ai=class{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=Ir++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Rr(f,c)){let d=i(f);if(l?!Ha(d,f.values[o],s):!s(d,f.values[o]))return f.values[o]=d,1}return 0},reconfigure:(f,u)=>{let d,p=u.config.address[r];if(p!=null){let O=Vn(u,p);if(this.dependencies.every(g=>g instanceof $?u.facet(g)===f.facet(g):g instanceof K?u.field(g,!1)==f.field(g,!1):!0)||(l?Ha(d=i(f),O,s):s(d=i(f),O)))return f.values[o]=O,0}else d=i(f);return f.values[o]=d,1}}}};function Ha(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),s=t.map(a=>a.type),r=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(Dn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(Dn),o=s.facet(Dn),l;return(l=r.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,Dn.of({field:this,create:e})]}get extension(){return this}},Et={lowest:4,low:3,default:2,high:1,highest:0};function Bi(n){return e=>new Yn(e,n)}var Se={highest:Bi(Et.highest),high:Bi(Et.high),default:Bi(Et.default),low:Bi(Et.low),lowest:Bi(Et.lowest)},Yn=class{constructor(e,t){this.inner=e,this.prec=t}},fi=class n{of(e){return new _i(this,e)}reconfigure(e){return n.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},_i=class{constructor(e,t){this.compartment=e,this.inner=t}},qn=class n{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let u of sp(e,t,o))u instanceof K?s.push(u):(r[u.facet.id]||(r[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of s)l[u.id]=h.length<<1,h.push(d=>u.slot(d));let c=i?.config.facets;for(let u in r){let d=r[u],p=d[0].facet,O=c&&c[u]||[];if(d.every(g=>g.type==0))if(l[p.id]=a.length<<1|1,Yr(O,d))a.push(i.facet(p));else{let g=p.combine(d.map(y=>y.value));a.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(y=>g.dynamicSlot(y)));l[p.id]=h.length<<1,h.push(g=>np(g,p,d))}}let f=h.map(u=>u(l));return new n(e,o,f,l,a,r)}};function sp(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,l){let a=s.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof _i&&t.delete(o.compartment)}if(s.set(o,l),Array.isArray(o))for(let h of o)r(h,l);else if(o instanceof _i){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),r(h,l)}else if(o instanceof Yn)r(o.inner,o.prec);else if(o instanceof K)i[l].push(o),o.provides&&r(o.provides,l);else if(o instanceof ai)i[l].push(o),o.facet.extensions&&r(o.facet.extensions,Et.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.`);r(h,l)}}return r(n,Et.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function Vn(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}var nh=$.define(),Xr=$.define({combine:n=>n.some(e=>e),static:!0}),sh=$.define({combine:n=>n.length?n[0]:void 0,static:!0}),rh=$.define(),oh=$.define(),lh=$.define(),ah=$.define({combine:n=>n.length?n[0]:!1}),xe=class{constructor(e,t){this.type=e,this.value=t}static define(){return new Lr}},Lr=class{of(e){return new xe(this,e)}},Er=class{constructor(e){this.map=e}of(e){return new A(this,e)}},A=class n{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 n(this.type,t)}is(e){return this.type==e}static define(e={}){return new Er(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}};A.reconfigure=A.define();A.appendConfig=A.define();var ie=class n{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&ih(i,t.newLength),r.some(l=>l.type==n.time)||(this.annotations=r.concat(n.time.of(Date.now())))}static create(e,t,i,s,r,o){return new n(e,t,i,s,r,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(n.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};ie.time=xe.define();ie.userEvent=xe.define();ie.addToHistory=xe.define();ie.remote=xe.define();function rp(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof ie?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof ie?n=r[0]:n=ch(e,hi(r),!1)}return n}function lp(n){let e=n.startState,t=e.facet(lh),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=hh(i,Dr(e,r,n.changes.newLength),!0))}return i==n?n:ie.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}var ap=[];function hi(n){return n==null?ap:Array.isArray(n)?n:[n]}var q=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(q||(q={})),hp=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Br;try{Br=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function cp(n){if(Br)return Br.test(n);for(let e=0;e"\x80"&&(t.toUpperCase()!=t.toLowerCase()||hp.test(t)))return!0}return!1}function fp(n){return e=>{if(!/\S/.test(e))return q.Space;if(cp(e))return q.Word;for(let t=0;t-1)return q.Word;return q.Other}}var Y=class n{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let l=0;ls.set(h,a)),t=null),s.set(l.value.compartment,l.value.extension)):l.is(A.reconfigure)?(t=null,i=l.value):l.is(A.appendConfig)&&(t=null,i=hi(i).concat(l.value));let r;t?r=e.startState.values.slice():(t=qn.resolve(i,s,this),r=new n(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(Xr)?e.newSelection:e.newSelection.asSingle();new n(t,e.newDoc,o,r,(l,a)=>a.update(l,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:b.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=hi(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return n.create({doc:e.doc,selection:b.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=qn.resolve(e.extensions||[],new Map),i=e.doc instanceof E?e.doc:E.of((e.doc||"").split(t.staticFacet(n.lineSeparator)||Zr)),s=e.selection?e.selection instanceof b?e.selection:b.single(e.selection.anchor,e.selection.head):b.single(0);return ih(s,i.length),t.staticFacet(Xr)||(s=s.asSingle()),new n(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(n.tabSize)}get lineBreak(){return this.facet(n.lineSeparator)||` +`}get readOnly(){return this.facet(ah)}phrase(e,...t){for(let i of this.facet(n.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(nh))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return fp(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=te(t,o,!1);if(r(t.slice(a,o))!=q.Word)break;o=a}for(;ln.length?n[0]:4});Y.lineSeparator=sh;Y.readOnly=ah;Y.phrases=$.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});Y.languageData=nh;Y.changeFilter=rh;Y.transactionFilter=oh;Y.transactionExtender=lh;fi.reconfigure=A.define();function ue(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}var Be=class{eq(e){return this==e}range(e,t=e){return zi.create(e,t,this)}};Be.prototype.startSide=Be.prototype.endSide=0;Be.prototype.point=!1;Be.prototype.mapMode=se.TrackDel;function qr(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}var zi=class n{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new n(e,t,i)}};function Wr(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var _r=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,l=r.length;;){if(o==l)return o;let a=o+l>>1,h=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rd||u==d&&h.startSide>0&&h.endSide<=0)continue;(d-u||h.endSide-h.startSide)<0||(o<0&&(o=u),h.point&&(l=Math.max(l,d-u)),i.push(h),s.push(u-o),r.push(d-o))}return{mapped:i.length?new n(s,r,i,l):null,pos:o}}},B=class n{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new n(e,t,i,s)}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:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Wr)),this.isEmpty)return t.length?n.of(t):this;let l=new jn(this,null,-1).goto(0),a=0,h=[],c=new Pe;for(;l.value||a=0){let f=t[a++];c.addInner(f.from,f.to,f.value)||h.push(f)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||rl.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return Ii.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Ii.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),l=t.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),a=Ka(o,l,i),h=new Dt(o,a,r),c=new Dt(l,a,r);i.iterGaps((f,u,d)=>Ja(h,f,c,u,d,s)),i.empty&&i.length==0&&Ja(h,0,c,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let l=Ka(r,o),a=new Dt(r,l,0).goto(i),h=new Dt(o,l,0).goto(i);for(;;){if(a.to!=h.to||!zr(a.active,h.active)||a.point&&(!h.point||!qr(a.point,h.point)))return!1;if(a.to>s)return!0;a.next(),h.next()}}static spans(e,t,i,s,r=-1){let o=new Dt(e,null,r).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let c=o.activeForPoint(o.to),f=o.pointFroml&&(s.span(l,h,o.active,a),a=o.openEnd(h));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new Pe;for(let s of e instanceof zi?[e]:t?up(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return n.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=n.empty;s=s.nextLayer)t=new n(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}};B.empty=new B([],[],null,-1);function up(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Wr);e=i}return n}B.empty.nextLayer=B.empty;var Pe=class n{finishChunk(e){this.chunks.push(new _r(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,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new n)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<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=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.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 i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(B.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=B.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function Ka(n,e,t){let i=new Map;for(let r of n)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=i&&s.push(new jn(o,t,i,r));return s.length==1?s[0]:new n(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Tr(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Tr(this.heap,i);(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(),Tr(this.heap,0)}}};function Tr(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}var Dt=class{constructor(e,t,i){this.minPoint=i,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=Ii.from(e,t,i)}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){Bn(this.active,e),Bn(this.activeTo,e),Bn(this.activeRank,e),this.minActive=eh(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t0;)t++;Wn(this.active,t,i),Wn(this.activeTo,t,s),Wn(this.activeRank,t,r),e&&Wn(e,t,this.cursor.from),this.minActive=eh(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&Bn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[s]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}};function Ja(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,l=i,a=i-e,h=!!r.boundChange;for(let c=!1;;){let f=n.to+a-t.to,u=f||n.endSide-t.endSide,d=u<0?n.to+a:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&qr(n.point,t.point)&&zr(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(l,p,n.point,t.point),c=!1):(c&&r.boundChange(l),p>l&&!zr(n.active,t.active)&&r.compareRange(l,p,n.active,t.active),h&&po)break;l=d,u<=0&&n.next(),u>=0&&t.next()}}function zr(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function eh(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=te(n,s)}return i===!0?-1:n.length}var fh=typeof Symbol>"u"?"__\u037C":Symbol.for("\u037C"),Vr=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),uh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},We=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,l,a,h){let c=[],f=/^@(\w+)\b/.exec(o[0]),u=f&&f[1]=="keyframes";if(f&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))r(d.split(/,\s*/).map(O=>o.map(g=>O.replace(/&/,g))).reduce((O,g)=>O.concat(g)),p,a);else if(p&&typeof p=="object"){if(!f)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,c,u)}else p!=null&&c.push(d.replace(/_.*/,"").replace(/[A-Z]/g,O=>"-"+O.toLowerCase())+": "+p+";")}(c.length||u)&&a.push((i&&!f&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=uh[fh]||1;return uh[fh]=e+1,"\u037C"+e.toString(36)}static mount(e,t,i){let s=e[Vr],r=i&&i.nonce;s?r&&s.setNonce(r):s=new jr(e,r),s.mount(Array.isArray(t)?t:[t],e)}},dh=new Map,jr=class{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=dh.get(i);if(r)return e[Vr]=r;this.sheet=new s.CSSStyleSheet,dh.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Vr]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o-1&&(this.modules.splice(a,1),r--,a=-1),a==-1){if(this.modules.splice(r++,0,l),i)for(let h=0;h",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},dp=typeof navigator<"u"&&/Mac/.test(navigator.platform),pp=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(ne=0;ne<10;ne++)ft[48+ne]=ft[96+ne]=String(ne);var ne;for(ne=1;ne<=24;ne++)ft[ne+111]="F"+ne;var ne;for(ne=65;ne<=90;ne++)ft[ne]=String.fromCharCode(ne+32),ui[ne]=String.fromCharCode(ne);var ne;for(Gn in ft)ui.hasOwnProperty(Gn)||(ui[Gn]=ft[Gn]);var Gn;function ph(n){var e=dp&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||pp&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?ui:ft)[n.keyCode]||n.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 W(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e2),T={mac:yh||/Mac/.test(ge.platform),windows:/Win/.test(ge.platform),linux:/Linux|X11/.test(ge.platform),ie:Ps,ie_version:ec?io.documentMode||6:so?+so[1]:no?+no[1]:0,gecko:mh,gecko_version:mh?+(/Firefox\/(\d+)/.exec(ge.userAgent)||[0,0])[1]:0,chrome:!!Nr,chrome_version:Nr?+Nr[1]:0,ios:yh,android:/Android\b/.test(ge.userAgent),webkit:gh,webkit_version:gh?+(/\bAppleWebKit\/(\d+)/.exec(ge.userAgent)||[0,0])[1]:0,safari:ro,safari_version:ro?+(/\bVersion\/(\d+(\.\d+)?)/.exec(ge.userAgent)||[0,0])[1]:0,tabSize:io.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Ko(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}var hs=Object.create(null);function Jo(n,e,t){if(n==e)return!0;n||(n=hs),e||(e=hs);let i=Object.keys(n),s=Object.keys(e);if(i.length-(t&&i.indexOf(t)>-1?1:0)!=s.length-(t&&s.indexOf(t)>-1?1:0))return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function Op(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function bh(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function mp(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new Yt(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=tc(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Yt(e,i,s,t,e.widget||null,!0)}static line(e){return new sn(e)}static set(e,t=!1){return B.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};Z.none=B.empty;var nn=class n extends Z{constructor(e){let{start:t,end:i}=tc(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Ko(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||hs}eq(e){return this==e||e instanceof n&&this.tagName==e.tagName&&Jo(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};nn.prototype.point=!1;var sn=class n extends Z{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof n&&this.spec.class==e.spec.class&&Jo(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)}};sn.prototype.mapMode=se.TrackBefore;sn.prototype.point=!0;var Yt=class n extends Z{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?se.TrackBefore:se.TrackAfter:se.TrackDel}get type(){return this.startSide!=this.endSide?he.WidgetRange:this.startSide<=0?he.WidgetBefore:he.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof n&&gp(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)}};Yt.prototype.point=!0;function tc(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function gp(n,e){return n==e||!!(n&&e&&n.compare(e))}function yi(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}var cs=class n extends Be{constructor(e,t){super(),this.tagName=e,this.attributes=t}eq(e){return e==this||e instanceof n&&this.tagName==e.tagName&&Jo(this.attributes,e.attributes)}static create(e){return new n(e.tagName,e.attributes||hs)}static set(e,t=!1){return B.of(e,t)}};cs.prototype.startSide=cs.prototype.endSide=-1;function rn(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function oo(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Ni(n,e){if(!e.anchorNode)return!1;try{return oo(n,e.anchorNode)}catch{return!1}}function ss(n){return n.nodeType==3?on(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Gi(n,e,t,i){return t?xh(n,e,t,i,-1)||xh(n,e,t,i,1):!1}function wt(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function fs(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function xh(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:pt(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=wt(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?pt(n):0}else return!1}}function pt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function us(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function yp(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function ic(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function bp(n,e,t,i,s,r,o,l){let a=n.ownerDocument,h=a.defaultView||window;for(let c=n,f=!1;c&&!f;)if(c.nodeType==1){let u,d=c==a.body,p=1,O=1;if(d)u=yp(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 x=c.getBoundingClientRect();({scaleX:p,scaleY:O}=ic(c,x)),u={left:x.left,right:x.left+c.clientWidth*p,top:x.top,bottom:x.top+c.clientHeight*O}}let g=0,y=0;if(s=="nearest")e.top0&&e.bottom>u.bottom+y&&(y=e.bottom-u.bottom+o)):e.bottom>u.bottom-o&&(y=e.bottom-u.bottom+o,t<0&&e.top-y0&&e.right>u.right+g&&(g=e.right-u.right+r)):e.right>u.right-r&&(g=e.right-u.right+r,t<0&&e.leftu.bottom||e.leftu.right)&&(e={left:Math.max(e.left,u.left),right:Math.min(e.right,u.right),top:Math.max(e.top,u.top),bottom:Math.min(e.bottom,u.bottom)}),c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function nc(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}var lo=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:i}=e;this.set(t,Math.min(e.anchorOffset,t?pt(t):0),i,Math.min(e.focusOffset,i?pt(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}},_t=null;T.safari&&T.safari_version>=26&&(_t=!1);function sc(n){if(n.setActive)return n.setActive();if(_t)return n.focus(_t);let e=[];for(let t=n;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(n.focus(_t==null?{get preventScroll(){return _t={preventScroll:!0},!0}}:void 0),!_t){_t=!1;for(let t=0;tMath.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function oc(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=pt(t)}else if(t.parentNode&&!fs(t))i=wt(t),t=t.parentNode;else return null}}function lc(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(l.level==i)return o;(r<0||(s!=0?s<0?l.fromt:e[r].level>l.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}};function cc(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;O-=3)if(nt[O+1]==-d){let g=nt[O+2],y=g&2?s:g&4?g&1?r:s:0;y&&(j[f]=j[nt[O]]=y),l=O;break}}else{if(nt.length==189)break;nt[l++]=f,nt[l++]=u,nt[l++]=a}else if((p=j[f])==2||p==1){let O=p==s;a=O?0:1;for(let g=l-3;g>=0;g-=3){let y=nt[g+2];if(y&2)break;if(O)nt[g+2]|=2;else{if(y&4)break;nt[g+2]|=4}}}}}function Pp(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,l=sa;)p==g&&(p=t[--O].from,g=O?t[O-1].to:n),j[--p]=d;a=c}else r=h,a++}}}function ho(n,e,t,i,s,r,o){let l=i%2?2:1;if(i%2==s%2)for(let a=e,h=0;aa&&o.push(new Ie(a,O.from,d));let g=O.direction==qt!=!(d%2);co(n,g?i+1:i,s,O.inner,O.from,O.to,o),a=O.to}p=O.to}else{if(p==t||(c?j[p]!=l:j[p]==l))break;p++}u?ho(n,a,p,i+1,s,u,o):ae;){let c=!0,f=!1;if(!h||a>r[h-1].to){let O=j[a-1];O!=l&&(c=!1,f=O==16)}let u=!c&&l==1?[]:null,d=c?i:i+1,p=a;e:for(;;)if(h&&p==r[h-1].to){if(f)break e;let O=r[--h];if(!c)for(let g=O.from,y=h;;){if(g==e)break e;if(y&&r[y-1].to==g)g=r[--y].from;else{if(j[g-1]==l)break e;break}}if(u)u.push(O);else{O.toj.length;)j[j.length]=256;let i=[],s=e==qt?0:1;return co(n,s,s,t,0,n.length,i),i}function fc(n){return[new Ie(0,n,0)]}var uc="";function Cp(n,e,t,i,s){var r;let o=i.head-n.from,l=Ie.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),a=e[l],h=a.side(s,t);if(o==h){let u=l+=s?1:-1;if(u<0||u>=e.length)return null;a=e[l=u],o=a.side(!s,t),h=a.side(s,t)}let c=te(n.text,o,a.forward(s,t));(ca.to)&&(c=h),uc=n.text.slice(Math.min(o,c),Math.max(o,c));let f=l==(s?e.length-1:0)?null:e[l+(s?1:-1)];return f&&c==h&&f.level+(s?0:1)n.some(e=>e)}),xc=$.define({combine:n=>n.some(e=>e)}),Sc=$.define(),Ui=class n{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new n(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 n(b.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},Un=A.define({map:(n,e)=>n.map(e)}),wc=A.define();function ae(n,e,t){let i=n.facet(mc);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}var ut=$.define({combine:n=>n.length?n[0]:!0}),Ap=0,pi=$.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let a=[];return o&&a.push(Ts.of(h=>{let c=h.plugin(l);return c?o(c):Z.none})),r&&a.push(r(l)),a})}static fromClass(e,t){return n.define((i,s)=>new e(i,s),t)}},Fi=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}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(i){if(ae(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ae(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(i){ae(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},kc=$.define(),nl=$.define(),Ts=$.define(),Qc=$.define(),sl=$.define(),ln=$.define(),vc=$.define();function wh(n,e){let t=n.state.facet(vc);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return B.spans(i,e.from,e.to,{point(){},span(r,o,l,a){let h=r-e.from,c=o-e.from,f=s;for(let u=l.length-1;u>=0;u--,a--){let d=l[u].spec.bidiIsolate,p;if(d==null&&(d=Zp(e.text,h,c)),a>0&&f.length&&(p=f[f.length-1]).to==h&&p.direction==d)p.to=c,f=p.inner;else{let O={from:h,to:c,direction:d,inner:[]};f.push(O),f=O.inner}}}}),s}var $c=$.define();function rl(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet($c)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}var qi=$.define(),Ne=class n{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new n(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,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAs.push(new Ne(r,o,l,a))),this.changedRanges=s}static create(e,t,i){return new n(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>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}},Mp=[],F=class{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Mp}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&Op(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t){return null}domPosFor(e,t){let i=wt(this.dom),s=this.length?e>0:t>0;return new st(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Si)return e;return null}static get(e){return e.cmTile}},xi=class extends F{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let l of this.children){if(l.sync(e),o+=l.length+l.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=l.dom&&(r.written=!0),l.dom.parentNode==t)for(;s&&s!=l.dom;)s=kh(s);else t.insertBefore(l.dom,s);i=l.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=kh(s);this.length=o}};function kh(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}var Si=class extends xi{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=F.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof dt)t.push(s),i=o,s=0;else{let l=r+o.length,a=e(o,r);if(a!==void 0)return a;r=l+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((l,a)=>{let h=a+l.length;if(e>=a&&e<=h){if(l.isWidget()&&t>=-1&&t<=1){if(l.flags&32)return!0;l.flags&16&&(i=void 0)}(ae||e==a&&(t>1?l.length:l.covers(-1)))&&(!r||!l.isWidget()&&r.isWidget())&&(r=l,o=e-a)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}},dt=class n extends xi{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new n(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}},wi=class n extends xi{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new n(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,l=-1;function a(c,f){for(let u=0,d=0;u=f&&(p.isComposite()?a(p,f-d):(!o||o.isHidden&&(t>0||i&&Xp(o,p)))&&(O>f||p.flags&32)?(o=p,l=f-d):(di&&(e=i);let s=e,r=e,o=0;e==0&&t<0||e==i&&t>=0?T.chrome||T.gecko||(e?(s--,o=1):r=0)?0:l.length-1];return T.safari&&!o&&a.width==0&&(a=Array.prototype.find.call(l,h=>h.width)||a),o?us(a,o<0):a||null}static of(e,t){let i=new n(t||document.createTextNode(e),e);return t||(i.flags|=2),i}},Vt=class n extends F{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return us(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let l=this.flags&16?!0:this.flags&32?!1:e>0;for(let a=l?r.length-1:0;o=r[a],!(e>0?a==0:a==r.length-1||o.top0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!l.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=l.pop(),r++}else{let a=s.children[r],h=a.breakAfter;(t>0?a.length<=e:a.length=0;l--){let a=t.marks[l],h=s.lastChild;if(h instanceof we&&h.mark.eq(a.mark))h.dom!=a.dom&&h.setDOM(Gr(a.dom)),s=h;else{if(this.cache.reused.get(a)){let f=F.get(a.dom);f&&f.setDOM(Gr(a.dom))}let c=we.of(a.mark,a.dom);s.append(c),s=c}this.cache.reused.set(a,2)}let r=F.get(e.text);r&&this.cache.reused.set(r,2);let o=new zt(e.text,e.text.nodeValue);o.flags|=8,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=Pc);let s=wi.start(e,t||((i=this.cache.find(wi))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],l;if(t>0&&(l=s.lastChild)&&l instanceof we&&l.mark.eq(o))s=l,t--;else{let a=we.of(o,(i=this.cache.find(we,h=>h.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(a),s=a,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Qh(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(T.ios&&Qh(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Ur,0,32)||new Vt(Ur.toDOM(),0,Ur,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=new po(e.from,e.to,e.value,e.rank),i=this.wrappers.length;for(;i>0&&(this.wrappers[i-1].rank-t.rank||this.wrappers[i-1].to-t.to)<0;)i--;this.wrappers.splice(i,0,t)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(ki,void 0,1);return i&&(i.flags=t),i||new ki(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},mo=class{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let l=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}},ps=[Vt,wi,zt,we,ki,dt,Si];for(let n=0;n[]),this.index=ps.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let l=r.length-1;l>=0;l--){let a=(l+o)%r.length,h=r[a];if((!t||t(h))&&!this.reused.has(h))return r.splice(a,1),a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let l=os){let h=a-s;this.preserve(h,!o,!l),s=a,r+=h}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(this.forward(l.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let h=a>0||l{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof we&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof we&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=0,o=B.spans(this.decorations,e,t,{point:(l,a,h,c,f,u)=>{if(h instanceof Yt){if(this.disallowBlockEffectsFor[u]){if(h.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=c.length,f>c.length)s.continueWidget(a-l);else{let d=h.widget||(h.block?kt.block:kt.inline),p=Lp(h),O=this.cache.findWidget(d,a-l,p)||Vt.of(d,this.view,a-l,p);h.block?(h.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(O)):(s.ensureLine(i),s.addInlineWidget(O,c,f))}i=null}else i=Ep(i,h);a>l&&this.text.skip(a-l)},span:(l,a,h,c)=>{for(let f=l;fr,this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=F.get(s);if(s==this.view.contentDOM)break;r instanceof we?t.push(r):r?.isLine()?i=r:r instanceof dt||(s.nodeName=="DIV"&&!i&&s!=this.view.contentDOM?i=new wi(s,Pc):i||t.push(we.of(new nn({tagName:s.nodeName.toLowerCase(),attributes:mp(s)}),s)))}return{line:i,marks:t}}};function Qh(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function Lp(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}var Pc={class:"cm-line"};function Ep(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&Ko(t,n),i&&(n.class+=" "+i)),n}function Dp(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof we&&e.push(i.mark)}return e}function Gr(n){let e=F.get(n);return e&&e.setDOM(n.cloneNode()),n}var kt=class extends ye{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 Ur=new class extends ye{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}},Os=class{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=Z.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.updateDeco(),this.tile=new Si(e,e.contentDOM),this.updateInner([new Ne(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:c,toA:f})=>fthis.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 s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!Vp(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?Wp(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:c,to:f}=this.hasComposition;i=new Ne(c,f,e.changes.mapPos(c,-1),e.changes.mapPos(f,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(T.ie||T.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,l=this.blockWrappers;this.updateDeco();let a=Ip(o,this.decorations,e.changes);a.length&&(i=Ne.extendWithRanges(i,a));let h=Yp(l,this.blockWrappers,e.changes);return h.length&&(i=Ne.extendWithRanges(i,h)),r&&!i.some(c=>c.fromA<=r.range.fromA&&c.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,l=new yo(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&F.get(t.text)&&l.cache.reused.set(F.get(t.text),2),this.tile=l.run(e,t),bo(o,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=T.chrome||T.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Ni(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,h,c;if(a.empty?c=h=this.inlineDOMNearPos(a.anchor,a.assoc||1):(c=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),h=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),T.gecko&&a.empty&&!this.hasComposition&&Bp(h)){let u=document.createTextNode("");this.view.observer.ignore(()=>h.node.insertBefore(u,h.node.childNodes[h.offset]||null)),h=c=new st(u,0),l=!0}let f=this.view.observer.selectionRange;(l||!f.focusNode||(!Gi(h.node,h.offset,f.anchorNode,f.anchorOffset)||!Gi(c.node,c.offset,f.focusNode,f.focusOffset))&&!this.suppressWidgetCursorChange(f,a))&&(this.view.observer.ignore(()=>{T.android&&T.chrome&&i.contains(f.focusNode)&&qp(f.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let u=rn(this.view.root);if(u)if(a.empty){if(T.gecko){let d=_p(h.node,h.offset);if(d&&d!=3){let p=(d==1?oc:lc)(h.node,h.offset);p&&(h=new st(p.node,p.offset))}}u.collapse(h.node,h.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(h.node,h.offset);try{u.extend(c.node,c.offset)}catch{}}else{let d=document.createRange();a.anchor>a.head&&([h,c]=[c,h]),d.setEnd(c.node,c.offset),d.setStart(h.node,h.offset),u.removeAllRanges(),u.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(h,c)),this.impreciseAnchor=h.precise?null:new st(f.anchorNode,f.anchorOffset),this.impreciseHead=c.precise?null:new st(f.focusNode,f.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Gi(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,i=rn(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(c.node,c.offset),i.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&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=pt(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==i.dom)break;o==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?o=-1:o=1),e=l}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!F.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,l=s;;o++){let a=i.children[o];if(a.dom==r)return l;l+=a.length+a.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(e,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,l=-1,a=!1;return this.tile.blockTiles((h,c)=>{if(h.isWidget()){if(h.flags&32&&c>=e)return!0;h.flags&16&&(r=!0)}else{let f=c+h.length;if(c<=e&&(i=h,s=e-c,r=f=e&&!o&&(o=h,l=e-c,a=c>e),c>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:a&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(l,t))}coordsAt(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.widget instanceof Hi?null:i.coordsInWidget(s,t,!0):i.coordsIn(s,t)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let l of r.children){if(l.length>=o){let a=s(l,o);if(a)return a}if(o-=l.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==z.LTR,h=0,c=(f,u,d)=>{for(let p=0;ps);p++){let O=f.children[p],g=u+O.length,y=O.dom.getBoundingClientRect(),{height:x}=y;if(d&&!p&&(h+=y.top-d.top),O instanceof dt)g>i&&c(O,u,y);else if(u>=i&&(h>0&&t.push(-h),t.push(x+h),h=0,o)){let S=O.dom.lastChild,C=S?ss(S):[];if(C.length){let w=C[C.length-1],k=a?w.right-y.left:y.right-w.left;k>l&&(l=k,this.minWidth=r,this.minWidthFrom=u,this.minWidthTo=g)}}d&&p==f.children.length-1&&(h+=d.bottom-y.bottom),u=g+O.breakAfter}};return c(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?z.RTL:z.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let l=0,a;for(let h of o.children){if(!h.isText()||/[^ -~]/.test(h.text))return;let c=ss(h.dom);if(c.length!=1)return;l+=c[0].width,a=c[0].height}if(l)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:l/o.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=ss(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let l=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(Z.replace({widget:new Hi(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return Z.set(e)}updateDeco(){let e=1,t=this.view.state.facet(Ts).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(sl).map((r,o)=>{let l=typeof r=="function";return l&&(i=!0),l?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(B.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){var t;if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(Sc))try{if(c(this.view,e.range,e))return!0}catch(f){ae(this.view.state,f,"scroll handler")}let{range:i}=e,s=this.coordsAt(i.head,(t=i.assoc)!==null&&t!==void 0?t:i.empty?0:i.head>i.anchor?-1:1),r;if(!s)return;!i.empty&&(r=this.coordsAt(i.anchor,i.anchor>i.head?-1:1))&&(s={left:Math.min(s.left,r.left),top:Math.min(s.top,r.top),right:Math.max(s.right,r.right),bottom:Math.max(s.bottom,r.bottom)});let o=rl(this.view),l={left:s.left-o.left,top:s.top-o.top,right:s.right+o.right,bottom:s.bottom+o.bottom},{offsetWidth:a,offsetHeight:h}=this.view.scrollDOM;if(bp(this.view.scrollDOM,l,i.head1&&(s.top>window.pageYOffset+window.visualViewport.offsetTop+window.visualViewport.height||s.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){bo(this.tile)}};function bo(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)bo(i,e)}}function Bp(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function Tc(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=oc(t.focusNode,t.focusOffset),s=lc(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let l=F.get(s.node);if(!l||l.isText()&&l.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let a=F.get(i.node);!a||a.isText()&&a.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function Wp(n,e,t){let i=Tc(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,l=s.nodeValue;if(/[\n\r]/.test(l)||n.state.doc.sliceString(i.from,i.to)!=l)return null;let a=e.invertedDesc;return{range:new Ne(a.mapPos(r),a.mapPos(o),r,o),text:s}}function _p(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}var Hi=class extends ye{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function jp(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return b.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,l=r;t<0?o=te(s.text,r,!1):l=te(s.text,r);let a=i(s.text.slice(o,l));for(;o>0;){let h=te(s.text,o,!1);if(i(s.text.slice(h,o))!=a)break;o=h}for(;ln.defaultLineHeight*1.5){let l=n.viewState.heightOracle.textHeight,a=Math.floor((s-t.top-(n.defaultLineHeight-l)*.5)/l);r+=a*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Nn(o,r,n.state.tabSize)}function So(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!s||r.type==he.Text&&(s.type!=r.type||(t<0?r.frome)))&&(s=r)}}return s||i}return i}function Gp(n,e,t,i){let s=So(n,e.head,e.assoc||-1),r=!i||s.type!=he.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),l=n.textDirectionAt(s.from),a=n.posAtCoords({x:t==(l==z.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(a!=null)return b.cursor(a,t?-1:1)}return b.cursor(t?s.to:s.from,t?-1:1)}function vh(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let l=e,a=null;;){let h=Cp(s,r,o,l,t),c=uc;if(!h){if(s.number==(t?n.state.doc.lines:1))return l;c=` +`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),h=n.visualLineSide(s,!t)}if(a){if(!a(c))return l}else{if(!i)return h;a=i(c)}l=h}}function Up(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==q.Space&&(s=o),s==o}}function Fp(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return b.cursor(s,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),c=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=r<0?h.top:h.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(s-p.from))),l=(r<0?p.top:p.bottom)+c}let f=a.left+o,u=n.viewState.heightOracle.textHeight>>1,d=i??u;for(let p=0;;p+=u){let O=l+(d+p)*r,g=wo(n,{x:f,y:O},!1,r);if(t?O>a.bottom:Ol:x{if(e>r&&es(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:b.cursor(i,in.viewState.docHeight)return new ze(n.state.doc.length,-1);if(h=n.elementAtHeight(a),i==null)break;if(h.type==he.Text){if(i<0?h.ton.viewport.to)break;let u=n.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+r:u.bottom>=a+r))break}let f=n.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+f:h.top-f}if(n.viewport.from>=h.to||n.viewport.to<=h.from){if(t)return null;if(h.type==he.Text){let f=Np(n,s,h,o,l);return new ze(f,f==h.from?1:-1)}}if(h.type!=he.Text)return a<(h.top+h.bottom)/2?new ze(h.from,1):new ze(h.to,-1);let c=n.docView.lineAt(h.from,2);return(!c||c.length!=h.length)&&(c=n.docView.lineAt(h.from,-2)),new ko(n,o,l,n.textDirectionAt(h.from)).scanTile(c,h.from)}var ko=class{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from>1;t:if(r.has(p)){let g=i+Math.floor(Math.random()*d);for(let y=0;y1)){if(y.bottomthis.y)(!a||a.top>y.top)&&(a=y),x=-1;else{let S=y.left>this.x?this.x-y.left:y.right(d+d+p)/3)return this.y=l.bottom-1,this.scan(e,t);if(a&&a.top<(d+p+p)/3)return this.y=a.top+1,this.scan(e,t)}let u=(o?this.dirAt(e[h],1):this.baseDir)==z.LTR;return{i:h,after:this.x>(f.left+f.right)/2==u}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,l=i[r+1]-t;return on(e.dom,o,l).getClientRects()});return s.after?new ze(i[s.i+1],-1):new ze(i[s.i],1)}scanTile(e,t){if(!e.length)return new ze(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:on(a.dom,0,a.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new ze(i[s.i+1],-1):new ze(o,1)}},di="\uFFFF",Qo=class{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(Y.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=di}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=F.get(s),l=s.nextSibling;if(l==t){o?.breakAfter&&!l&&i!=this.view.contentDOM&&this.lineBreak();break}let a=F.get(l);(o&&a?o.breakAfter:(o?o.breakAfter:fs(s))||fs(l)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!Kp(l,t)&&this.lineBreak(),s=l}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,l;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=s.exec(t))&&(r=l.index,o=l[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){let t=F.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.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 i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(Hp(e,i.node,i.offset)?t:0))}};function Hp(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Zc(e.docView.tile,t,i,0))){let a=r||o?[]:eO(e),h=new Qo(a,e);h.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=h.text,this.newSel=tO(a,this.bounds.from)}else{let a=e.observer.selectionRange,h=r&&r.node==a.focusNode&&r.offset==a.focusOffset||!oo(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),c=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!oo(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),f=e.viewport;if((T.ios||T.chrome)&&l.main.empty&&h!=c&&(f.from>0||f.to-1&&l.ranges.length>1)this.newSel=l.replaceRange(b.range(c,h));else if(e.lineWrapping&&c==h&&!(l.main.empty&&l.main.head==h)&&e.inputState.lastTouchTime>Date.now()-100){let u=e.coordsAtPos(h,-1),d=0;u&&(d=e.inputState.lastTouchY<=u.bottom?-1:1),this.newSel=b.create([b.cursor(h,d)])}else this.newSel=b.single(c,h)}}};function Zc(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,l=-1;for(let a=0,h=i,c=i;at)return Zc(f,e,t,h);if(u>=e&&s==-1&&(s=a,r=h),h>t&&f.dom.parentNode==n.dom){o=a,l=c;break}c=u,h=u+f.breakAfter}return{from:r,to:l<0?i+n.length:l,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function Ac(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,h=r.from,c=null;(o===8||T.android&&e.text.length=l&&r.to<=a&&(e.typeOver||f!=e.text)&&f.slice(0,r.from-l)==e.text.slice(0,r.from-l)&&f.slice(r.to-l)==e.text.slice(u=e.text.length-(f.length-(r.to-l)))?t={from:r.from,to:r.to,insert:E.of(e.text.slice(r.from-l,u).split(di))}:(d=Mc(f,e.text,h-l,c))&&(T.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==di+di&&d.toB--,t={from:l+d.from,to:l+d.toA,insert:E.of(e.text.slice(d.from,d.toB).split(di))})}else i&&(!n.hasFocus&&s.facet(ut)||gs(i,r))&&(i=null);if(!t&&!i)return!1;if((T.mac||T.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:E.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:T.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(i&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:E.of([" "])}),t)return ol(n,t,i,o);if(i&&!gs(i,r)){let l=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(l=!0),a=n.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=Cc(s.facet(ln).map(h=>h(n)),i))),n.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function ol(n,e,t,i=-1){if(T.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(T.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&bi(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.lengths.head)&&bi(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&bi(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=Jp(n,e,t));return n.state.facet(gc).some(a=>a(n,e.from,e.to,r,l))||n.dispatch(l()),!0}function Jp(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let a=e.fromf(n)),h,a);e.from==c&&(o=c)}if(o>-1)i={changes:e,selection:b.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=r.frome.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let a=s.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let c=n.state.sliceDoc(e.from,e.to),f,u=t&&Tc(n,t.main.head);if(u){let p=e.insert.length-(e.to-e.from);f={from:u.from,to:u.to-p}}else f=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:a,range:h||p.map(a)};let O=p.to-d,g=O-c.length;if(n.state.sliceDoc(g,O)!=c||O>=f.from&&g<=f.to)return{range:p};let y=s.changes({from:g,to:O,insert:e.insert}),x=p.to-r.to;return{changes:y,range:h?b.range(Math.max(0,h.anchor+x),Math.max(0,h.head+x)):p.map(y)}})}else i={changes:a,selection:h&&s.selection.replaceRange(h)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:l,scrollIntoView:!0})}function Mc(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function eO(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new ms(t,i)),(s!=t||r!=i)&&e.push(new ms(s,r))),e}function tO(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?b.single(t+e,i+e):null}function gs(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}var $o=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,T.safari&&e.contentDOM.addEventListener("input",()=>null),T.gecko&&OO(e.contentDOM.ownerDocument)}handleEvent(e){!aO(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=iO(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,l=i[r];l&&o!=!l.handlers.length&&(s.removeEventListener(r,this.handleEvent),l=null),l||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,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&&Xc.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),T.android&&T.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return T.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&!e.shiftKey&&((t=Rc.find(i=>i.keyCode==e.keyCode))&&!e.ctrlKey||nO.indexOf(e.key)>-1&&e.ctrlKey)?(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:T.safari&&!T.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!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 $h(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ae(t.state,s)}}}function iO(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let l in r){let a=r[l];a&&t(l).handlers.push($h(i.value,a))}if(o)for(let l in o){let a=o[l];a&&t(l).observers.push($h(i.value,a))}}for(let i in Ge)t(i).handlers.push(Ge[i]);for(let i in ke)t(i).observers.push(ke[i]);return e}var Rc=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],nO="dthko",Xc=[16,17,18,20,91,92,224,225],Fn=6;function Hn(n){return Math.max(0,n)*.7+8}function sO(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}var Po=class{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=nc(e.contentDOM),this.atoms=e.state.facet(ln).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(Y.allowMultipleSelections)&&rO(e,t),this.dragging=lO(e,t)&&Dc(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&sO(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=rl(this.view);e.clientX-a.left<=s+Fn?t=-Hn(s-e.clientX):e.clientX+a.right>=o-Fn&&(t=Hn(e.clientX-o)),e.clientY-a.top<=r+Fn?i=-Hn(r-e.clientY):e.clientY+a.bottom>=l-Fn&&(i=Hn(e.clientY-l)),this.setScrollSpeed(t,i)}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(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=Cc(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function rO(n,e){let t=n.state.facet(dc);return t.length?t[0](e):T.mac?e.metaKey:e.ctrlKey}function oO(n,e){let t=n.state.facet(pc);return t.length?t[0](e):T.mac?!e.altKey:!e.ctrlKey}function lO(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=rn(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function aO(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=F.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}var Ge=Object.create(null),ke=Object.create(null),Lc=T.ie&&T.ie_version<15||T.ios&&T.webkit_version<604;function hO(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),Ec(n,t.value)},50)}function Cs(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function Ec(n,e){e=Cs(n.state,tl,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(To!=null&&t.selection.ranges.every(a=>a.empty)&&To==r.toString()){let a=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==a)return{range:h};a=c.from;let f=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:f},range:b.cursor(h.from+f.length)}})}else o?i=t.changeByRange(a=>{let h=r.line(s++);return{changes:{from:a.from,to:a.to,insert:h.text},range:b.cursor(a.from+h.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}ke.scroll=n=>{n.inputState.lastScrollTop=n.scrollDOM.scrollTop,n.inputState.lastScrollLeft=n.scrollDOM.scrollLeft};ke.wheel=ke.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ge.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);ke.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};ke.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};Ge.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(Oc))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=fO(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new Po(n,e,t,i)),i&&n.observer.ignore(()=>{sc(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Ph(n,e,t,i){if(i==1)return b.cursor(e,t);if(i==2)return jp(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,l=s?s.posAtEnd:r.to;return lDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Ch+1)%3:1}function fO(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=Dc(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,l){let a=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),h,c=Ph(n,a.pos,a.assoc,i);if(t.pos!=a.pos&&!o){let f=Ph(n,t.pos,t.assoc,i),u=Math.min(f.from,c.from),d=Math.max(f.to,c.to);c=u1&&(h=uO(s,a.pos))?h:l?s.addRange(c):b.create([c])}}}function uO(n,e){for(let t=0;t=e)return b.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ge.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=b.range(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",Cs(n.state,il,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ge.dragend=n=>(n.inputState.draggedContent=null,!1);function Ah(n,e,t,i){if(t=Cs(n.state,tl,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&oO(n,e)?{from:r.from,to:r.to}:null,l={from:s,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(s,-1),head:a.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ge.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Ah(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),r()},l.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Ah(n,e,i,!0),!0}return!1};Ge.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=Lc?null:e.clipboardData;return t?(Ec(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(hO(n),!1)};function dO(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function pO(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:Cs(n,il,e.join(n.lineBreak)),ranges:t,linewise:i}}var To=null;Ge.copy=Ge.cut=(n,e)=>{if(!Ni(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=pO(n.state);if(!t&&!s)return!1;To=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=Lc?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(dO(n,t),!1)};var Bc=xe.define();function Wc(n,e){let t=[];for(let i of n.facet(yc)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:Bc.of(!0)}):null}function _c(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=Wc(n.state,e);t?n.dispatch(t):n.update([])}},10)}ke.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),_c(n)};ke.blur=n=>{n.observer.clearSelectionRange(),_c(n)};ke.compositionstart=ke.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};ke.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,T.chrome&&T.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};ke.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ge.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let l=o[0],a=n.posAtDOM(l.startContainer,l.startOffset),h=n.posAtDOM(l.endContainer,l.endOffset);return ol(n,{from:a,to:h,insert:n.state.toText(r)},null),!0}}let s;if(T.chrome&&T.android&&(s=Rc.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return T.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),T.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>ke.compositionend(n,e),20),!1};var Mh=new Set;function OO(n){Mh.has(n)||(Mh.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}var Rh=["pre-wrap","normal","pre-line","break-spaces"],Qi=!1;function Xh(){Qi=!1}var Co=class{constructor(e){this.lineWrapping=e,this.doc=E.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Rh.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l||Math.abs(i-this.charWidth)>.1;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,a){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>rs&&(Qi=!0),this.height=e)}replace(e,t,i){return n.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let l=s.length-1;l>=0;l--){let{fromA:a,toA:h,fromB:c,toB:f}=s[l],u=r.lineAt(a,G.ByPosNoHeight,i.setDoc(t),0,0),d=u.to>=h?u:r.lineAt(h,G.ByPosNoHeight,i,0,0);for(f+=d.to-h,h=d.to;l>0&&u.from<=s[l-1].toA;)a=s[l-1].fromA,c=s[l-1].fromB,l--,ar*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,s-=l.size}else if(r>s*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,r-=l.size}else break;else if(s=r&&o(this.lineAt(0,G.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}},_e=class n extends bs{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new je(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof n||s instanceof St&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof St?s=new n(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):Ce.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(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:""})`}},St=class n extends Ce{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*r);o=a/r,this.length>r+1&&(l=(this.height-a)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:l}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,s);if(t.lineWrapping){let h=s+(e0){let r=i[i.length-1];r instanceof n?i[i.length-1]=new n(r.length+s):i.push(null,new n(s-1))}if(e>0){let r=i[0];r instanceof n?i[0]=new n(e+r.length):i.unshift(new n(e-1),null)}return Ce.of(i)}decomposeLeft(e,t){t.push(new n(e-1),null)}decomposeRight(e,t){t.push(null,new n(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],l=Math.max(t,s.from),a=-1;for(s.from>t&&o.push(new n(s.from-t-1).updateHeight(e,t));l<=r&&s.more;){let c=e.doc.lineAt(l).length;o.length&&o.push(null);let f=s.heights[s.index++],u=0;f<0&&(u=-f,f=s.heights[s.index++]),a==-1?a=f:Math.abs(f-a)>=rs&&(a=-2);let d=new _e(c,f,u);d.outdated=!1,o.push(d),l+=c+1}l<=r&&o.push(null,new n(r-l).updateHeight(e,l));let h=Ce.of(o);return(a<0||Math.abs(h.height-this.height)>=rs||Math.abs(a-this.heightMetrics(e,t).perLine)>=rs)&&(Qi=!0),ys(this,h)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},Ao=class extends Ce{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return el))return h;let c=t==G.ByPosNoHeight?G.ByPosNoHeight:G.ByPos;return a?h.join(this.right.lineAt(l,c,i,o,l)):this.left.lineAt(l,c,i,s,r).join(h)}forEachLine(e,t,i,s,r,o){let l=s+this.left.height,a=r+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,G.ByPos,i,s,r);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,l,a,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let l of i)r.push(l);if(e>0&&Lh(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?Ce.of(this.break?[e,null,t]:[e,t]):(this.left=ys(this.left,e),this.right=ys(this.right,t),this.setHeight(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,i=!1,s){let{left:r,right:o}=this,l=t+r.length+this.break,a=null;return s&&s.from<=t+r.length&&s.more?a=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=l+o.length&&s.more?a=o=o.updateHeight(e,l,i,s):o.updateHeight(e,l,i),a?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function Lh(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof St&&(i=n[e+1])instanceof St&&n.splice(e-1,3,new St(t.length+1+i.length))}var gO=5,Mo=class n{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 i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof _e?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new _e(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=gO)&&this.addLineDeco(s,r,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 _e(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new St(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof _e)return e;let t=new _e(0,-1,0);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,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof _e)&&!this.isCovered?this.nodes.push(new _e(0,-1,0)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&f.overflow!="visible"){let u=c.getBoundingClientRect();r=Math.max(r,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=Math.min(h==n.parentNode?s.innerHeight:a,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:r-t.left,right:Math.max(r,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function xO(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function SO(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var Ji=class{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new Co(i),this.stateDeco=Dh(t),this.heightMap=Ce.empty().applyChanges(this.stateDeco,E.empty,this.heightOracle.setDoc(t.doc),[new Ne(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Z.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new Oi(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?Eh:new Lo(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(Vi(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=Dh(this.state);let s=e.changedRanges,r=Ne.extendWithRanges(s,yO(i,this.stateDeco,e?e.changes:me.empty(this.state.doc.length))),o=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);Xh(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||Qi)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let a=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.heada.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let h=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,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(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(xc)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?z.RTL:z.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let h=0,c=0;if(l.width&&l.height){let{scaleX:w,scaleY:k}=ic(t,l);(w>.005&&Math.abs(this.scaleX-w)>.005||k>.005&&Math.abs(this.scaleY-k)>.005)&&(this.scaleX=w,this.scaleY=k,h|=16,o=a=!0)}let f=(parseInt(i.paddingTop)||0)*this.scaleY,u=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=f||this.paddingBottom!=u)&&(this.paddingTop=f,this.paddingBottom=u,h|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=16);let d=nc(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=rc(this.scrollParent||e.win);let O=(this.printing?SO:bO)(t,this.paddingTop),g=O.top-this.pixelViewport.top,y=O.bottom-this.pixelViewport.bottom;this.pixelViewport=O;let x=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(x!=this.inView&&(this.inView=x,x&&(a=!0)),!this.inView&&!this.scrollTarget&&!xO(e.dom))return 0;let S=l.width;if((this.contentDOMWidth!=S||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,h|=16),a){let w=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(w)&&(o=!0),o||s.lineWrapping&&Math.abs(S-this.contentDOMWidth)>s.charWidth){let{lineHeight:k,charWidth:Q,textHeight:X}=e.docView.measureTextSize();o=k>0&&s.refresh(r,k,Q,X,Math.max(5,S/Q),w),o&&(e.docView.minWidth=0,h|=16)}g>0&&y>0?c=Math.max(g,y):g<0&&y<0&&(c=Math.min(g,y)),Xh();for(let k of this.viewports){let Q=k.from==this.viewport.from?w:e.docView.measureVisibleLineHeights(k);this.heightMap=(o?Ce.empty().applyChanges(this.stateDeco,E.empty,this.heightOracle,[new Ne(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new Zo(k.from,Q))}Qi&&(h|=2)}let C=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return C&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(c,this.scrollTarget),h|=this.updateForViewport()),(h&2||C)&&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 i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new Oi(s.lineAt(o-i*1e3,G.ByHeight,r,0,0).from,s.lineAt(l+(1-i)*1e3,G.ByHeight,r,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),f=s.lineAt(h,G.ByPos,r,0,0),u;t.y=="center"?u=(f.top+f.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=z.LTR&&!i)return[];let l=[],a=(c,f,u,d)=>{if(f-cc&&yy.from>=u.from&&y.to<=u.to&&Math.abs(y.from-c)y.fromx));if(!g){if(fS.from<=f&&S.to>=f)){let S=t.moveToLineBoundary(b.cursor(f),!1,!0).head;S>c&&(f=S)}let y=this.gapSize(u,c,f,d),x=i||y<2e6?y:2e6;g=new Ji(c,f,y,x)}l.push(g)},h=c=>{if(c.length2e6)for(let k of e)k.from>=c.from&&k.fromc.from&&a(c.from,d,c,f),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];B.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Vi(this.heightMap.lineAt(e,G.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)||Vi(this.heightMap.lineAt(this.scaler.fromDOM(e),G.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}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 Vi(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}},Oi=class{constructor(e,t){this.from=e,this.to=t}};function wO(n,e,t){let i=[],s=n,r=0;return B.spans(t,n,e,{span(){},point(o,l){o>s&&(i.push({from:s,to:o}),r+=o-s),s=l}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],l=o-r;if(i<=l)return r+i;i-=l}}function Jn(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function kO(n,e){for(let t of n)if(e(t))return t}var Eh={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function Dh(n){let e=n.facet(Ts).filter(i=>typeof i!="function"),t=n.facet(sl).filter(i=>typeof i!="function");return t.length&&e.push(B.join(t)),e}var Lo=class n{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,G.ByPos,e,0,0).top,c=t.lineAt(a,G.ByPos,e,0,0).bottom;return s+=c-h,{from:l,to:a,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let l of this.viewports)l.domTop=o+(l.top-r)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),r=l.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}};function Vi(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new je(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>Vi(s,e)):n._content)}var es=$.define({combine:n=>n.join(" ")}),Eo=$.define({combine:n=>n.indexOf(!0)>-1}),Do=We.newName(),zc=We.newName(),Ic=We.newName(),Yc={"&light":"."+zc,"&dark":"."+Ic};function Bo(n,e,t){return new We(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}var QO=Bo("."+Do,{"&":{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,overflowAnchor:"none"},".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:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".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",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&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,zIndex:300},"&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-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".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",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".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"}},Yc),vO={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Hr=T.ie&&T.ie_version<=11,Wo=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new lo,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 i of t)this.queue.push(i);(T.ie&&T.ie_version<=11||T.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&T.android&&e.constructor.EDIT_CONTEXT!==!1&&!(T.chrome&&T.chrome_version<126)&&(this.editContext=new _o(e),e.state.facet(ut)&&(e.contentDOM.editContext=this.editContext.editContext)),Hr&&(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.type)&&!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,i)=>t!=e[i]))){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:i}=this,s=this.selectionRange;if(i.state.facet(ut)?i.root.activeElement!=this.dom:!Ni(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(T.ie&&T.ie_version<=11||T.android&&T.chrome)&&!i.state.selection.main.empty&&s.focusNode&&Gi(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=rn(e.root);if(!t)return!1;let i=T.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&$O(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=Ni(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&bi(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!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,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&Ni(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new vo(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}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 i=this.view.state,s=Ac(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!gs(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Bh(t,e.previousSibling||e.target.previousSibling,-1),s=Bh(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):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?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(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?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(ut)!=e.state.facet(ut)&&(e.view.contentDOM.editContext=e.state.facet(ut)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function Bh(n,e,t){for(;e;){let i=F.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function Wh(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return Gi(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function $O(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return Wh(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?Wh(n,t):null}var _o=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=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)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,l=this.toEditorPos(i.updateRangeStart),a=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:l,drifted:!1});let h=a-l>i.text.length;l==this.from&&rthis.to&&(a=r);let c=Mc(e.state.sliceDoc(l,a),i.text,(h?s.from:s.to)-l,h?"end":null);if(!c){let u=b.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));gs(u,s)||e.dispatch({selection:u,userEvent:"select"});return}let f={from:c.from+l,to:c.toA+l,insert:E.of(i.text.slice(c.from,c.toB).split(` +`))};if((T.mac||T.android)&&f.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(f={from:l,to:a,insert:E.of([i.text.replace("."," ")])}),this.pendingContextChange=f,!e.state.readOnly){let u=this.to-this.from+(f.to-f.from+f.insert.length);ol(e,f,b.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),f.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,l=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(r.rangeStart),h=this.toEditorPos(r.rangeEnd);if(a{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{this.editContext.updateControlBounds(i.contentDOM.getBoundingClientRect());let s=rn(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,l,a,h)=>{if(i)return;let c=h.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(h)){s=this.pendingContextChange=null,t+=c,this.to+=c;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=c,this.to+=c;else if(rthis.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),h.toString()),this.to+=c}t+=c}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&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)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},v=class n{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&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;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:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||xp(e.parent)||document,this.viewState=new xs(this,e.state||Y.create(e)),e.scrollTo&&e.scrollTo.is(Un)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(pi).map(s=>new Fi(s));for(let s of this.plugins)s.update(this);this.observer=new Wo(this),this.inputState=new $o(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Os(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof ie?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,i=!1,s,r=this.state;for(let u of e){if(u.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=u.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,l=0,a=null;e.some(u=>u.annotation(Bc))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=Wc(r,o),a||(l=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(c=null)):this.observer.clear(),r.facet(Y.phrases)!=this.state.facet(Y.phrases))return this.setState(r);s=ds.create(this,r,e),s.flags|=l;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,{x:p,y:O}=this.state.facet(n.cursorScrollMargin);f=new Ui(d.empty?d:b.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",O,p)}for(let d of u.effects)d.is(Un)&&(f=d.value.clip(this.state))}this.viewState.update(s,f),this.bidiCache=Ss.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(qi)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(es)!=s.state.facet(es)&&(this.viewState.mustMeasureContent=!0),(t||i||f||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let u of this.state.facet(fo))try{u(s)}catch(d){ae(this.state,d,"update listener")}(a||c)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),c&&!Ac(this,c)&&h.force&&bi(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 i of this.plugins)i.destroy(this);this.viewState=new xs(this,e),this.plugins=e.facet(pi).map(i=>new Fi(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new Os(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(pi),i=e.state.facet(pi);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Fi(r));else{let l=this.plugins[o];l.mustUpdate=e,s.push(l)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-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,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let l=0;;l++){if(o<0)if(rc(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(s);r=d.from,o=d.top}this.updateState=1;let a=this.viewState.measure();if(!a&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let h=[];a&4||([this.measureRequests,h]=[h,this.measureRequests]);let c=h.map(d=>{try{return d.read(this)}catch(p){return ae(this.state,p),_h}}),f=ds.create(this,this.state,[]),u=!1;f.flags|=a,t?t.flags|=a: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||p<-1)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let l of this.state.facet(fo))l(t)}get themeClasses(){return Do+" "+(this.state.facet(Eo)?Ic:zc)+" "+this.state.facet(es)}updateAttrs(){let e=zh(this,kc,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(ut)?"true":"false",class:"cm-content",style:`${T.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),zh(this,nl,t);let i=this.observer.ignore(()=>{let s=bh(this.contentDOM,this.contentAttrs,t),r=bh(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(n.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(qi);let e=this.state.facet(n.cspNonce);We.mount(this.root,this.styleModules.concat(QO).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;ti.plugin==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,i){return Fr(this,e,vh(this,e,t,i))}moveByGroup(e,t){return Fr(this,e,vh(this,e,t,i=>Up(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),s=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return b.cursor(r.side(t,s)+e.from,r.forward(!t,s)?1:-1)}moveToLineBoundary(e,t,i=!0){return Gp(this,e,t,i)}moveVertically(e,t,i){return Fr(this,e,Fp(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=wo(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),wo(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let s=this.state.doc.lineAt(e),r=this.bidiSpans(s),o=r[Ie.find(r,e-s.from,-1,t)];return us(i,o.dir==z.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(bc)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>PO)return fc(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||cc(r.isolates,i=wh(this,e))))return r.order;i||(i=wh(this,e));let s=Tp(e.text,t,i);return this.bidiCache.push(new Ss(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||T.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{sc(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={}){var i,s,r,o;return Un.of(new Ui(typeof e=="number"?b.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Un.of(new Ui(b.cursor(i.from),"start","start",i.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 H.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return H.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=We.newName(),s=[es.of(i),qi.of(Bo(`.${i}`,e))];return t&&t.dark&&s.push(Eo.of(!0)),s}static baseTheme(e){return Se.lowest(qi.of(Bo("."+Do,e,Yc)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&F.get(i)||F.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}};v.styleModule=qi;v.inputHandler=gc;v.clipboardInputFilter=tl;v.clipboardOutputFilter=il;v.scrollHandler=Sc;v.focusChangeEffect=yc;v.perLineTextDirection=bc;v.exceptionSink=mc;v.updateListener=fo;v.editable=ut;v.mouseSelectionStyle=Oc;v.dragMovesSelection=pc;v.clickAddsSelectionRange=dc;v.decorations=Ts;v.blockWrappers=Qc;v.outerDecorations=sl;v.atomicRanges=ln;v.bidiIsolatedRanges=vc;v.cursorScrollMargin=$.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});v.scrollMargins=$c;v.darkTheme=Eo;v.cspNonce=$.define({combine:n=>n.length?n[0]:""});v.contentAttributes=nl;v.editorAttributes=kc;v.lineWrapping=v.contentAttributes.of({class:"cm-lineWrapping"});v.announce=A.define();var PO=4096,_h={},Ss=class n{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:z.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&Ko(o,t)}return t}var TO=T.mac?"mac":T.windows?"win":T.linux?"linux":"key";function CO(n,e){let t=n.split(/-(?!$)/),i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,l;for(let a=0;ai.concat(s),[]))),t}function Vc(n,e,t){return jc(qc(n.state),e,n,t)}var xt=null,AO=4e3;function MO(n,e=TO){let t=Object.create(null),i=Object.create(null),s=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,l,a,h,c)=>{var f,u;let d=t[o]||(t[o]=Object.create(null)),p=l.split(/ (?!$)/).map(y=>CO(y,e));for(let y=1;y{let C=xt={view:S,prefix:x,scope:o};return setTimeout(()=>{xt==C&&(xt=null)},AO),!0}]})}let O=p.join(" ");s(O,!1);let g=d[O]||(d[O]={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())||[]});a&&g.run.push(a),h&&(g.preventDefault=!0),c&&(g.stopPropagation=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){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,zo))}let a=o[e]||o.key;if(a)for(let h of l)r(h,a,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(h,"Shift-"+a,o.shift,o.preventDefault,o.stopPropagation)}return t}var zo=null;function jc(n,e,t,i){zo=e;let s=ph(e),r=le(s,0),o=Te(r)==s.length&&s!=" ",l="",a=!1,h=!1,c=!1;xt&&xt.view==t&&xt.scope==i&&(l=xt.prefix+" ",Xc.indexOf(e.keyCode)<0&&(h=!0,xt=null));let f=new Set,u=g=>{if(g){for(let y of g.run)if(!f.has(y)&&(f.add(y),y(t)))return g.stopPropagation&&(c=!0),!0;g.preventDefault&&(g.stopPropagation&&(c=!0),h=!0)}return!1},d=n[i],p,O;return d&&(u(d[l+ts(s,e,!o)])?a=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(T.windows&&e.ctrlKey&&e.altKey)&&!(T.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=ft[e.keyCode])&&p!=s?(u(d[l+ts(p,e,!0)])||e.shiftKey&&(O=ui[e.keyCode])!=s&&O!=p&&u(d[l+ts(O,e,!1)]))&&(a=!0):o&&e.shiftKey&&u(d[l+ts(s,e,!0)])&&(a=!0),!a&&u(d._any)&&(a=!0)),h&&(a=!0),a&&c&&e.stopPropagation(),zo=null,a}var It=class n{constructor(e,t,i,s,r){this.className=e,this.left=t,this.top=i,this.width=s,this.height=r}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,i){if(i.empty){let s=e.coordsAtPos(i.head,i.assoc||1);if(!s)return[];let r=Nc(e);return[new n(t,s.left-r.left,s.top-r.top,null,s.bottom-s.top)]}else return RO(e,t,i)}};function Nc(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==z.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function Yh(n,e,t,i){let s=n.coordsAtPos(e,t*2);if(!s)return i;let r=n.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,l=n.posAtCoords({x:r.left+1,y:o}),a=n.posAtCoords({x:r.right-1,y:o});return l==null||a==null?i:{from:Math.max(i.from,Math.min(l,a)),to:Math.min(i.to,Math.max(l,a))}}function RO(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),s=Math.min(t.to,n.viewport.to),r=n.textDirection==z.LTR,o=n.contentDOM,l=o.getBoundingClientRect(),a=Nc(n),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),f=l.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),u=l.right-(c?parseInt(c.paddingRight):0),d=So(n,i,1),p=So(n,s,-1),O=d.type==he.Text?d:null,g=p.type==he.Text?p:null;if(O&&(n.lineWrapping||d.widgetLineBreaks)&&(O=Yh(n,i,1,O)),g&&(n.lineWrapping||p.widgetLineBreaks)&&(g=Yh(n,s,-1,g)),O&&g&&O.from==g.from&&O.to==g.to)return x(S(t.from,t.to,O));{let w=O?S(t.from,null,O):C(d,!1),k=g?S(null,t.to,g):C(p,!0),Q=[];return(O||d).to<(g||p).from-(O&&g?1:0)||d.widgetLineBreaks>1&&w.bottom+n.defaultLineHeight/2M&&_.from=Oe)break;Ee>N&&L(Math.max(oe,N),w==null&&oe<=M,Math.min(Ee,Oe),k==null&&Ee>=I,tt.dir)}if(N=ve.to+1,N>=Oe)break}return V.length==0&&L(M,w==null,I,k==null,n.textDirection),{top:X,bottom:D,horizontal:V}}function C(w,k){let Q=l.top+(k?w.top:w.bottom);return{top:Q,bottom:Q,horizontal:[]}}}function XO(n,e){return n.constructor==e.constructor&&n.eq(e)}var Io=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(os)!=e.state.facet(os)&&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,i=e.facet(os);for(;t!XO(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let s of e)s.update&&t&&s.constructor&&this.drawn[i].constructor&&s.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(s.draw(),t);for(;t;){let s=t.nextSibling;t.remove(),t=s}this.drawn=e,T.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},os=$.define();function Gc(n){return[H.define(e=>new Io(e,n)),os.of(n)]}var vi=$.define({combine(n){return ue(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function Uc(n={}){return[vi.of(n),LO,EO,DO,xc.of(!0)]}function Fc(n){return n.startState.facet(vi)!=n.state.facet(vi)}var LO=Gc({above:!0,markers(n){let{state:e}=n,t=e.facet(vi),i=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty||t.drawRangeCursor&&!(r&&T.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",l=s.empty?s:b.cursor(s.head,s.assoc);for(let a of It.forRange(n,o,l))i.push(a)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Fc(n);return t&&qh(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){qh(e.state,n)},class:"cm-cursorLayer"});function qh(n,e){e.style.animationDuration=n.facet(vi).cursorBlinkRate+"ms"}var EO=Gc({above:!1,markers(n){let e=[],{main:t,ranges:i}=n.state.selection;for(let s of i)if(!s.empty)for(let r of It.forRange(n,"cm-selectionBackground",s))e.push(r);if(T.ios&&!t.empty&&n.state.facet(vi).iosSelectionHandles){for(let s of It.forRange(n,"cm-selectionHandle cm-selectionHandle-start",b.cursor(t.from,1)))e.push(s);for(let s of It.forRange(n,"cm-selectionHandle cm-selectionHandle-end",b.cursor(t.to,1)))e.push(s)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||Fc(n)},class:"cm-selectionLayer"}),DO=Se.highest(v.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),Hc=A.define({map(n,e){return n==null?null:e.mapPos(n)}}),ji=K.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(Hc)?i.value:t,n)}}),BO=H.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(ji);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"),(n.startState.field(ji)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(ji),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(ji)!=n&&this.view.dispatch({effects:Hc.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Kc(){return[ji,BO]}function Vh(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,l;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;l=e.exec(r.value);)s(o+l.index,l)}function WO(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}var Yo=class{constructor(e){let{regexp:t,decoration:i,decorate:s,boundary:r,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,s)this.addMatch=(l,a,h,c)=>s(c,h,h+l[0].length,l,a);else if(typeof i=="function")this.addMatch=(l,a,h,c)=>{let f=i(l,a,h);f&&c(h,h+l[0].length,f)};else if(i)this.addMatch=(l,a,h,c)=>c(h,h+l[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new Pe,i=t.add.bind(t);for(let{from:s,to:r}of WO(e,this.maxLength))Vh(e.state.doc,this.regexp,s,r,(o,l)=>this.addMatch(l,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,l,a)=>{a>=e.view.viewport.from&&l<=e.view.viewport.to&&(i=Math.min(l,i),s=Math.max(a,s))}),e.viewportMoved||s-i>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),l=Math.min(r.to,s);if(l>=o){let a=e.state.doc.lineAt(o),h=a.toa.from;o--)if(this.boundary.test(a.text[o-1-a.from])){c=o;break}for(;lu.push(y.range(O,g));if(a==h)for(this.regexp.lastIndex=c-a.from;(d=this.regexp.exec(a.text))&&d.indexthis.addMatch(g,e,O,p));t=t.update({filterFrom:c,filterTo:f,filter:(O,g)=>Of,add:u})}}return t}},qo=/x/.unicode!=null?"gu":"g",_O=new RegExp(`[\0-\b +-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,qo),zO={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"},Kr=null;function IO(){var n;if(Kr==null&&typeof document<"u"&&document.body){let e=document.body.style;Kr=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Kr||!1}var ls=$.define({combine(n){let e=ue(n,{render:null,specialChars:_O,addSpecialChars:null});return(e.replaceTabs=!IO())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,qo)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,qo)),e}});function Jc(n={}){return[ls.of(n),YO()]}var jh=null;function YO(){return jh||(jh=H.fromClass(class{constructor(n){this.view=n,this.decorations=Z.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(ls)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Yo({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=le(e[0],0);if(r==9){let o=s.lineAt(i),l=t.state.tabSize,a=ct(o.text,l,i-o.from);return Z.replace({widget:new jo((l-a%l)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=Z.replace({widget:new Vo(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(ls);n.startState.facet(ls)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}var qO="\u2022";function VO(n){return n>=32?qO:n==10?"\u2424":String.fromCharCode(9216+n)}var Vo=class extends ye{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=VO(this.code),i=e.state.phrase("Control character")+" "+(zO[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}},jo=class extends ye{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 ef(){return NO}var jO=Z.line({class:"cm-activeLine"}),NO=H.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(jO.range(s.from)),e=s.from)}return Z.set(t)}},{decorations:n=>n.decorations});var No=2e3;function GO(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>No||t.off>No||e.col<0||t.col<0){let o=Math.min(e.off,t.off),l=Math.max(e.off,t.off);for(let a=i;a<=s;a++){let h=n.doc.line(a);h.length<=l&&r.push(b.range(h.from+o,h.to+l))}}else{let o=Math.min(e.col,t.col),l=Math.max(e.col,t.col);for(let a=i;a<=s;a++){let h=n.doc.line(a),c=Nn(h.text,o,n.tabSize,!0);if(c<0)r.push(b.cursor(h.to));else{let f=Nn(h.text,l,n.tabSize);r.push(b.range(h.from+c,h.from+f))}}}return r}function UO(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function Nh(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>No?-1:s==i.length?UO(n,e.clientX):ct(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function FO(n,e){let t=Nh(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let l=Nh(n,s);if(!l)return i;let a=GO(n.state,t,l);return a.length?o?b.create(a.concat(i.ranges)):b.create(a):i}}:null}function tf(n){let e=n?.eventFilter||(t=>t.altKey&&t.button==0);return v.mouseSelectionStyle.of((t,i)=>e(i)?FO(t,i):null)}var HO={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},KO={style:"cursor: crosshair"};function nf(n={}){let[e,t]=HO[n.key||"Alt"],i=H.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,v.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?KO:null})]}var is="-10000px",ws=class{constructor(e,t,i,s){this.facet=t,this.createTooltipView=i,this.removeTooltipView=s,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let s=e.state.facet(this.facet),r=s.filter(a=>a);if(s===this.input){for(let a of this.tooltipViews)a.update&&a.update(e);return!1}let o=[],l=t?[]:null;for(let a=0;at[h]=a),t.length=l.length),this.input=s,this.tooltips=r,this.tooltipViews=o,!0}};function JO(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}var Jr=$.define({combine:n=>{var e,t,i;return{position:T.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||JO}}}),Gh=new WeakMap,ll=H.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Jr);this.position=e.position,this.parent=e.parent,this.classes=n.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 ws(n,an,(t,i)=>this.createTooltip(t,i),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(),n.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 n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Jr);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",t.dom.appendChild(s)}return t.dom.style.position=this.position,t.dom.style.top=is,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);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 n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(T.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(n=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),s=rl(this.view);return{visible:{left:i.left+s.left,top:i.top+s.top,right:i.right-s.right,bottom:i.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let l=this.manager.tooltipViews[o];return l.getCoords?l.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Jr).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let l of this.manager.tooltipViews)l.dom.style.position="absolute"}let{visible:t,space:i,scaleX:s,scaleY:r}=n,o=[];for(let l=0;l=Math.min(t.bottom,i.bottom)||f.rightMath.min(t.right,i.right)+.1)){c.style.top=is;continue}let d=a.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,O=u.right-u.left,g=(e=Gh.get(h))!==null&&e!==void 0?e:u.bottom-u.top,y=h.offset||tm,x=this.view.textDirection==z.LTR,S=u.width>i.right-i.left?x?i.left:i.right-u.width:x?Math.max(i.left,Math.min(f.left-(d?14:0)+y.x,i.right-O)):Math.min(Math.max(i.left,f.left-O+(d?14:0)-y.x),i.right-O),C=this.above[l];!a.strictSide&&(C?f.top-g-p-y.yi.bottom)&&C==i.bottom-f.bottom>f.top-i.top&&(C=this.above[l]=!C);let w=(C?f.top-i.top:i.bottom-f.bottom)-p;if(wS&&X.topk&&(k=C?X.top-g-2-p:X.bottom+p+2);if(this.position=="absolute"?(c.style.top=(k-n.parent.top)/r+"px",Uh(c,(S-n.parent.left)/s)):(c.style.top=k/r+"px",Uh(c,S/s)),d){let X=f.left+(x?y.x:-y.x)-(S+14-7);d.style.left=X/s+"px"}h.overlap!==!0&&o.push({left:S,top:k,right:Q,bottom:k+g}),c.classList.toggle("cm-tooltip-above",C),c.classList.toggle("cm-tooltip-below",!C),h.positioned&&h.positioned(n.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 n of this.manager.tooltipViews)n.dom.style.top=is}},{eventObservers:{scroll(){this.maybeMeasure()}}});function Uh(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}var em=v.baseTheme({".cm-tooltip":{zIndex:500,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:"14px",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"}}}),tm={x:0,y:0},an=$.define({enables:[ll,em]}),ks=$.define({combine:n=>n.reduce((e,t)=>e.concat(t),[])}),Qs=class n{static create(e){return new n(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new ws(e,ks,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}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 i of this.manager.tooltipViews){let s=i[e];if(s!==void 0){if(t===void 0)t=s;else if(t!==s)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")}},im=an.compute([ks],n=>{let e=n.facet(ks);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:Qs.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),Go=class{constructor(e,t,i,s,r){this.view=e,this.source=t,this.field=i,this.setHover=s,this.hoverTime=r,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;el.bottom||t.xl.right+e.defaultCharacterWidth)return;let a=e.bidiSpans(e.state.doc.lineAt(s)).find(c=>c.from<=s&&c.to>=s),h=a&&a.dir==z.RTL?-1:1;r=t.x{this.pending==l&&(this.pending=null,a&&!(Array.isArray(a)&&!a.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(a)?a:[a])}))},a=>ae(e.state,a,"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(ll),t=e?e.manager.tooltips.findIndex(i=>i.create==Qs.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;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:s,tooltip:r}=this;if(s.length&&r&&!nm(r.dom,e)||this.pending){let{pos:o}=s[0]||this.pending,l=(i=(t=s[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==l?this.view.posAtCoords(this.lastMove)!=o:!sm(this.view,o,l,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:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t),this.active.length&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}},ns=4;function nm(n,e){let{left:t,right:i,top:s,bottom:r}=n.getBoundingClientRect(),o;if(o=n.querySelector(".cm-tooltip-arrow")){let l=o.getBoundingClientRect();s=Math.min(l.top,s),r=Math.max(l.bottom,r)}return e.clientX>=t-ns&&e.clientX<=i+ns&&e.clientY>=s-ns&&e.clientY<=r+ns}function sm(n,e,t,i,s,r){let o=n.scrollDOM.getBoundingClientRect(),l=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.rights||Math.min(o.bottom,l)=e&&a<=t}function sf(n,e={}){let t=A.define(),i=K.define({create(){return[]},update(s,r){if(s.length&&(e.hideOnChange&&(r.docChanged||r.selection)?s=[]:e.hideOn&&(s=s.filter(o=>!e.hideOn(r,o))),r.docChanged)){let o=[];for(let l of s){let a=r.changes.mapPos(l.pos,-1,se.TrackDel);if(a!=null){let h=Object.assign(Object.create(null),l);h.pos=a,h.end!=null&&(h.end=r.changes.mapPos(h.end)),o.push(h)}}s=o}for(let o of r.effects)o.is(t)&&(s=o.value),o.is(rm)&&(s=[]);return s},provide:s=>ks.from(s)});return{active:i,extension:[i,H.define(s=>new Go(s,n,i,t,e.hoverTime||300)),im]}}function al(n,e){let t=n.plugin(ll);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}var rm=A.define();var Fh=$.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function hn(n,e){let t=n.plugin(rf),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}var rf=H.fromClass(class{constructor(n){this.input=n.state.facet(jt),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(Fh);this.top=new mi(n,!0,e.topContainer),this.bottom=new mi(n,!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(n){let e=n.state.facet(Fh);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new mi(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new mi(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(jt);if(t!=this.input){let i=t.filter(a=>a),s=[],r=[],o=[],l=[];for(let a of i){let h=this.specs.indexOf(a),c;h<0?(c=a(n.view),l.push(c)):(c=this.panels[h],c.update&&c.update(n)),s.push(c),(c.top?r:o).push(c)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let a of l)a.dom.classList.add("cm-panel"),a.mount&&a.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>v.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})}),mi=class{constructor(e,t,i){this.view=e,this.top=t,this.container=i,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=Hh(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=Hh(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 Hh(n){let e=n.nextSibling;return n.remove(),e}var jt=$.define({enables:rf});function of(n,e){let t,i=new Promise(o=>t=o),s=o=>om(o,e,t);n.state.field(eo,!1)?n.dispatch({effects:lf.of(s)}):n.dispatch({effects:A.appendConfig.of(eo.init(()=>[s]))});let r=af.of(s);return{close:r,result:i.then(o=>((n.win.queueMicrotask||(a=>n.win.setTimeout(a,10)))(()=>{n.state.field(eo).indexOf(s)>-1&&n.dispatch({effects:r})}),o))}}var eo=K.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(lf)?n=[t.value].concat(n):t.is(af)&&(n=n.filter(i=>i!=t.value));return n},provide:n=>jt.computeN([n],e=>e.field(n))}),lf=A.define(),af=A.define();function om(n,e,t){let i=e.content?e.content(n,()=>o(null)):null;if(!i){if(i=W("form"),e.input){let l=W("input",e.input);/^(text|password|number|email|tel|url)$/.test(l.type)&&l.classList.add("cm-textfield"),l.name||(l.name="input"),i.appendChild(W("label",(e.label||"")+": ",l))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(W("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let l=0;l{h.keyCode==27?(h.preventDefault(),o(null)):h.keyCode==13&&(h.preventDefault(),o(a))}),a.addEventListener("submit",h=>{h.preventDefault(),o(a)})}let r=W("div",i,W("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["\xD7"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(l){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(l)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let l;typeof e.focus=="string"?l=i.querySelector(e.focus):l=i.querySelector("input")||i.querySelector("button"),l&&"select"in l?l.select():l&&"focus"in l&&l.focus()}}}}var Ze=class extends Be{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=se.TrackBefore;Ze.prototype.startSide=Ze.prototype.endSide=-1;Ze.prototype.point=!0;var as=$.define(),lm=$.define(),am={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>B.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},en=$.define();function hl(n){return[hf(),en.of({...am,...n})]}var Uo=$.define({combine:n=>n.some(e=>e)});function hf(n){let e=[hm];return n&&n.fixed===!1&&e.push(Uo.of(!0)),e}var hm=H.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(en).map(e=>new vs(n,e)),this.fixed=!n.state.facet(Uo);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(Uo)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=B.iter(this.view.state.facet(as),this.view.viewport.from),i=[],s=this.gutters.map(r=>new Ho(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let l of r.type)if(l.type==he.Text&&o){Fo(t,i,l.from);for(let a of s)a.line(this.view,l,i);o=!1}else if(l.widget)for(let a of s)a.widget(this.view,l)}else if(r.type==he.Text){Fo(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(en),t=n.state.facet(en),i=n.docChanged||n.heightChanged||n.viewportChanged||!B.eq(n.startState.facet(as),n.state.facet(as),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new vs(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>v.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==z.LTR?{left:i,right:s}:{right:i,left:s}})});function Kh(n){return Array.isArray(n)?n:[n]}function Fo(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}var Ho=class{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=B.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let l=new $s(e,o,r,i);s.elements.push(l),s.dom.appendChild(l.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Fo(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(lm)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},vs=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 i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let a=r.getBoundingClientRect();o=(a.top+a.bottom)/2}else o=s.clientY;let l=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,l,s)&&s.preventDefault()});this.markers=Kh(t.markers(e)),t.initialSpacer&&(this.spacer=new $s(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=Kh(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!B.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},$s=class{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),cm(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let l=o,a=rr(l,a,h)||o(l,a,h):o}return i}})}}),tn=class extends Ze{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function to(n,e){return n.state.facet(gi).formatNumber(e,n.state)}var dm=en.compute([gi],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(fm)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new tn(to(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(um)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(gi)!=e.state.facet(gi),initialSpacer(e){return new tn(to(e,Jh(e.state.doc.lines)))},updateSpacer(e,t){let i=to(t.view,Jh(t.view.state.doc.lines));return i==e.number?e:new tn(i)},domEventHandlers:n.facet(gi).domEventHandlers,side:"before"}));function cf(n={}){return[gi.of(n),hf(),dm]}function Jh(n){let e=9;for(;e{let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.head).from;s>t&&(t=s,e.push(pm.range(s)))}return B.of(e)});function ff(){return Om}var mm=0,cn=class{constructor(e,t){this.from=e,this.to=t}},R=class{constructor(e={}){this.id=mm++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=de.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}};R.closedBy=new R({deserialize:n=>n.split(" ")});R.openedBy=new R({deserialize:n=>n.split(" ")});R.group=new R({deserialize:n=>n.split(" ")});R.isolate=new R({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});R.contextHash=new R({perNode:!0});R.lookAhead=new R({perNode:!0});R.mounted=new R({perNode:!0});var Nt=class{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[R.mounted.id]}},gm=Object.create(null),de=class n{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):gm,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new n(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}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(R.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(R.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}};de.none=new de("",Object.create(null),0,8);var fn=class n{constructor(e){this.types=e;for(let t=0;t0;for(let a=this.cursor(o|U.IncludeAnonymous);;){let h=!1;if(a.from<=r&&a.to>=s&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;h=!0}for(;h&&i&&(l||!a.type.isAnonymous)&&i(a),!a.nextSibling();){if(!a.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:ml(de.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new n(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new n(de.none,t,i,s)))}static build(e){return bm(e)}};J.empty=new J(de.none,[],[],0);var cl=class n{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 n(this.buffer,this.index)}},vt=class n{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return de.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function un(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?l.length:-1;e!=h;e+=t){let c=l[e],f=a[e]+o.from,u;if(!(!(r&U.EnterBracketed&&c instanceof J&&(u=Nt.get(c))&&!u.overlay&&u.bracketed&&i>=f&&i<=f+c.length)&&!Of(s,i,f,f+c.length))){if(c instanceof vt){if(r&U.ExcludeBuffers)continue;let d=c.findChild(0,c.buffer.length,t,i-f,s);if(d>-1)return new Gt(new ul(o,c,e,f),null,d)}else if(r&U.IncludeAnonymous||!c.type.isAnonymous||Ol(c)){let d;if(!(r&U.IgnoreMounts)&&(d=Nt.get(c))&&!d.overlay)return new n(d.tree,f,e,o);let p=new n(c,f,e,o);return r&U.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?c.children.length-1:0,t,i,s,r)}}}if(r&U.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)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&U.IgnoreOverlays)&&(s=Nt.get(this._tree))&&s.overlay){let r=e-this.from,o=i&U.EnterBracketed&&s.bracketed;for(let{from:l,to:a}of s.overlay)if((t>0||o?l<=r:l=r:a>r))return new n(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}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 df(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function fl(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}var ul=class{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}},Gt=class n extends Ms{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,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new n(this.context,this,r)}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)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&U.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new n(this.context,this,r)}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 n(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 n(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new J(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function mf(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let l=new Ye(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(un(l,e,t,!1))}}return s?mf(s):i}var dn=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~U.EnterBracketed,e instanceof Ye)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.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:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof Ye?(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,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}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,i=this.mode){return this.buffer?i&U.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&U.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&U.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,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<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,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let l=i._tree.children[r];if(this.mode&U.IncludeAnonymous||l instanceof vt||!l.type.isAnonymous||Ol(l))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==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return fl(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}};function Ol(n){return n.children.some(e=>e instanceof vt||!e.type.isAnonymous||Ol(e))}function bm(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=1024,reused:r=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new cl(t,t.length):t,a=i.types,h=0,c=0;function f(w,k,Q,X,D,V){let{id:L,start:M,end:I,size:_}=l,N=c,Oe=h;if(_<0)if(l.next(),_==-1){let at=r[L];Q.push(at),X.push(M-w);return}else if(_==-3){h=L;return}else if(_==-4){c=L;return}else throw new RangeError(`Unrecognized record size: ${_}`);let ve=a[L],tt,oe,Ee=M-w;if(I-M<=s&&(oe=g(l.pos-k,D))){let at=new Uint16Array(oe.size-oe.skip),De=l.pos-oe.size,it=at.length;for(;l.pos>De;)it=y(oe.start,at,it);tt=new vt(at,I-oe.start,i),Ee=oe.start-w}else{let at=l.pos-_;l.next();let De=[],it=[],Lt=L>=o?L:-1,ri=0,Ln=I;for(;l.pos>at;)Lt>=0&&l.id==Lt&&l.size>=0?(l.end<=Ln-s&&(p(De,it,M,ri,l.end,Ln,Lt,N,Oe),ri=De.length,Ln=l.end),l.next()):V>2500?u(M,at,De,it):f(M,at,De,it,Lt,V+1);if(Lt>=0&&ri>0&&ri-1&&ri>0){let Ba=d(ve,Oe);tt=ml(ve,De,it,0,De.length,0,I-M,Ba,Ba)}else tt=O(ve,De,it,I-M,N-I,Oe)}Q.push(tt),X.push(Ee)}function u(w,k,Q,X){let D=[],V=0,L=-1;for(;l.pos>k;){let{id:M,start:I,end:_,size:N}=l;if(N>4)l.next();else{if(L>-1&&I=0;_-=3)M[N++]=D[_],M[N++]=D[_+1]-I,M[N++]=D[_+2]-I,M[N++]=N;Q.push(new vt(M,D[2]-I,i)),X.push(I-w)}}function d(w,k){return(Q,X,D)=>{let V=0,L=Q.length-1,M,I;if(L>=0&&(M=Q[L])instanceof J){if(!L&&M.type==w&&M.length==D)return M;(I=M.prop(R.lookAhead))&&(V=X[L]+M.length+I)}return O(w,Q,X,D,V,k)}}function p(w,k,Q,X,D,V,L,M,I){let _=[],N=[];for(;w.length>X;)_.push(w.pop()),N.push(k.pop()+Q-D);w.push(O(i.types[L],_,N,V-D,M-V,I)),k.push(D-Q)}function O(w,k,Q,X,D,V,L){if(V){let M=[R.contextHash,V];L=L?[M].concat(L):[M]}if(D>25){let M=[R.lookAhead,D];L=L?[M].concat(L):[M]}return new J(w,k,Q,X,L)}function g(w,k){let Q=l.fork(),X=0,D=0,V=0,L=Q.end-s,M={size:0,start:0,skip:0};e:for(let I=Q.pos-w;Q.pos>I;){let _=Q.size;if(Q.id==k&&_>=0){M.size=X,M.start=D,M.skip=V,V+=4,X+=4,Q.next();continue}let N=Q.pos-_;if(_<0||N=o?4:0,ve=Q.start;for(Q.next();Q.pos>N;){if(Q.size<0)if(Q.size==-3||Q.size==-4)Oe+=4;else break e;else Q.id>=o&&(Oe+=4);Q.next()}D=ve,X+=_,V+=Oe}return(k<0||X==w)&&(M.size=X,M.start=D,M.skip=V),M.size>4?M:void 0}function y(w,k,Q){let{id:X,start:D,end:V,size:L}=l;if(l.next(),L>=0&&X4){let I=l.pos-(L-4);for(;l.pos>I;)Q=y(w,k,Q)}k[--Q]=M,k[--Q]=V-w,k[--Q]=D-w,k[--Q]=X}else L==-3?h=X:L==-4&&(c=X);return Q}let x=[],S=[];for(;l.pos>0;)f(n.start||0,n.bufferStart||0,x,S,-1,0);let C=(e=n.length)!==null&&e!==void 0?e:x.length?S[0]+x[0].length:0;return new J(a[n.topID],x.reverse(),S.reverse(),C)}var pf=new WeakMap;function As(n,e){if(!n.isAnonymous||e instanceof vt||e.type!=n)return 1;let t=pf.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof J)){t=1;break}t+=As(n,i)}pf.set(e,t)}return t}function ml(n,e,t,i,s,r,o,l,a){let h=0;for(let p=i;p=c)break;k+=Q}if(S==C+1){if(k>c){let Q=p[C];d(Q.children,Q.positions,0,Q.children.length,O[C]+x);continue}f.push(p[C])}else{let Q=O[S-1]+p[S-1].length-w;f.push(ml(n,p,O,C,S,w,Q,null,a))}u.push(w+x-r)}}return d(e,t,i,s,0),(l||a)(f,u,o)}var Rs=class{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Gt?this.setBuffer(e.context.buffer,e.index,t):e instanceof Ye&&this.map.set(e.tree,t)}get(e){return e instanceof Gt?this.getBuffer(e.context.buffer,e.index):e instanceof Ye?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)}},Ut=class n{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new n(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let c=l=i)for(;o&&o.from=u.from||f<=u.to||h){let d=Math.max(u.from,a)-h,p=Math.min(u.to,f)-h;u=d>=p?null:new n(d,p,u.tree,u.offset+h,l>0,!!c)}if(u&&s.push(u),o.to>f)break;o=rnew cn(s.from,s.to)):[new cn(0,0)]:[new cn(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}},pl=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 rb=new R({perNode:!0});var bl=class n{constructor(e,t,i,s,r,o,l,a,h,c=0,f){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=l,this.bufferBase=a,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,i=0){let s=e.parser.context;return new n(e,[],t,i,i,0,[],0,s?new Xs(s,s.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 i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(s,h)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)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,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let l=o.stateFlag(r,1);!l&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let s=this.pos;this.reducePos=this.pos=s+e.length,this.pushState(t,s),this.buffer.push(i,s,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&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new n(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new xl(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}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 s=[];for(let r=0,o;ra&1&&l==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!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=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-r;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,r+1);if(l!=null)return l}})};return i(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;t0&&this.emitLookAhead()}},Xs=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},xl=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,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}},Sl=class n{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new n(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 n(this.stack,this.pos,this.index)}};function pn(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),r+=a,l)break;r*=46}t?t[s++]=r:t=new e(r)}return t}var Pi=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},gf=new Pi,wl=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=gf,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 i=this.range,s=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=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=gf,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 i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}},$t=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;wf(this.data,e,t,this.id,i.data,i.tokenPrecTable)}};$t.prototype.contextual=$t.prototype.fallback=$t.prototype.extend=!1;var Ti=class{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?pn(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(wf(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}};Ti.prototype.contextual=$t.prototype.fallback=$t.prototype.extend=!1;var Pt=class{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}};function wf(n,e,t,i,s,r){let o=0,l=1<0){let p=n[d];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||Sm(p,e.token.value,s,r))){e.acceptToken(p);break}}let c=e.next,f=0,u=n[o+2];if(e.next<0&&u>f&&n[h+u*3-3]==65535){o=n[h+u*3-1];continue e}for(;f>1,p=h+d+(d<<1),O=n[p],g=n[p+1]||65536;if(c=g)f=d+1;else{o=n[p+2],e.advance();continue e}}break}}function yf(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function Sm(n,e,t,i){let s=yf(t,i,e);return s<0||yf(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}var kl=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?bf(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?bf(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(r instanceof J){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}},Ql=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Pi)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hf.end+25&&(a=Math.max(f.lookAhead,a)),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&&(i=f,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new Pi,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Pi,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;re.bufferLength*4?new kl(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;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)i.push(l);else{if(this.advanceStack(l,i,e))continue;{s||(s=[],r=[]),s.push(l);let a=this.tokens.getMainToken(l);r.push(a.value,a.end)}}break}}if(!i.length){let o=s&&wm(s);if(o)return Ae&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw Ae&&s&&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&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return Ae&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&s>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(s);f;){let u=this.parser.nodeSet.types[f.type.id]==f.type?r.getGoto(e.state,f.type.id):-1;if(u>-1&&f.length&&(!h||(f.prop(R.contextHash)||0)==c))return e.useNode(f,u),Ae&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(f.type.id)})`),!0;if(!(f instanceof J)||f.children.length==0||f.positions[0]>0)break;let d=f.children[0];if(d instanceof J&&f.positions[0]==0)f=d;else break}}let l=r.stateSlot(e.state,4);if(l>0)return e.reduce(l),Ae&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hs?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return xf(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o ":"";if(l.deadEnd&&(r||(r=!0,l.restart(),Ae&&console.log(c+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let f=l.split(),u=c;for(let d=0;d<10&&f.forceReduce()&&(Ae&&console.log(u+this.stackID(f)+" (via force-reduce)"),!this.advanceFully(f,i));d++)Ae&&(u=this.stackID(f)+" -> ");for(let d of l.recoverByInsert(a))Ae&&console.log(c+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),Ae&&console.log(c+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),xf(l,i)):(!s||s.scoren,Ls=class{constructor(e){this.start=e.start,this.shift=e.shift||yl,this.reduce=e.reduce||yl,this.reuse=e.reuse||yl,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}},Es=class n extends $i{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 l=0;le.topRules[l][1]),s=[];for(let l=0;l=0)r(c,a,l[h++]);else{let f=l[h+-c];for(let u=-c;u>0;u--)r(l[h++],a,f);h++}}}this.nodeSet=new fn(t.map((l,a)=>de.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:s[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=pn(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new $t(o,l):l),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,i){let s=new vl(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],l=o&1,a=s[r++];if(l&&i)return a;for(let h=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Ot(this.data,r+2);else break;s=t(Ot(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Ot(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(n.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(l=>l.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=Sf(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),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}var km=0,Ue=class n{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=km++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof n&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new n(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new _s(e);return i=>i.modified.indexOf(t)>-1?i:_s.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}},Qm=0,_s=class n{constructor(e){this.name=e,this.instances=[],this.id=Qm++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&vm(t,l.modified));if(i)return i;let s=[],r=new Ue(e.name,s,e,t);for(let l of t)l.instances.push(r);let o=$m(t);for(let l of e.set)if(!l.modified.length)for(let a of o)s.push(n.get(l,a));return r}};function vm(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function $m(n){let e=[[]];for(let t=0;ti.length-t.length)}function zs(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,l=s;for(let f=0;;){if(l=="..."&&f>0&&f+3==s.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+s);if(r.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),f+=u[0].length,f==s.length)break;let d=s[f++];if(f==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);l=s.slice(f)}let a=r.length-1,h=r[a];if(!h)throw new RangeError("Invalid path: "+s);let c=new Ht(i,o,a>0?r.slice(0,a):null);e[h]=c.sort(e[h])}}return vf.add(e)}var vf=new R({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth>=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Ht(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}}),Ht=class{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let l of r)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function Pm(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function $f(n,e,t,i=0,s=n.length){let r=new Tl(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}var Tl=class{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,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,i,s,r){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=s,c=Tm(e)||Ht.empty,f=Pm(r,c.tags);if(f&&(h&&(h+=" "),h+=f,c.mode==1&&(s+=(s?" ":"")+f)),this.startSpan(Math.max(t,l),h),c.opaque)return;let u=e.tree&&e.tree.prop(R.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+l,1),p=this.highlighters.filter(g=>!g.scope||g.scope(u.tree.type)),O=e.firstChild();for(let g=0,y=l;;g++){let x=g=S||!e.nextSibling())););if(!x||S>i)break;y=x.to+l,y>t&&(this.highlightRange(d.cursor(),Math.max(t,x.from+l),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),h))}O&&e.parent()}else if(e.firstChild()){u&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}};function Tm(n){let e=n.type.prop(vf);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}var P=Ue.define,Ds=P(),Tt=P(),kf=P(Tt),Qf=P(Tt),Ct=P(),Bs=P(Ct),Pl=P(Ct),lt=P(),Ft=P(lt),rt=P(),ot=P(),Cl=P(),On=P(Cl),Ws=P(),m={comment:Ds,lineComment:P(Ds),blockComment:P(Ds),docComment:P(Ds),name:Tt,variableName:P(Tt),typeName:kf,tagName:P(kf),propertyName:Qf,attributeName:P(Qf),className:P(Tt),labelName:P(Tt),namespace:P(Tt),macroName:P(Tt),literal:Ct,string:Bs,docString:P(Bs),character:P(Bs),attributeValue:P(Bs),number:Pl,integer:P(Pl),float:P(Pl),bool:P(Ct),regexp:P(Ct),escape:P(Ct),color:P(Ct),url:P(Ct),keyword:rt,self:P(rt),null:P(rt),atom:P(rt),unit:P(rt),modifier:P(rt),operatorKeyword:P(rt),controlKeyword:P(rt),definitionKeyword:P(rt),moduleKeyword:P(rt),operator:ot,derefOperator:P(ot),arithmeticOperator:P(ot),logicOperator:P(ot),bitwiseOperator:P(ot),compareOperator:P(ot),updateOperator:P(ot),definitionOperator:P(ot),typeOperator:P(ot),controlOperator:P(ot),punctuation:Cl,separator:P(Cl),bracket:On,angleBracket:P(On),squareBracket:P(On),paren:P(On),brace:P(On),content:lt,heading:Ft,heading1:P(Ft),heading2:P(Ft),heading3:P(Ft),heading4:P(Ft),heading5:P(Ft),heading6:P(Ft),contentSeparator:P(lt),list:P(lt),quote:P(lt),emphasis:P(lt),strong:P(lt),link:P(lt),monospace:P(lt),strikethrough:P(lt),inserted:P(),deleted:P(),changed:P(),invalid:P(),meta:Ws,documentMeta:P(Ws),annotation:P(Ws),processingInstruction:P(Ws),definition:Ue.defineModifier("definition"),constant:Ue.defineModifier("constant"),function:Ue.defineModifier("function"),standard:Ue.defineModifier("standard"),local:Ue.defineModifier("local"),special:Ue.defineModifier("special")};for(let n in m){let e=m[n];e instanceof Ue&&(e.name=n)}var cb=Zl([{tag:m.link,class:"tok-link"},{tag:m.heading,class:"tok-heading"},{tag:m.emphasis,class:"tok-emphasis"},{tag:m.strong,class:"tok-strong"},{tag:m.keyword,class:"tok-keyword"},{tag:m.atom,class:"tok-atom"},{tag:m.bool,class:"tok-bool"},{tag:m.url,class:"tok-url"},{tag:m.labelName,class:"tok-labelName"},{tag:m.inserted,class:"tok-inserted"},{tag:m.deleted,class:"tok-deleted"},{tag:m.literal,class:"tok-literal"},{tag:m.string,class:"tok-string"},{tag:m.number,class:"tok-number"},{tag:[m.regexp,m.escape,m.special(m.string)],class:"tok-string2"},{tag:m.variableName,class:"tok-variableName"},{tag:m.local(m.variableName),class:"tok-variableName tok-local"},{tag:m.definition(m.variableName),class:"tok-variableName tok-definition"},{tag:m.special(m.variableName),class:"tok-variableName2"},{tag:m.definition(m.propertyName),class:"tok-propertyName tok-definition"},{tag:m.typeName,class:"tok-typeName"},{tag:m.namespace,class:"tok-namespace"},{tag:m.className,class:"tok-className"},{tag:m.macroName,class:"tok-macroName"},{tag:m.propertyName,class:"tok-propertyName"},{tag:m.operator,class:"tok-operator"},{tag:m.comment,class:"tok-comment"},{tag:m.meta,class:"tok-meta"},{tag:m.invalid,class:"tok-invalid"},{tag:m.punctuation,class:"tok-punctuation"}]);var Cm=316,Zm=317,Pf=1,Am=2,Mm=3,Rm=4,Xm=318,Lm=320,Em=321,Dm=5,Bm=6,Wm=0,Ml=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],Tf=125,_m=59,Rl=47,zm=42,Im=43,Ym=45,qm=60,Vm=44,jm=63,Nm=46,Gm=91,Um=new Ls({start:!1,shift(n,e){return e==Dm||e==Bm||e==Lm?n:e==Em},strict:!1}),Fm=new Pt((n,e)=>{let{next:t}=n;(t==Tf||t==-1||e.context)&&n.acceptToken(Xm)},{contextual:!0,fallback:!0}),Hm=new Pt((n,e)=>{let{next:t}=n,i;Ml.indexOf(t)>-1||t==Rl&&((i=n.peek(1))==Rl||i==zm)||t!=Tf&&t!=_m&&t!=-1&&!e.context&&n.acceptToken(Cm)},{contextual:!0}),Km=new Pt((n,e)=>{n.next==Gm&&!e.context&&n.acceptToken(Zm)},{contextual:!0}),Jm=new Pt((n,e)=>{let{next:t}=n;if(t==Im||t==Ym){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift(Pf);n.acceptToken(i?Pf:Am)}}else t==jm&&n.peek(1)==Nm&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(Mm))},{contextual:!0});function Al(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}var eg=new Pt((n,e)=>{if(n.next!=qm||!e.dialectEnabled(Wm)||(n.advance(),n.next==Rl))return;let t=0;for(;Ml.indexOf(n.next)>-1;)n.advance(),t++;if(Al(n.next,!0)){for(n.advance(),t++;Al(n.next,!1);)n.advance(),t++;for(;Ml.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==Vm)return;for(let i=0;;i++){if(i==7){if(!Al(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(Rm,-t)}),tg=zs({"get set async static":m.modifier,"for while do if else switch try catch finally return throw break continue default case defer":m.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":m.operatorKeyword,"let var const using function class extends":m.definitionKeyword,"import export from":m.moduleKeyword,"with debugger new":m.keyword,TemplateString:m.special(m.string),super:m.atom,BooleanLiteral:m.bool,this:m.self,null:m.null,Star:m.modifier,VariableName:m.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":m.function(m.variableName),VariableDefinition:m.definition(m.variableName),Label:m.labelName,PropertyName:m.propertyName,PrivatePropertyName:m.special(m.propertyName),"CallExpression/MemberExpression/PropertyName":m.function(m.propertyName),"FunctionDeclaration/VariableDefinition":m.function(m.definition(m.variableName)),"ClassDeclaration/VariableDefinition":m.definition(m.className),"NewExpression/VariableName":m.className,PropertyDefinition:m.definition(m.propertyName),PrivatePropertyDefinition:m.definition(m.special(m.propertyName)),UpdateOp:m.updateOperator,"LineComment Hashbang":m.lineComment,BlockComment:m.blockComment,Number:m.number,String:m.string,Escape:m.escape,ArithOp:m.arithmeticOperator,LogicOp:m.logicOperator,BitOp:m.bitwiseOperator,CompareOp:m.compareOperator,RegExp:m.regexp,Equals:m.definitionOperator,Arrow:m.function(m.punctuation),": Spread":m.punctuation,"( )":m.paren,"[ ]":m.squareBracket,"{ }":m.brace,"InterpolationStart InterpolationEnd":m.special(m.brace),".":m.derefOperator,", ;":m.separator,"@":m.meta,TypeName:m.typeName,TypeDefinition:m.definition(m.typeName),"type enum interface implements namespace module declare":m.definitionKeyword,"abstract global Privacy readonly override":m.modifier,"is keyof unique infer asserts":m.operatorKeyword,JSXAttributeValue:m.attributeValue,JSXText:m.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":m.angleBracket,"JSXIdentifier JSXNameSpacedName":m.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":m.attributeName,"JSXBuiltin/JSXIdentifier":m.standard(m.tagName)}),ig={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},ng={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},sg={__proto__:null,"<":193},Cf=Es.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}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],x2_R6l2[Q%opQ&z!_Q&}!aQ'P!bQ'R!cQ'q!uQ+`%lQ+l%zQ,Q&XQ,h&mQ-P&|W-p'k's't'wQ-w'oQ0X*nQ1P+mQ1c,PS2O,i,lQ2g-OQ2h-RQ2i-SQ2}-oW3P-r-s-v-xQ5a1QQ5m1_Q5q1eQ6V1uQ6a2QQ6k2ZU6z3O3R3UQ6}3SQ8]5bQ8e5oQ8g5rQ8l5zQ8u6WQ8{6`S9[6{7PQ9^7OQ:W8cQ:b8vQ:g8|Q:n9]Q;U:XQ;]:cQ;a:oQ;l;VR;o;^Q%zyQ'd!iQ'o!uU+m%{%|%}Q-W'VU-k'e'f'gS-o'k'uQ0Q*jS1Q+n+oQ2o-YS2{-l-mQ3S-tS4p0R0UQ5b1RQ6v2uQ6y2|Q7O3TU7{4r4s4vQ9z7}R;O9{S$wi>PR*{%VU%Ui%V>PR0f*yQ$viS(u#v+iS)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.lPQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.nSR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:Um,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[tg],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$I|Er$I|$I}$Dk$I}$JO$Dk$JO$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr(n%d_$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c'|'U]$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!b(SU(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!b(iP;=`<%l'}'|(oP;=`<%l&}'[(y]$i&j(WpOY(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Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr07[$D|k$i&j(Wp(Z!b'}0/l$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",tokenizers:[Hm,Km,Jm,eg,2,3,4,5,6,7,8,9,10,11,12,13,14,Fm,new Ti("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new Ti("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>ig[n]||-1},{term:343,get:n=>ng[n]||-1},{term:95,get:n=>sg[n]||-1}],tokenPrec:15201});var Xl,Ci=new R;function jl(n){return $.define({combine:n?e=>e.concat(n):void 0})}var js=new R,Me=class{constructor(e,t,i=[],s=""){this.data=e,this.name=s,Y.prototype.hasOwnProperty("tree")||Object.defineProperty(Y.prototype,"tree",{get(){return ee(this)}}),this.parser=t,this.extension=[Zt.of(this),Y.languageData.of((r,o,l)=>{let a=Zf(r,o,l),h=a.type.prop(Ci);if(!h)return[];let c=r.facet(h),f=a.type.prop(js);if(f){let u=a.resolve(o-a.from,l);for(let d of f)if(d.test(u,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(c)}}return c})].concat(i)}isActiveAt(e,t,i=-1){return Zf(e,t,i).type.prop(Ci)==this.data}findRegions(e){let t=e.facet(Zt);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop(Ci)==this.data){i.push({from:o,to:o+r.length});return}let l=r.prop(R.mounted);if(l){if(l.tree.prop(Ci)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+r.length});return}else if(l.overlay){let a=i.length;if(s(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new n(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function ee(n){let e=n.field(Me.state,!1);return e?e.tree:J.empty}var Bl=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 i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}},mn=null,Wl=class n{constructor(e,t,i=[],s,r,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new n(e,t,[],J.empty,0,i,[],null)}startParse(){return this.parser.startParse(new Bl(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=J.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}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(Ut.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=mn;mn=this;try{return e()}finally{mn=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Af(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,c,f,u)=>a.push({fromA:h,toA:c,fromB:f,toB:u})),i=Ut.applyChanges(i,a),s=J.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),f=e.mapPos(h.to,-1);ce.from&&(this.fragments=Af(this.fragments,s,r),this.skipped.splice(i--,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 $i{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let a=mn;if(a){for(let h of s)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new J(de.none,[],[],o-r)},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 mn}};function Af(n,e,t){return Ut.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}var yn=class n{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),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new n(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=Wl.create(e.facet(Zt).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new n(i)}};Me.state=K.define({create:yn.init,update(n,e){for(let t of e.effects)if(t.is(Me.setState))return t.value;return e.startState.facet(Zt)!=e.state.facet(Zt)?yn.init(e.state):n.apply(e)}});var Bf=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Bf=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var Ll=typeof navigator<"u"&&(!((Xl=navigator.scheduling)===null||Xl===void 0)&&Xl.isInputPending)?()=>navigator.scheduling.isInputPending():null,rg=H.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(Me.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(Me.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Bf(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,a=r.context.work(()=>Ll&&Ll()||Date.now()>o,s+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:Me.setState.of(new yn(r.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ae(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()}}}),Zt=$.define({combine(n){return n.length?n[0]:null},enables:n=>[Me.state,rg,v.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]}),Ys=class{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}};var og=$.define(),Ai=$.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function bn(n){let e=n.facet(Ai);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Mi(n,e){let t="",i=n.tabSize,s=n.facet(Ai)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=e?lg(n,t,e):null}var Kt=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=bn(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return ct(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},Nl=new R;function lg(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return Wf(i,n,t)}function Wf(n,e,t){for(let i=n;i;i=i.next){let s=hg(i.node);if(s)return s(_l.create(e,t,i))}return 0}function ag(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function hg(n){let e=n.type.prop(Nl);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(R.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>zf(o,!0,1,void 0,r&&!ag(o)?s.from:void 0)}return n.parent==null?cg:null}function cg(){return 0}var _l=class n extends Kt{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new n(e,t,i)}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 i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(fg(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return Wf(this.context.next,this.base,this.pos)}};function fg(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function ug(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped){if(a.from>=o)return null;let h=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+h}}l=a.to}}function _f({closing:n,align:e=!0,units:t=1}){return i=>zf(i,e,t,n)}function zf(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,l=i&&r.slice(o,o+i.length)==i||s==n.pos+o,a=e?ug(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}var If=n=>n.baseIndent;function Gs({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}var dg=200;function Yf(){return Y.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+dg)return n;let r=t.sliceString(s.from,i);if(!e.some(h=>h.test(r)))return n;let{state:o}=n,l=-1,a=[];for(let{head:h}of o.selection.ranges){let c=o.doc.lineAt(h);if(c.from==l)continue;l=c.from;let f=Ns(o,c.from);if(f==null)continue;let u=/^\s*/.exec(c.text)[0],d=Mi(o,f);u!=d&&a.push({from:c.from,to:c.from+u.length,insert:d})}return a.length?[n,{changes:a,sequential:!0}]:n})}var pg=$.define(),Gl=new R;function qf(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(r&&l.from=e&&h.to>t&&(r=h)}}return r}function mg(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function qs(n,e,t){for(let i of n.facet(pg)){let s=i(n,e,t);if(s)return s}return Og(n,e,t)}function Vf(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}var Us=A.define({map:Vf}),xn=A.define({map:Vf});function jf(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}var Jt=K.define({create(){return Z.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((t,i)=>n=Mf(n,t,i)),n=n.map(e.changes);for(let t of e.effects)if(t.is(Us)&&!gg(n,t.value.from,t.value.to)){let{preparePlaceholder:i}=e.state.facet(Ul),s=i?Z.replace({widget:new zl(i(e.state,t.value))}):Rf;n=n.update({add:[s.range(t.value.from,t.value.to)]})}else t.is(xn)&&(n=n.update({filter:(i,s)=>t.value.from!=i||t.value.to!=s,filterFrom:t.value.from,filterTo:t.value.to}));return e.selection&&(n=Mf(n,e.selection.main.head)),n},provide:n=>v.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{se&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(s,r)=>s>=t||r<=e}):n}function Vs(n,e,t){var i;let s=null;return(i=n.field(Jt,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!s||s.from>r)&&(s={from:r,to:o})}),s}function gg(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function Nf(n,e){return n.field(Jt,!1)?e:e.concat(A.appendConfig.of(Ff()))}var yg=n=>{for(let e of jf(n)){let t=qs(n.state,e.from,e.to);if(t)return n.dispatch({effects:Nf(n.state,[Us.of(t),Gf(n,t)])}),!0}return!1},bg=n=>{if(!n.state.field(Jt,!1))return!1;let e=[];for(let t of jf(n)){let i=Vs(n.state,t.from,t.to);i&&e.push(xn.of(i),Gf(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function Gf(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return v.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}var xg=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(Jt,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(xn.of({from:i,to:s}))}),n.dispatch({effects:t}),!0};var Uf=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:yg},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:bg},{key:"Ctrl-Alt-[",run:xg},{key:"Ctrl-Alt-]",run:Sg}],wg={placeholderDOM:null,preparePlaceholder:null,placeholderText:"\u2026"},Ul=$.define({combine(n){return ue(n,wg)}});function Ff(n){let e=[Jt,Qg];return n&&e.push(Ul.of(n)),e}function Hf(n,e){let{state:t}=n,i=t.facet(Ul),s=o=>{let l=n.lineBlockAt(n.posAtDOM(o.target)),a=Vs(n.state,l.from,l.to);a&&n.dispatch({effects:xn.of(a)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,s,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}var Rf=Z.replace({widget:new class extends ye{toDOM(n){return Hf(n,null)}}}),zl=class extends ye{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return Hf(e,this.value)}},kg={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},gn=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 Kf(n={}){let e={...kg,...n},t=new gn(e,!0),i=new gn(e,!1),s=H.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(Zt)!=o.state.facet(Zt)||o.startState.field(Jt,!1)!=o.state.field(Jt,!1)||ee(o.startState)!=ee(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let l=new Pe;for(let a of o.viewportLineBlocks){let h=Vs(o.state,a.from,a.to)?i:qs(o.state,a.from,a.to)?t:null;h&&l.add(a.from,a.from,h)}return l.finish()}}),{domEventHandlers:r}=e;return[s,hl({class:"cm-foldGutter",markers(o){var l;return((l=o.plugin(s))===null||l===void 0?void 0:l.markers)||B.empty},initialSpacer(){return new gn(e,!1)},domEventHandlers:{...r,click:(o,l,a)=>{if(r.click&&r.click(o,l,a))return!0;let h=Vs(o.state,l.from,l.to);if(h)return o.dispatch({effects:xn.of(h)}),!0;let c=qs(o.state,l.from,l.to);return c?(o.dispatch({effects:Us.of(c)}),!0):!1}}}),Ff()]}var Qg=v.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"}}),Zi=class n{constructor(e,t){this.specs=e;let i;function s(l){let a=We.newName();return(i||(i=Object.create(null)))["."+a]=l,a}let r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof Me?l=>l.prop(Ci)==o.data:o?l=>l==o:void 0,this.style=Zl(e.map(l=>({tag:l.tag,class:l.class||s(Object.assign({},l,{tag:null}))})),{all:r}).style,this.module=i?new We(i):null,this.themeType=t.themeType}static define(e,t){return new n(e,t||{})}},Il=$.define(),Jf=$.define({combine(n){return n.length?[n[0]]:null}});function El(n){let e=n.facet(Il);return e.length?e:n.facet(Jf)}function Fs(n,e){let t=[vg],i;return n instanceof Zi&&(n.module&&t.push(v.styleModule.of(n.module)),i=n.themeType),e?.fallback?t.push(Jf.of(n)):i?t.push(Il.computeN([v.darkTheme],s=>s.facet(v.darkTheme)==(i=="dark")?[n]:[])):t.push(Il.of(n)),t}var Yl=class{constructor(e){this.markCache=Object.create(null),this.tree=ee(e.state),this.decorations=this.buildDeco(e,El(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=ee(e.state),i=El(e.state),s=i!=El(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return Z.none;let i=new Pe;for(let{from:s,to:r}of e.visibleRanges)$f(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=Z.mark({class:a})))},s,r);return i.finish()}},vg=Se.high(H.fromClass(Yl,{decorations:n=>n.decorations})),eu=Zi.define([{tag:m.meta,color:"#404740"},{tag:m.link,textDecoration:"underline"},{tag:m.heading,textDecoration:"underline",fontWeight:"bold"},{tag:m.emphasis,fontStyle:"italic"},{tag:m.strong,fontWeight:"bold"},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.keyword,color:"#708"},{tag:[m.atom,m.bool,m.url,m.contentSeparator,m.labelName],color:"#219"},{tag:[m.literal,m.inserted],color:"#164"},{tag:[m.string,m.deleted],color:"#a11"},{tag:[m.regexp,m.escape,m.special(m.string)],color:"#e40"},{tag:m.definition(m.variableName),color:"#00f"},{tag:m.local(m.variableName),color:"#30a"},{tag:[m.typeName,m.namespace],color:"#085"},{tag:m.className,color:"#167"},{tag:[m.special(m.variableName),m.macroName],color:"#256"},{tag:m.definition(m.propertyName),color:"#00c"},{tag:m.comment,color:"#940"},{tag:m.invalid,color:"#f00"}]),$g=v.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),tu=1e4,iu="()[]{}",nu=$.define({combine(n){return ue(n,{afterCursor:!0,brackets:iu,maxScanDistance:tu,renderMatch:Cg})}}),Pg=Z.mark({class:"cm-matchingBracket"}),Tg=Z.mark({class:"cm-nonmatchingBracket"});function Cg(n){let e=[],t=n.matched?Pg:Tg;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function Xf(n){let e=[],t=n.facet(nu);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Fe(n,i.head,-1,t)||i.head>0&&Fe(n,i.head-1,1,t)||t.afterCursor&&(Fe(n,i.head,1,t)||i.headn.decorations}),Ag=[Zg,$g];function su(n={}){return[nu.of(n),Ag]}var Mg=new R;function ql(n,e,t){let i=n.prop(e<0?R.openedBy:R.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function Vl(n){let e=n.type.prop(Mg);return e?e(n.node):n}function Fe(n,e,t,i={}){let s=i.maxScanDistance||tu,r=i.brackets||iu,o=ee(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=ql(a.type,t,r);if(h&&a.from0?e>=c.from&&ec.from&&e<=c.to))return Rg(n,e,t,a,c,h,r)}}return Xg(n,e,t,o,l.type,s,r)}function Rg(n,e,t,i,s,r,o){let l=i.parent,a={from:s.from,to:s.to},h=0,c=l?.cursor();if(c&&(t<0?c.childBefore(i.from):c.childAfter(i.to)))do if(t<0?c.to<=i.from:c.from>=i.to){if(h==0&&r.indexOf(c.type.name)>-1&&c.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=n.doc.iterRange(e,t>0?n.doc.length:0),f=0;for(let u=0;!c.next().done&&u<=r;){let d=c.value;t<0&&(u+=d.length);let p=e+u*t;for(let O=t>0?0:d.length-1,g=t>0?d.length:-1;O!=g;O+=t){let y=o.indexOf(d[O]);if(!(y<0||i.resolveInner(p+O,1).type!=s))if(y%2==0==t>0)f++;else{if(f==1)return{start:h,end:{from:p+O,to:p+O+1},matched:y>>1==a>>1};f--}}t>0&&(u+=d.length)}return c.done?{start:h,matched:!1}:null}var Lg=Object.create(null),Lf=[de.none];var Ef=[],Df=Object.create(null),Eg=Object.create(null);for(let[n,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"]])Eg[n]=Dg(Lg,e);function Dl(n,e){Ef.indexOf(n)>-1||(Ef.push(n),console.warn(e))}function Dg(n,e){let t=[];for(let l of e.split(" ")){let a=[];for(let h of l.split(".")){let c=n[h]||m[h];c?typeof c=="function"?a.length?a=a.map(c):Dl(h,`Modifier ${h} used at start of tag`):a.length?Dl(h,`Tag ${h} used as modifier`):a=Array.isArray(c)?c:[c]:Dl(h,`Unknown highlighting tag ${h}`)}for(let h of a)t.push(h)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(l=>l.id),r=Df[s];if(r)return r.id;let o=Df[s]=de.define({id:Lf.length,name:i,props:[zs({[i]:t})]});return Lf.push(o),o.id}var Sb={rtl:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:z.RTL}),ltr:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:z.LTR}),auto:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};var Ks=class{constructor(e,t,i,s){this.state=e,this.pos=t,this.explicit=i,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=ee(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),i=Math.max(t.from,this.pos-250),s=t.text.slice(i-t.from,this.pos-t.from),r=s.search(pu(e,!1));return r<0?null:{from:i+r,to:this.pos,text:s.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}};function ru(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Bg(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Bg(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function du(n,e){return t=>{for(let i=ee(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}var Js=class{constructor(e,t,i,s){this.completion=e,this.source=t,this.match=i,this.score=s}};function ti(n){return n.selection.main.from}function pu(n,e){var t;let{source:i}=n,s=e&&i[0]!="^",r=i[i.length-1]!="$";return!s&&!r?n:new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}var ha=xe.define();function Wg(n,e,t,i){let{main:s}=n.selection,r=t-s.from,o=i-s.from;return{...n.changeByRange(l=>{if(l!=s&&t!=i&&n.sliceDoc(l.from+r,l.from+o)!=n.sliceDoc(t,i))return{range:l};let a=n.toText(e);return{changes:{from:l.from+r,to:i==s.from?l.to:l.from+o,insert:a},range:b.cursor(l.from+r+a.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}var ou=new WeakMap;function _g(n){if(!Array.isArray(n))return n;let e=ou.get(n);return e||ou.set(n,e=aa(n)),e}var er=A.define(),Sn=A.define(),Jl=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:(k=Yi(w))!=k.toLowerCase()?1:k!=k.toUpperCase()?2:0;(!x||Q==1&&g||C==0&&Q!=0)&&(t[f]==w||i[f]==w&&(u=!0)?o[f++]=x:o.length&&(y=!1)),C=Q,x+=Te(w)}return f==a&&o[0]==0&&y?this.result(-100+(u?-200:0),o,e):d==a&&p==0?this.ret(-200-e.length+(O==e.length?0:-100),[0,O]):l>-1?this.ret(-700-e.length,[l,l+this.pattern.length]):d==a?this.ret(-900-e.length,[p,O]):f==a?this.result(-100+(u?-200:0)+-700+(y?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[],r=0;for(let o of t){let l=o+(this.astral?Te(le(i,o)):1);r&&s[r-1]==o?s[r-1]=l:(s[r++]=o,s[r++]=l)}return this.ret(e-i.length,s)}},ea=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:zg,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>lu(e(i),t(i)),optionClass:(e,t)=>i=>lu(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function lu(n,e){return n?e?n+" "+e:n:e}function zg(n,e,t,i,s,r){let o=n.textDirection==z.RTL,l=o,a=!1,h="top",c,f,u=e.left-s.left,d=s.right-e.right,p=i.right-i.left,O=i.bottom-i.top;if(l&&u=O||x>e.top?c=t.bottom-e.top:(h="bottom",c=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,y=(e.right-e.left)/r.offsetWidth;return{style:`${h}: ${c/g}px; max-width: ${f/y}px`,class:"cm-completionInfo-"+(a?o?"left-narrow":"right-narrow":l?"left":"right")}}var ca=A.define();function Ig(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s,r){let o=document.createElement("span");o.className="cm-completionLabel";let l=t.displayLabel||t.label,a=0;for(let h=0;ha&&o.appendChild(document.createTextNode(l.slice(a,c)));let u=o.appendChild(document.createElement("span"));u.appendChild(document.createTextNode(l.slice(c,f))),u.className="cm-completionMatchedText",a=f}return at.position-i.position).map(t=>t.render)}function Fl(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.floor((n-e)/t);return{from:n-(i+1)*t,to:n-i*t}}var ta=class{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:a=>this.placeInfo(a),key:this},this.space=null,this.currentClass="";let s=e.state.field(t),{options:r,selected:o}=s.open,l=e.state.facet(re);this.optionContent=Ig(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=Fl(r.length,o,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",a=>{let{options:h}=e.state.field(t).open;for(let c=a.target,f;c&&c!=this.dom;c=c.parentNode)if(c.nodeName=="LI"&&(f=/-(\d+)$/.exec(c.id))&&+f[1]this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;c!=null&&(e.dispatch({effects:ca.of(c)}),a.preventDefault())}}),this.dom.addEventListener("focusout",a=>{let h=e.state.field(this.stateField,!1);h&&h.tooltip&&e.state.facet(re).closeOnBlur&&a.relatedTarget!=e.contentDOM&&e.dispatch({effects:Sn.of(null)})}),this.showOptions(r,s.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 i=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=s){let{options:r,selected:o,disabled:l}=i.open;(!s.open||s.open.options!=r)&&(this.range=Fl(r.length,o,e.state.facet(re).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),l!=((t=s.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);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;(t.selected>-1&&t.selected=this.range.to)&&(this.range=Fl(t.options.length,t.selected,this.view.state.facet(re).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:s}=t.options[t.selected],{info:r}=s;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(s);if(!o)return;"then"in o?o.then(l=>{l&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(l,s)}).catch(l=>ae(this.view.state,l,"completion info")):(this.addInfoPane(o,s),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:r}=e;i.appendChild(s),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)i.nodeName!="LI"||!i.id?s--:s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&qg(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return s.top>Math.min(r.bottom,t.bottom)-10||s.bottom{o.target==s&&o.preventDefault()});let r=null;for(let o=i.from;oi.from||i.from==0))if(r=u,typeof h!="string"&&h.header)s.appendChild(h.header(h));else{let d=s.appendChild(document.createElement("completion-section"));d.textContent=u}}let c=s.appendChild(document.createElement("li"));c.id=t+"-"+o,c.setAttribute("role","option");let f=this.optionClass(l);f&&(c.className=f);for(let u of this.optionContent){let d=u(l,this.view.state,this.view,a);d&&c.appendChild(d)}}return i.from&&s.classList.add("cm-completionListIncompleteTop"),i.tonew ta(t,n,e)}function qg(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),s=t.height/n.offsetHeight;i.topt.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/s)}function au(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function Vg(n,e){let t=[],i=null,s=null,r=c=>{t.push(c);let{section:f}=c.completion;if(f){i||(i=[]);let u=typeof f=="string"?f:f.name;i.some(d=>d.name==u)||i.push(typeof f=="string"?{name:u}:f)}},o=e.facet(re);for(let c of n)if(c.hasResult()){let f=c.result.getMatch;if(c.result.filter===!1)for(let u of c.result.options)r(new Js(u,c.source,f?f(u):[],1e9-t.length));else{let u=e.sliceDoc(c.from,c.to),d,p=o.filterStrict?new ea(u):new Jl(u);for(let O of c.result.options)if(d=p.match(O.label)){let g=O.displayLabel?f?f(O,d.matched):[]:d.matched,y=d.score+(O.boost||0);if(r(new Js(O,c.source,g,y)),typeof O.section=="object"&&O.section.rank==="dynamic"){let{name:x}=O.section;s||(s=Object.create(null)),s[x]=Math.max(y,s[x]||-1e9)}}}}if(i){let c=Object.create(null),f=0,u=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?s[p.name]-s[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.nameu.score-f.score||h(f.completion,u.completion))){let f=c.completion;!a||a.label!=f.label||a.detail!=f.detail||a.type!=null&&f.type!=null&&a.type!=f.type||a.apply!=f.apply||a.boost!=f.boost?l.push(c):au(c.completion)>au(a)&&(l[l.length-1]=c),a=c.completion}return l}var ia=class n{constructor(e,t,i,s,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new n(this.options,hu(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,s,r,o){if(s&&!o&&e.some(h=>h.isPending))return s.setDisabled();let l=Vg(e,t);if(!l.length)return s&&e.some(h=>h.isPending)?s.setDisabled():null;let a=t.facet(re).selectOnOpen?0:-1;if(s&&s.selected!=a&&s.selected!=-1){let h=s.options[s.selected].completion;for(let c=0;cc.hasResult()?Math.min(h,c.from):h,1e8),create:Hg,above:r.aboveCursor},s?s.timestamp:Date.now(),a,!1)}map(e){return new n(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new n(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}},na=class n{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new n(Ug,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(re),r=(i.override||t.languageDataAt("autocomplete",ti(t)).map(_g)).map(a=>(this.active.find(c=>c.source==a)||new mt(a,this.active.some(c=>c.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((a,h)=>a==this.active[h])&&(r=this.active);let o=this.open,l=e.effects.some(a=>a.is(fa));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(a=>a.hasResult()&&e.changes.touchesRange(a.from,a.to))||!jg(r,this.active)||l?o=ia.build(r,t,this.id,o,i,l):o&&o.disabled&&!r.some(a=>a.isPending)&&(o=null),!o&&r.every(a=>!a.isPending)&&r.some(a=>a.hasResult())&&(r=r.map(a=>a.hasResult()?new mt(a.source,0):a));for(let a of e.effects)a.is(ca)&&(o=o&&o.setSelected(a.value,this.id));return r==this.active&&o==this.open?this:new n(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Ng:Gg}};function jg(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}var Ug=[];function Ou(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(ha);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}var mt=class n{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=Ou(e,t),s=this;(i&8||i&16&&this.touches(e))&&(s=new n(s.source,0)),i&4&&s.state==0&&(s=new n(this.source,1)),s=s.updateFor(e,i);for(let r of e.effects)if(r.is(er))s=new n(s.source,1,r.value);else if(r.is(Sn))s=new n(s.source,0);else if(r.is(fa))for(let o of r.value)o.source==s.source&&(s=o);return s}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(ti(e.state))}},tr=class n extends mt{constructor(e,t,i,s,r,o){super(e,3,t),this.limit=i,this.result=s,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),l=ti(e.state);if(l>o||!s||t&2&&(ti(e.startState)==this.from||lt.map(e))}}),Qe=K.define({create(){return na.start()},update(n,e){return n.update(e)},provide:n=>[an.from(n,e=>e.tooltip),v.contentAttributes.from(n,e=>e.attrs)]});function ua(n,e){let t=e.completion.apply||e.completion.label,i=n.state.field(Qe).active.find(s=>s.source==e.source);return i instanceof tr?(typeof t=="string"?n.dispatch({...Wg(n.state,t,i.from,i.to),annotations:ha.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}var Hg=Yg(Qe,ua);function Hs(n,e="option"){return t=>{let i=t.state.field(Qe,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+s*(n?1:-1):n?0:o-1;return l<0?l=e=="page"?0:o-1:l>=o&&(l=e=="page"?o-1:0),t.dispatch({effects:ca.of(l)}),!0}}var Kg=n=>{let e=n.state.field(Qe,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestampn.state.field(Qe,!1)?(n.dispatch({effects:er.of(!0)}),!0):!1,Jg=n=>{let e=n.state.field(Qe,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Sn.of(null)}),!0)},sa=class{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}},e0=50,t0=1e3,i0=H.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(Qe).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(Qe),t=n.state.facet(re);if(!n.selectionSet&&!n.docChanged&&n.startState.field(Qe)==e)return;let i=n.transactions.some(r=>{let o=Ou(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;re0&&Date.now()-o.time>t0){for(let l of o.context.abortListeners)try{l()}catch(a){ae(this.view.state,a)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(r=>r.effects.some(o=>o.is(er)))&&(this.pendingStart=!0);let s=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let r of n.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(Qe);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(re).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=ti(e),i=new Ks(e,t,n.explicit,this.view),s=new sa(n,i);this.running.push(s),Promise.resolve(n.source(i)).then(r=>{s.context.aborted||(s.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:Sn.of(null)}),ae(this.view.state,r)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(re).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(re),i=this.view.state.field(Qe);for(let s=0;sl.source==r.active.source);if(o&&o.isPending)if(r.done==null){let l=new mt(r.active.source,0);for(let a of r.updates)l=l.update(a,t);l.isPending||e.push(l)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:fa.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(Qe,!1);if(e&&e.tooltip&&this.view.state.facet(re).closeOnBlur){let t=e.open&&al(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Sn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:er.of(!1)}),20),this.composing=0}}}),n0=typeof navigator=="object"&&/Win/.test(navigator.platform),s0=Se.highest(v.domEventHandlers({keydown(n,e){let t=e.state.field(Qe,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(n0&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],s=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||s.result.commitCharacters;return r&&r.indexOf(n.key)>-1&&ua(e,i),!1}})),mu=v.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",whiteSpace:"pre-line"},".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"}}}),ra=class{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}},oa=class n{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,se.TrackDel),i=e.mapPos(this.to,1,se.TrackDel);return t==null||i==null?null:new n(this.field,t,i)}},la=class n{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let a of this.lines){if(i.length){let h=o,c=/^\t*/.exec(a)[0].length;for(let f=0;fnew oa(a.field,s[a.line]+a.from,s[a.line]+a.to));return{text:i,ranges:l}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let l=r[1]?+r[1]:null,a=r[2]||r[3]||"",h=-1,c=a.replace(/\\[{}]/g,f=>f[1]);for(let f=0;f=h&&u.field++}for(let f of s)if(f.line==i.length&&f.from>r.index){let u=r[2]?3+(r[1]||"").length:2;f.from-=u,f.to-=u}s.push(new ra(h,i.length,r.index,r.index+c.length)),o=o.slice(0,r.index)+a+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(l,a,h)=>{for(let c of s)c.line==i.length&&c.from>h&&(c.from--,c.to--);return a}),i.push(o)}return new n(i,s)}},r0=Z.widget({widget:new class extends ye{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),o0=Z.mark({class:"cm-snippetField"}),Ri=class n{constructor(e,t){this.ranges=e,this.active=t,this.deco=Z.set(e.map(i=>(i.from==i.to?r0:o0).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new n(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}},Qn=A.define({map(n,e){return n&&n.map(e)}}),l0=A.define(),wn=K.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(Qn))return t.value;if(t.is(l0)&&n)return new Ri(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>v.decorations.from(n,e=>e?e.deco:Z.none)});function da(n,e){return b.create(n.filter(t=>t.field==e).map(t=>b.range(t.from,t.to)))}function a0(n){let e=la.parse(n);return(t,i,s,r)=>{let{text:o,ranges:l}=e.instantiate(t.state,s),{main:a}=t.state.selection,h={changes:{from:s,to:r==a.from?a.to:r,insert:E.of(o)},scrollIntoView:!0,annotations:i?[ha.of(i),ie.userEvent.of("input.complete")]:void 0};if(l.length&&(h.selection=da(l,0)),l.some(c=>c.field>0)){let c=new Ri(l,0),f=h.effects=[Qn.of(c)];t.state.field(wn,!1)===void 0&&f.push(A.appendConfig.of([wn,d0,p0,mu]))}t.dispatch(t.state.update(h))}}function gu(n){return({state:e,dispatch:t})=>{let i=e.field(wn,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:da(i.ranges,s),effects:Qn.of(r?null:new Ri(i.ranges,s)),scrollIntoView:!0})),!0}}var h0=({state:n,dispatch:e})=>n.field(wn,!1)?(e(n.update({effects:Qn.of(null)})),!0):!1,c0=gu(1),f0=gu(-1);var u0=[{key:"Tab",run:c0,shift:f0},{key:"Escape",run:h0}],cu=$.define({combine(n){return n.length?n[0]:u0}}),d0=Se.highest(Qt.compute([cu],n=>n.facet(cu)));function be(n,e){return{...e,apply:a0(n)}}var p0=v.domEventHandlers({mousedown(n,e){let t=e.state.field(wn,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:da(t.ranges,s.field),effects:Qn.of(t.ranges.some(r=>r.field>s.field)?new Ri(t.ranges,s.field):null),scrollIntoView:!0}),!0)}});var kn={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},ei=A.define({map(n,e){let t=e.mapPos(n,-1,se.TrackAfter);return t??void 0}}),pa=new class extends Be{};pa.startSide=1;pa.endSide=-1;var yu=K.define({create(){return B.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(ei)&&(n=n.update({add:[pa.range(t.value,t.value+1)]}));return n}});function bu(){return[m0,yu]}var Kl="()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";function xu(n){for(let e=0;e{if((O0?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Te(le(i,0))==1||e!=s.from||t!=s.to)return!1;let r=y0(n.state,i);return r?(n.dispatch(r),!0):!1}),g0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=Su(n,n.selection.main.head).brackets||kn.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let l=b0(n.doc,o.head);for(let a of i)if(a==l&&ir(n.doc,o.head)==xu(le(a,0)))return{changes:{from:o.head-a.length,to:o.head+a.length},range:b.cursor(o.head-a.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},wu=[{key:"Backspace",run:g0}];function y0(n,e){let t=Su(n,n.selection.main.head),i=t.brackets||kn.brackets;for(let s of i){let r=xu(le(s,0));if(e==s)return r==s?w0(n,s,i.indexOf(s+s+s)>-1,t):x0(n,s,r,t.before||kn.before);if(e==r&&ku(n,n.selection.main.from))return S0(n,s,r)}return null}function ku(n,e){let t=!1;return n.field(yu).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function ir(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Te(le(t,0)))}function b0(n,e){let t=n.sliceString(e-2,e);return Te(le(t,0))==t.length?t:t.slice(1)}function x0(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:ei.of(o.to+e.length),range:b.range(o.anchor+e.length,o.head+e.length)};let l=ir(n.doc,o.head);return!l||/\s/.test(l)||i.indexOf(l)>-1?{changes:{insert:e+t,from:o.head},effects:ei.of(o.head+e.length),range:b.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function S0(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&ir(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:b.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function w0(n,e,t,i){let s=i.stringPrefixes||kn.stringPrefixes,r=null,o=n.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:ei.of(l.to+e.length),range:b.range(l.anchor+e.length,l.head+e.length)};let a=l.head,h=ir(n.doc,a),c;if(h==e){if(fu(n,a))return{changes:{insert:e+e,from:a},effects:ei.of(a+e.length),range:b.cursor(a+e.length)};if(ku(n,a)){let u=t&&n.sliceDoc(a,a+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:a,to:a+u.length,insert:u},range:b.cursor(a+u.length)}}}else{if(t&&n.sliceDoc(a-2*e.length,a)==e+e&&(c=uu(n,a-2*e.length,s))>-1&&fu(n,c))return{changes:{insert:e+e+e+e,from:a},effects:ei.of(a+e.length),range:b.cursor(a+e.length)};if(n.charCategorizer(a)(h)!=q.Word&&uu(n,a,s)>-1&&!k0(n,a,e,s))return{changes:{insert:e+e,from:a},effects:ei.of(a+e.length),range:b.cursor(a+e.length)}}return{range:r=l}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function fu(n,e){let t=ee(n).resolveInner(e+1);return t.parent&&t.from==e}function k0(n,e,t,i){let s=ee(n).resolveInner(e,-1),r=i.reduce((o,l)=>Math.max(o,l.length),0);for(let o=0;o<5;o++){let l=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),a=l.indexOf(t);if(!a||a>-1&&i.indexOf(l.slice(0,a))>-1){let c=s.firstChild;for(;c&&c.from==s.from&&c.to-c.from>t.length+a;){if(n.sliceDoc(c.to-t.length,c.to)==t)return!1;c=c.firstChild}return!0}let h=s.to==e&&s.parent;if(!h)break;s=h}return!1}function uu(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=q.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=q.Word)return r}return-1}function Qu(n={}){return[s0,Qe,re.of(n),i0,Q0,mu]}var Oa=[{key:"Ctrl-Space",run:Hl},{mac:"Alt-`",run:Hl},{mac:"Alt-i",run:Hl},{key:"Escape",run:Jg},{key:"ArrowDown",run:Hs(!0)},{key:"ArrowUp",run:Hs(!1)},{key:"PageDown",run:Hs(!0,"page")},{key:"PageUp",run:Hs(!1,"page")},{key:"Enter",run:Kg}],Q0=Se.highest(Qt.computeN([re],n=>n.facet(re).defaultKeymap?[Oa]:[]));var Tu=[be("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),be("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),be("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),be("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),be("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),be(`try { \${} } catch (\${error}) { \${} -}`,{label:"try",detail:"/ catch block",type:"keyword"}),ye("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),ye(`if (\${}) { +}`,{label:"try",detail:"/ catch block",type:"keyword"}),be("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),be(`if (\${}) { \${} } else { \${} -}`,{label:"if",detail:"/ else block",type:"keyword"}),ye(`class \${name} { +}`,{label:"if",detail:"/ else block",type:"keyword"}),be(`class \${name} { constructor(\${params}) { \${} } -}`,{label:"class",detail:"definition",type:"keyword"}),ye('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),ye('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],Q0=Pu.concat([ye("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),ye("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),ye("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Qu=new As,Tu=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function vn(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}var v0=["FunctionDeclaration"],$0={FunctionDeclaration:vn("function"),ClassDeclaration:vn("class"),ClassExpression:()=>!0,EnumDeclaration:vn("constant"),TypeAliasDeclaration:vn("type"),NamespaceDeclaration:vn("namespace"),VariableDefinition(n,e){n.matchContext(v0)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function Cu(n,e){let t=Qu.get(e);if(t)return t;let i=[],s=!0;function r(o,l){let a=n.sliceString(o.from,o.to);i.push({label:a,type:l})}return e.cursor(U.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let l=$0[o.name];if(l&&l(o,r)||Tu.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of Cu(n,o.node))i.push(l);return!1}}),Qu.set(e,i),i}var vu=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Zu=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function P0(n){let e=ee(n.state).resolveInner(n.pos,-1);if(Zu.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&vu.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)Tu.has(s.name)&&(i=i.concat(Cu(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:vu}}var ii=zs.define({name:"javascript",parser:Tf.configure({props:[jl.add({IfStatement:js({except:/^\s*({|else\b)/}),TryStatement:js({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:_f,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:Bf({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":js({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),Nl.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":Yf,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Au={test:n=>/^JSX/.test(n.name),facet:ql({commentTokens:{block:{open:"{/*",close:"*/}"}}})},T0=ii.configure({dialect:"ts"},"typescript"),C0=ii.configure({dialect:"jsx",props:[Vs.add(n=>n.isTop?[Au]:void 0)]}),Z0=ii.configure({dialect:"jsx ts",props:[Vs.add(n=>n.isTop?[Au]:void 0)]},"typescript"),Mu=n=>({label:n,type:"keyword"}),Ru="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Mu),A0=Ru.concat(["declare","implements","private","protected","public"].map(Mu));function Xu(n={}){let e=n.jsx?n.typescript?Z0:C0:n.typescript?T0:ii,t=n.typescript?Q0.concat(A0):Pu.concat(Ru);return new _s(e,[ii.data.of({autocomplete:uu(Zu,la(t))}),ii.data.of({autocomplete:P0}),n.jsx?X0:[]])}function M0(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function $u(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}var R0=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),X0=v.inputHandler.of((n,e,t,i,s)=>{if((R0?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!ii.isActiveAt(n.state,e,-1))return!1;let r=s(),{state:o}=r,l=o.changeByRange(a=>{var h;let{head:c}=a,f=ee(o).resolveInner(c-1,-1),u;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(c-1,c)!=i||f.name=="JSXAttributeValue"&&f.to>c)){if(i==">"&&f.name=="JSXFragmentTag")return{range:a,changes:{from:c,insert:""}};if(i=="/"&&f.name=="JSXStartCloseTag"){let d=f.parent,p=d.parent;if(p&&d.from==c-2&&((u=$u(o.doc,p.firstChild,c))||((h=p.firstChild)===null||h===void 0?void 0:h.name)=="JSXFragmentTag")){let O=`${u}>`;return{range:b.cursor(c+O.length,-1),changes:{from:c,insert:O}}}}else if(i==">"){let d=M0(f);if(d&&d.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(c,c+2))&&(u=$u(o.doc,d,c)))return{range:a,changes:{from:c,insert:``}}}}return{range:a}});return l.changes.empty?!1:(n.dispatch([r,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});var L0=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=Sa(n.state,t.from);return i.line?E0(n):i.block?W0(n):!1};function xa(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}var E0=xa(_0,0);var D0=xa(Yu,0);var W0=xa((n,e)=>Yu(n,e,z0(e)),0);function Sa(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}var $n=50;function B0(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-$n,i),o=n.sliceDoc(s,s+$n),l=/\s*$/.exec(r)[0].length,a=/^\s*/.exec(o)[0].length,h=r.length-l;if(r.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:s+a,margin:a&&1}};let c,f;s-i<=2*$n?c=f=n.sliceDoc(i,s):(c=n.sliceDoc(i,i+$n),f=n.sliceDoc(s-$n,s));let u=/^\s*/.exec(c)[0].length,d=/\s*$/.exec(f)[0].length,p=f.length-d-t.length;return c.slice(u,u+e.length)==e&&f.slice(p,p+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(c.charAt(u+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(f.charAt(p-1))?1:0}}:null}function z0(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function Yu(n,e,t=e.selection.ranges){let i=t.map(r=>Sa(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>B0(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,l;os&&(r==o||o>f.from)){s=f.from;let u=/^\s*/.exec(f.text)[0].length,d=u==f.length,p=f.text.slice(u,u+h.length)==h?u:-1;ur.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:l,token:a,indent:h,empty:c,single:f}of i)(f||!c)&&r.push({from:l.from+h,insert:a+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,c=h+a.length;o.text[c-o.from]==" "&&c++,r.push({from:h,to:c})}return{changes:r}}return null}var ma=be.define(),I0=be.define(),Y0=$.define(),Vu=$.define({combine(n){return fe(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),qu=K.define({create(){return ni.empty},update(n,e){let t=e.state.facet(Vu),i=e.annotation(ma);if(i){let a=He.fromTransaction(e,i.selection),h=i.side,c=h==0?n.undone:n.done;return a?c=ir(c,c.length,t.minDepth,a):c=Uu(c,e.startState.selection),new ni(h==0?i.rest:c,h==0?c:i.rest)}let s=e.annotation(I0);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(ie.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=He.fromTransaction(e),o=e.annotation(ie.time),l=e.annotation(ie.userEvent);return r?n=n.addChanges(r,o,l,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new ni(n.done.map(He.fromJSON),n.undone.map(He.fromJSON))}});function ju(n={}){return[qu,Vu.of(n),v.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?Nu:e.inputType=="historyRedo"?ga:null;return i?(e.preventDefault(),i(t)):!1}})]}function nr(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(qu,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}var Nu=nr(0,!1),ga=nr(1,!1),V0=nr(0,!0),q0=nr(1,!0);var He=class n{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new n(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;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:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new n(e.changes&&Oe.fromJSON(e.changes),[],e.mapped&&ht.fromJSON(e.mapped),e.startSelection&&b.fromJSON(e.startSelection),e.selectionsAfter.map(b.fromJSON))}static fromTransaction(e,t){let i=Ve;for(let s of e.startState.facet(Y0)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new n(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,Ve)}static selection(e){return new n(void 0,Ve,void 0,void 0,e)}};function ir(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function j0(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,l)=>{for(let a=0;a=h&&o<=c&&(i=!0)}}),i}function N0(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function Gu(n,e){return n.length?e.length?n.concat(e):n:e}var Ve=[],G0=200;function Uu(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-G0));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),ir(n,n.length-1,1e9,t.setSelAfter(i)))}else return[He.selection([e])]}function U0(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function Oa(n,e){if(!n.length)return n;let t=n.length,i=Ve;for(;t;){let s=F0(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[He.selection(i)]:Ve}function F0(n,e,t){let i=Gu(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):Ve,t);if(!n.changes)return He.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new He(s,A.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}var H0=/^(input\.type|delete)($|\.)/,ni=class n{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new n(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||H0.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):sr(t,e))}function de(n){return n.textDirectionAt(n.state.selection.main.head)==_.LTR}var Ku=n=>Hu(n,!de(n)),Ju=n=>Hu(n,de(n));function ed(n,e){return Je(n,t=>t.empty?n.moveByGroup(t,e):sr(t,e))}var K0=n=>ed(n,!de(n)),J0=n=>ed(n,de(n));var Vb=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function e1(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function rr(n,e,t){let i=ee(n).resolveInner(e.head),s=t?R.closedBy:R.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;e1(n,h,s)?i=h:a=t?h.to:h.from}let r=i.type.prop(s),o,l;return r&&(o=t?Fe(n,i.from,1):Fe(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,b.cursor(l,t?-1:1)}var t1=n=>Je(n,e=>rr(n.state,e,!de(n))),i1=n=>Je(n,e=>rr(n.state,e,de(n)));function td(n,e){return Je(n,t=>{if(!t.empty)return sr(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}var id=n=>td(n,!1),nd=n=>td(n,!0);function sd(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):sr(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),l=n.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,h=l.bottom-t.marginBottom;o&&o.top>a&&o.bottomrd(n,!1),ya=n=>rd(n,!0);function At(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=b.cursor(i.from+r))}return s}var n1=n=>Je(n,e=>At(n,e,!0)),s1=n=>Je(n,e=>At(n,e,!1)),r1=n=>Je(n,e=>At(n,e,!de(n))),o1=n=>Je(n,e=>At(n,e,de(n))),l1=n=>Je(n,e=>b.cursor(n.lineBlockAt(e.head).from,1)),a1=n=>Je(n,e=>b.cursor(n.lineBlockAt(e.head).to,-1));function h1(n,e,t){let i=!1,s=Xi(n.selection,r=>{let o=Fe(n,r.head,-1)||Fe(n,r.head,1)||r.head>0&&Fe(n,r.head-1,1)||r.headh1(n,e,!1);function qe(n,e){let t=Xi(n.state.selection,i=>{let s=e(i);return b.range(i.anchor,s.head,s.goalColumn,s.bidiLevel||void 0,s.assoc)});return t.eq(n.state.selection)?!1:(n.dispatch(Ke(n.state,t)),!0)}function od(n,e){return qe(n,t=>n.moveByChar(t,e))}var ld=n=>od(n,!de(n)),ad=n=>od(n,de(n));function hd(n,e){return qe(n,t=>n.moveByGroup(t,e))}var f1=n=>hd(n,!de(n)),u1=n=>hd(n,de(n));var d1=n=>qe(n,e=>rr(n.state,e,!de(n))),p1=n=>qe(n,e=>rr(n.state,e,de(n)));function cd(n,e){return qe(n,t=>n.moveVertically(t,e))}var fd=n=>cd(n,!1),ud=n=>cd(n,!0);function dd(n,e){return qe(n,t=>n.moveVertically(t,e,sd(n).height))}var Eu=n=>dd(n,!1),Du=n=>dd(n,!0),O1=n=>qe(n,e=>At(n,e,!0)),m1=n=>qe(n,e=>At(n,e,!1)),g1=n=>qe(n,e=>At(n,e,!de(n))),y1=n=>qe(n,e=>At(n,e,de(n))),b1=n=>qe(n,e=>b.cursor(n.lineBlockAt(e.head).from)),x1=n=>qe(n,e=>b.cursor(n.lineBlockAt(e.head).to)),Wu=({state:n,dispatch:e})=>(e(Ke(n,{anchor:0})),!0),Bu=({state:n,dispatch:e})=>(e(Ke(n,{anchor:n.doc.length})),!0),zu=({state:n,dispatch:e})=>(e(Ke(n,{anchor:n.selection.main.anchor,head:0})),!0),_u=({state:n,dispatch:e})=>(e(Ke(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),S1=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),w1=({state:n,dispatch:e})=>{let t=or(n).map(({from:i,to:s})=>b.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:b.create(t),userEvent:"select"})),!0},k1=({state:n,dispatch:e})=>{let t=Xi(n.selection,i=>{let s=ee(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:l}=o;if((l.from=i.to||l.to>i.to&&l.from<=i.from)&&o.next)return b.range(l.to,l.from)}return i});return t.eq(n.selection)?!1:(e(Ke(n,t)),!0)};function pd(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let l=r;;){let a=n.moveVertically(l,e);if(a.heado.to){s.some(h=>h.head==a.head)||s.push(a);break}else{if(a.head==l.head)break;l=a}}}return s.length==i.ranges.length?!1:(n.dispatch(Ke(t,b.create(s,s.length-1))),!0)}var Q1=n=>pd(n,!1),v1=n=>pd(n,!0),$1=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=b.create([t.main]):t.main.empty||(i=b.create([b.cursor(t.main.head)])),i?(e(Ke(n,i)),!0):!1};function Pn(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:l}=r;if(o==l){let a=e(r);ao&&(t="delete.forward",a=tr(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=tr(n,o,!1),l=tr(n,l,!0);return o==l?{range:r}:{changes:{from:o,to:l},range:b.cursor(o,os(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}var Od=(n,e,t)=>Pn(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),l,a;if(t&&!e&&s>o.from&&sOd(n,!1,!0);var md=n=>Od(n,!0,!1),gd=(n,e)=>Pn(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let l=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let a=te(r.text,i-r.from,e)+r.from,h=r.text.slice(Math.min(i,a)-r.from,Math.max(i,a)-r.from),c=o(h);if(l!=null&&c!=l)break;(h!=" "||i!=t.head)&&(l=c),i=a}return i}),yd=n=>gd(n,!1),P1=n=>gd(n,!0);var T1=n=>Pn(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headPn(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),Z1=n=>Pn(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:E.of(["",""])},range:b.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},M1=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:te(r.text,s-r.from,!1)+r.from,l=s==r.to?s+1:te(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:l,insert:n.doc.slice(s,l).append(n.doc.slice(o,s))},range:b.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function or(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function bd(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of or(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),l=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let a of r.ranges)s.push(b.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let a of r.ranges)s.push(b.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:b.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}var R1=({state:n,dispatch:e})=>bd(n,e,!1),X1=({state:n,dispatch:e})=>bd(n,e,!0);function xd(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of or(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}var L1=({state:n,dispatch:e})=>xd(n,e,!1),E1=({state:n,dispatch:e})=>xd(n,e,!0),D1=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(or(e).map(({from:s,to:r})=>(s>0?s--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),l=n.coordsAtPos(s.head,s.assoc||1);l&&(r=o.bottom+n.documentTop-l.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function W1(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=ee(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(R.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}var Iu=Sd(!1),B1=Sd(!0);function Sd(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,l=e.doc.lineAt(r),a=!n&&r==o&&W1(e,r);n&&(r=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new Kt(e,{simulateBreak:r,simulateDoubleBreak:!!a}),c=qs(h,r);for(c==null&&(c=ct(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));ol.from&&r{let s=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,s,i),t=l.number),o=l.to+1}let r=n.changes(s);return{changes:s,range:b.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}var z1=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Kt(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=wa(n,(r,o,l)=>{let a=qs(i,r.from);if(a==null)return;/\S/.test(r.text)||(a=0);let h=/^\s*/.exec(r.text)[0],c=Mi(n,a);(h!=c||l.fromn.readOnly?!1:(e(n.update(wa(n,(t,i)=>{i.push({from:t.from,insert:n.facet(Ai)})}),{userEvent:"input.indent"})),!0),I1=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(wa(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=ct(s,n.tabSize),o=0,l=Mi(n,Math.max(0,r-bn(n)));for(;o(n.setTabFocusMode(),!0);var V1=[{key:"Ctrl-b",run:Ku,shift:ld,preventDefault:!0},{key:"Ctrl-f",run:Ju,shift:ad},{key:"Ctrl-p",run:id,shift:fd},{key:"Ctrl-n",run:nd,shift:ud},{key:"Ctrl-a",run:l1,shift:b1},{key:"Ctrl-e",run:a1,shift:x1},{key:"Ctrl-d",run:md},{key:"Ctrl-h",run:ba},{key:"Ctrl-k",run:T1},{key:"Ctrl-Alt-h",run:yd},{key:"Ctrl-o",run:A1},{key:"Ctrl-t",run:M1},{key:"Ctrl-v",run:ya}],q1=[{key:"ArrowLeft",run:Ku,shift:ld,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:K0,shift:f1,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:r1,shift:g1,preventDefault:!0},{key:"ArrowRight",run:Ju,shift:ad,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:J0,shift:u1,preventDefault:!0},{mac:"Cmd-ArrowRight",run:o1,shift:y1,preventDefault:!0},{key:"ArrowUp",run:id,shift:fd,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Wu,shift:zu},{mac:"Ctrl-ArrowUp",run:Lu,shift:Eu},{key:"ArrowDown",run:nd,shift:ud,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Bu,shift:_u},{mac:"Ctrl-ArrowDown",run:ya,shift:Du},{key:"PageUp",run:Lu,shift:Eu},{key:"PageDown",run:ya,shift:Du},{key:"Home",run:s1,shift:m1,preventDefault:!0},{key:"Mod-Home",run:Wu,shift:zu},{key:"End",run:n1,shift:O1,preventDefault:!0},{key:"Mod-End",run:Bu,shift:_u},{key:"Enter",run:Iu,shift:Iu},{key:"Mod-a",run:S1},{key:"Backspace",run:ba,shift:ba,preventDefault:!0},{key:"Delete",run:md,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:yd,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:P1,preventDefault:!0},{mac:"Mod-Backspace",run:C1,preventDefault:!0},{mac:"Mod-Delete",run:Z1,preventDefault:!0}].concat(V1.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),wd=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:t1,shift:d1},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:i1,shift:p1},{key:"Alt-ArrowUp",run:R1},{key:"Shift-Alt-ArrowUp",run:L1},{key:"Alt-ArrowDown",run:X1},{key:"Shift-Alt-ArrowDown",run:E1},{key:"Mod-Alt-ArrowUp",run:Q1},{key:"Mod-Alt-ArrowDown",run:v1},{key:"Escape",run:$1},{key:"Mod-Enter",run:B1},{key:"Alt-l",mac:"Ctrl-l",run:w1},{key:"Mod-i",run:k1,preventDefault:!0},{key:"Mod-[",run:I1},{key:"Mod-]",run:_1},{key:"Mod-Alt-\\",run:z1},{key:"Shift-Mod-k",run:D1},{key:"Shift-Mod-\\",run:c1},{key:"Mod-/",run:L0},{key:"Alt-A",run:D0},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Y1}].concat(q1);var kd=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n,Rt=class{constructor(e,t,i=0,s=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=r?l=>r(kd(l)):kd,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 le(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=Yi(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=Pe(e);let s=this.normalize(t);if(s.length)for(let r=0,o=i,l=!0;;r++){let a=s.charCodeAt(r),h=this.match(a,o,l,this.bufferPos+this.bufferStart,r==s.length-1);if(h)return this.value=h,this;if(r==s.length-1)break;l&&rthis.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 i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=ur(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(ithis.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=i||s.to<=t){let l=new n(t,e.sliceString(t,i));return ka.set(e,l),l}if(s.from==t&&s.to==i)return s;let{text:r,from:o}=s;return o>t&&(r=e.sliceString(t,o)+r,o=t),s.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 i=this.flat.from+t.index,s=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this.matchPos=ur(this.text,s+(i==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=cr.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<"u"&&(hr.prototype[Symbol.iterator]=fr.prototype[Symbol.iterator]=function(){return this});function j1(n){try{return new RegExp(n,Ta),!0}catch{return!1}}function ur(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e=56320&&i<57344;)e++;return e}var N1=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:i,result:s}=rf(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return s.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:i});return}let l=e.doc.lineAt(e.selection.main.head),[,a,h,c,f]=o,u=c?+c.slice(1):0,d=h?+h:l.number;if(h&&f){let g=d/100;a&&(g=g*(a=="-"?-1:1)+l.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else h&&a&&(d=d*(a=="-"?-1:1)+l.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),O=b.cursor(p.from+Math.max(0,Math.min(u,p.length)));n.dispatch({effects:[i,v.scrollIntoView(O.from,{y:"center"})],selection:O})}),!0},G1={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Pd=$.define({combine(n){return fe(n,G1,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function Td(n){let e=[J1,K1];return n&&e.push(Pd.of(n)),e}var U1=Z.mark({class:"cm-selectionMatch"}),F1=Z.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function Qd(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=V.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=V.Word)}function H1(n,e,t,i){return n(e.sliceDoc(t,t+1))==V.Word&&n(e.sliceDoc(i-1,i))==V.Word}var K1=H.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(Pd),{state:t}=n,i=t.selection;if(i.ranges.length>1)return Z.none;let s=i.main,r,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return Z.none;let a=t.wordAt(s.head);if(!a)return Z.none;o=t.charCategorizer(s.head),r=t.sliceDoc(a.from,a.to)}else{let a=s.to-s.from;if(a200)return Z.none;if(e.wholeWords){if(r=t.sliceDoc(s.from,s.to),o=t.charCategorizer(s.head),!(Qd(o,t,s.from,s.to)&&H1(o,t,s.from,s.to)))return Z.none}else if(r=t.sliceDoc(s.from,s.to),!r)return Z.none}let l=[];for(let a of n.visibleRanges){let h=new Rt(t.doc,r,a.from,a.to);for(;!h.next().done;){let{from:c,to:f}=h.value;if((!o||Qd(o,t,c,f))&&(s.empty&&c<=s.from&&f>=s.to?l.push(F1.range(c,f)):(c>=s.to||f<=s.from)&&l.push(U1.range(c,f)),l.length>e.maxMatches))return Z.none}}return Z.set(l)}},{decorations:n=>n.decorations}),J1=v.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),ey=({state:n,dispatch:e})=>{let{selection:t}=n,i=b.create(t.ranges.map(s=>n.wordAt(s.head)||b.cursor(s.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function ty(n,e){let{main:t,ranges:i}=n.selection,s=n.wordAt(t.head),r=s&&s.from==t.from&&s.to==t.to;for(let o=!1,l=new Rt(n.doc,e,i[i.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new Rt(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(a=>a.from==l.value.from))continue;if(r){let a=n.wordAt(l.value.from);if(!a||a.from!=l.value.from||a.to!=l.value.to)continue}return l.value}}var iy=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return ey({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=i))return!1;let s=ty(n,i);return s?(e(n.update({selection:n.selection.addRange(b.range(s.from,s.to),!1),effects:v.scrollIntoView(s.to)})),!0):!1},Di=$.define({combine(n){return fe(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Pa(e),scrollToMatch:e=>v.scrollIntoView(e)})}});var dr=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||j1(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` -`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new va(this):new Qa(this)}getCursor(e,t=0,i){let s=e.doc?e:Y.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?Ei(this,s,t,i):Li(this,s,t,i)}},pr=class{constructor(e){this.spec=e}};function ny(n,e,t){return(i,s,r,o)=>{if(t&&!t(i,s,r,o))return!1;let l=i>=o&&s<=o+r.length?r.slice(i-o,s-o):e.doc.sliceString(i,s);return n(l,e,i,s)}}function Li(n,e,t,i){let s;return n.wholeWord&&(s=sy(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(s=ny(n.test,e,s)),new Rt(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),s)}function sy(n,e){return(t,i,s,r)=>((r>t||r+s.length=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Li(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}};function ry(n,e,t){return(i,s,r)=>(!t||t(i,s,r))&&n(r[0],e,i,s)}function Ei(n,e,t,i){let s;return n.wholeWord&&(s=oy(e.charCategorizer(e.selection.main.head))),n.test&&(s=ry(n.test,e,s)),new hr(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:s},t,i)}function Or(n,e){return n.slice(te(n,e,!1),e)}function mr(n,e){return n.slice(e,te(n,e))}function oy(n){return(e,t,i)=>!i[0].length||(n(Or(i.input,i.index))!=V.Word||n(mr(i.input,i.index))!=V.Word)&&(n(mr(i.input,i.index+i[0].length))!=V.Word||n(Or(i.input,i.index+i[0].length))!=V.Word)}var va=class extends pr{nextMatch(e,t,i){let s=Ei(this.spec,e,i,e.doc.length).next();return s.done&&(s=Ei(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=Ei(this.spec,e,r,i),l=null;for(;!o.next().done;)l=o.value;if(l&&(r==t||l.from>r+10))return l;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Ei(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}},Cn=A.define(),Ca=A.define(),Mt=K.define({create(n){return new Tn($a(n).create(),null)},update(n,e){for(let t of e.effects)t.is(Cn)?n=new Tn(t.value.create(),n.panel):t.is(Ca)&&(n=new Tn(n.query,t.value?Za:null));return n},provide:n=>jt.from(n,e=>e.panel)});var Tn=class{constructor(e,t){this.query=e,this.panel=t}},ly=Z.mark({class:"cm-searchMatch"}),ay=Z.mark({class:"cm-searchMatch cm-searchMatch-selected"}),hy=H.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(Mt))}update(n){let e=n.state.field(Mt);(e!=n.startState.field(Mt)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return Z.none;let{view:t}=this,i=new $e;for(let s=0,r=t.visibleRanges,o=r.length;sr[s+1].from-500;)a=r[++s].to;n.highlight(t.state,l,a,(h,c)=>{let f=t.state.selection.ranges.some(u=>u.from==h&&u.to==c);i.add(h,c,f?ay:ly)})}return i.finish()}},{decorations:n=>n.decorations});function Zn(n){return e=>{let t=e.state.field(Mt,!1);return t&&t.query.spec.valid?n(e,t):Ad(e)}}var gr=Zn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=b.single(i.from,i.to),r=n.state.facet(Di);return n.dispatch({selection:s,effects:[Aa(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),Zd(n),!0}),yr=Zn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=b.single(s.from,s.to),o=n.state.facet(Di);return n.dispatch({selection:r,effects:[Aa(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),Zd(n),!0}),cy=Zn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:b.create(t.map(i=>b.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),fy=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:s}=t.main,r=[],o=0;for(let l=new Rt(n.doc,n.sliceDoc(i,s));!l.next().done;){if(r.length>1e3)return!1;l.value.from==i&&(o=r.length),r.push(b.range(l.value.from,l.value.to))}return e(n.update({selection:b.create(r,o),userEvent:"select.search.matches"})),!0},vd=Zn((n,{query:e})=>{let{state:t}=n,{from:i,to:s}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,l=[],a,h,c=[];o.precise?o.from==i&&o.to==s&&(h=t.toText(e.getReplacement(o)),l.push({from:o.from,to:o.to,insert:h}),c.push(v.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let f=n.state.changes(l);return o&&(a=b.single(o.from,o.to).map(f),c.push(Aa(n,o)),c.push(t.facet(Di).scrollToMatch(a.main,n))),n.dispatch({changes:f,selection:a,effects:c,userEvent:"input.replace"}),!0}),uy=Zn((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let s of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:l}=s;l&&t.push({from:r,to:o,insert:e.getReplacement(s)})}if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:v.announce.of(i),userEvent:"input.replace.all"}),!0});function Za(n){return n.state.facet(Di).createPanel(n)}function $a(n,e){var t,i,s,r,o;let l=n.selection.main,a=l.empty||l.to>l.from+100?"":n.sliceDoc(l.from,l.to);if(e&&!a)return e;let h=n.facet(Di);return new dr({search:((t=e?.literal)!==null&&t!==void 0?t:h.literal)?a:a.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:h.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:h.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:h.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:h.wholeWord})}function Cd(n){let e=hn(n,Za);return e&&e.dom.querySelector("[main-field]")}function Zd(n){let e=Cd(n);e&&e==n.root.activeElement&&e.select()}var Ad=n=>{let e=n.state.field(Mt,!1);if(e&&e.panel){let t=Cd(n);if(t&&t!=n.root.activeElement){let i=$a(n.state,e.query.spec);i.valid&&n.dispatch({effects:Cn.of(i)}),t.focus(),t.select()}}else n.dispatch({effects:[Ca.of(!0),e?Cn.of($a(n.state,e.query.spec)):A.appendConfig.of(py)]});return!0},Md=n=>{let e=n.state.field(Mt,!1);if(!e||!e.panel)return!1;let t=hn(n,Za);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Ca.of(!1)}),!0},Rd=[{key:"Mod-f",run:Ad,scope:"editor search-panel"},{key:"F3",run:gr,shift:yr,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:gr,shift:yr,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Md,scope:"editor search-panel"},{key:"Mod-Shift-l",run:fy},{key:"Mod-Alt-g",run:N1},{key:"Mod-d",run:iy,preventDefault:!0}],Pa=class{constructor(e){this.view=e;let t=this.query=e.state.field(Mt).query.spec;this.commit=this.commit.bind(this),this.searchField=B("input",{value:t.search,placeholder:Me(e,"Find"),"aria-label":Me(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=B("input",{value:t.replace,placeholder:Me(e,"Replace"),"aria-label":Me(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=B("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=B("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=B("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(s,r,o){return B("button",{class:"cm-button",name:s,onclick:r,type:"button"},o)}this.dom=B("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,i("next",()=>gr(e),[Me(e,"next")]),i("prev",()=>yr(e),[Me(e,"previous")]),i("select",()=>cy(e),[Me(e,"all")]),B("label",null,[this.caseField,Me(e,"match case")]),B("label",null,[this.reField,Me(e,"regexp")]),B("label",null,[this.wordField,Me(e,"by word")]),...e.state.readOnly?[]:[B("br"),this.replaceField,i("replace",()=>vd(e),[Me(e,"replace")]),i("replaceAll",()=>uy(e),[Me(e,"replace all")])],B("button",{name:"close",onclick:()=>Md(e),"aria-label":Me(e,"close"),type:"button"},["\xD7"])])}commit(){let e=new dr({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:Cn.of(e)}))}keydown(e){Vc(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?yr:gr)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),vd(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(Cn)&&!i.value.eq(this.query)&&this.setQuery(i.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(Di).top}};function Me(n,e){return n.state.phrase(e)}var lr=30,ar=/[\s\.,:;?!]/;function Aa(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),s=n.state.doc.lineAt(t).to,r=Math.max(i.from,e-lr),o=Math.min(s,t+lr),l=n.state.sliceDoc(r,o);if(r!=i.from){for(let a=0;al.length-lr;a--)if(!ar.test(l[a-1])&&ar.test(l[a])){l=l.slice(0,a);break}}return v.announce.of(`${n.state.phrase("current match")}. ${l} ${n.state.phrase("on line")} ${i.number}.`)}var dy=v.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"}}),py=[Mt,xe.low(hy),dy];var xr=class{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}},si=class n{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let s=i.facet(An).markerFilter;s&&(e=s(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new $e,l=[],a=0,h=i.doc.iter(),c=0,f=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!l.length)break;let O,g;if(l.length)O=a,g=l.reduce((S,C)=>Math.min(S,C.to),p&&p.from>O?p.from:1e8);else{if(O=p.from,O>f)break;g=p.to,l.push(p),d++}for(;dS.from||S.to==O))l.push(S),d++,g=Math.min(S.to,g);else{g=Math.min(S.from,g);break}}g=Math.min(g,f);let y=!1;if(l.some(S=>S.from==O&&(S.to==g||g==f))&&(y=O==g,!y&&g-O<10)){let S=O-(c+h.value.length);S>0&&(h.next(S),c=O);for(let C=O;;){if(C>=g){y=!0;break}if(!h.lineBreak&&c+h.value.length>C)break;C=c+h.value.length,c+=h.value.length,h.next()}}let x=vy(l);if(y)o.add(O,O,Z.widget({widget:new Ma(x),diagnostics:l.slice()}));else{let S=l.reduce((C,w)=>w.markClass?C+" "+w.markClass:C,"");o.add(O,g,Z.mark({class:"cm-lintRange cm-lintRange-"+x+S,diagnostics:l.slice(),inclusiveEnd:l.some(C=>C.to>g)}))}if(a=g,a==f)break;for(let S=0;S{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new xr(s,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new xr(i.from,r,i.diagnostic)}}),i}function Oy(n,e){let t=e.pos,i=e.end||t,s=n.state.facet(An).hideOn(n,t,i);if(s!=null)return s;let r=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(Ed))||n.changes.touchesRange(r.from,Math.max(r.to,i)))}function my(n,e){return n.field(Re,!1)?e:e.concat(A.appendConfig.of($y))}var Ed=A.define(),Ra=A.define(),Dd=A.define(),Re=K.define({create(){return new si(Z.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),i=null,s=n.panel;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=Xt(t,n.selected.diagnostic,r)||Xt(t,null,r)}!t.size&&s&&e.state.facet(An).autoPanel&&(s=null),n=new si(t,s,i)}for(let t of e.effects)if(t.is(Ed)){let i=e.state.facet(An).autoPanel?t.value.length?Mn.open:null:n.panel;n=si.init(t.value,i,e.state)}else t.is(Ra)?n=new si(n.diagnostics,t.value?Mn.open:null,n.selected):t.is(Dd)&&(n=new si(n.diagnostics,n.panel,t.value));return n},provide:n=>[jt.from(n,e=>e.panel),v.decorations.from(n,e=>e.diagnostics)]});var gy=Z.mark({class:"cm-lintRange cm-lintRange-active"});function yy(n,e,t){let{diagnostics:i}=n.state.field(Re),s,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(a,h,{spec:c})=>{if(e>=a&&e<=h&&(a==h||(e>a||t>0)&&(ezd(n,t,!1)))}var xy=n=>{let e=n.state.field(Re,!1);(!e||!e.panel)&&n.dispatch({effects:my(n.state,[Ra.of(!0)])});let t=hn(n,Mn.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},Xd=n=>{let e=n.state.field(Re,!1);return!e||!e.panel?!1:(n.dispatch({effects:Ra.of(!1)}),!0)},Sy=n=>{let e=n.state.field(Re,!1);if(!e)return!1;let t=n.state.selection.main,i=Xt(e.diagnostics,null,t.to+1);return!i&&(i=Xt(e.diagnostics,null,0),!i||i.from==t.from&&i.to==t.to)?!1:(n.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0}),!0)};var Wd=[{key:"Mod-Shift-m",run:xy,preventDefault:!0},{key:"F8",run:Sy}];var An=$.define({combine(n){return{sources:n.map(e=>e.source).filter(e=>e!=null),...fe(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:Ld,tooltipFilter:Ld,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,s,r)=>e(i,s,r)||t(i,s,r):e:t,autoPanel:(e,t)=>e||t})}}});function Ld(n,e){return n?e?(t,i)=>e(n(t,i),i):n:e}function Bd(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;ir.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function zd(n,e,t){var i;let s=t?Bd(e.actions):[];return B("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},B("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let l=!1,a=d=>{if(d.preventDefault(),l)return;l=!0;let p=Xt(n.state.field(Re).diagnostics,e);p&&r.apply(n,p.from,p.to)},{name:h}=r,c=s[o]?h.indexOf(s[o]):-1,f=c<0?h:[h.slice(0,c),B("u",h.slice(c,c+1)),h.slice(c+1)],u=r.markClass?" "+r.markClass:"";return B("button",{type:"button",class:"cm-diagnosticAction"+u,onclick:a,onmousedown:a,"aria-label":` Action: ${h}${c<0?"":` (access key "${s[o]})"`}.`},f)}),e.source&&B("div",{class:"cm-diagnosticSource"},e.source))}var Ma=class extends ge{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return B("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}},Sr=class{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=zd(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}},Mn=class n{constructor(e){this.view=e,this.items=[];let t=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)Xd(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=Bd(r.actions);for(let l=0;l{for(let r=0;rXd(this.view)},"\xD7")),this.update()}get selectedIndex(){let e=this.view.state.field(Re).selected;if(!e)return-1;for(let t=0;t{for(let c of h.diagnostics){if(o.has(c))continue;o.add(c);let f=-1,u;for(let d=i;di&&(this.items.splice(i,f-i),s=!0)),t&&u.diagnostic==t.diagnostic?u.dom.hasAttribute("aria-selected")||(u.dom.setAttribute("aria-selected","true"),r=u):u.dom.hasAttribute("aria-selected")&&u.dom.removeAttribute("aria-selected"),i++}});i({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:a})=>{let h=a.height/this.list.offsetHeight;l.topa.bottom&&(this.list.scrollTop+=(l.bottom-a.bottom)/h)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(Re),i=Xt(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:Dd.of(i)})}static open(e){return new n(e)}};function wy(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function br(n){return wy(``,'width="6" height="3"')}var ky=v.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:br("#d11")},".cm-lintRange-warning":{backgroundImage:br("orange")},".cm-lintRange-info":{backgroundImage:br("#999")},".cm-lintRange-hint":{backgroundImage:br("#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}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function Qy(n){return n=="error"?4:n=="warning"?3:n=="info"?2:1}function vy(n){let e="hint",t=1;for(let i of n){let s=Qy(i.severity);s>t&&(t=s,e=i.severity)}return e}var $y=[Re,v.decorations.compute([Re],n=>{let{selected:e,panel:t}=n.field(Re);return!e||!t||e.from==e.to?Z.none:Z.set([gy.range(e.from,e.to)])}),nf(yy,{hideOn:Oy}),ky];var _d=[hf(),cf(),Kc(),ju(),Hf(),Gc(),Hc(),Y.allowMultipleSelections.of(!0),If(),Gs(Jf,{fallback:!0}),nu(),yu(),ku(),ef(),tf(),Jc(),Td(),Qt.of([...Su,...wd,...Rd,...Fu,...Gf,...pa,...Wd])];var wr="#FAFAF7",yt="#0A0A0A",gt="#E63946",Xa="rgba(10, 10, 10, 0.12)",qd="rgba(10, 10, 10, 0.55)",Py="rgba(230, 57, 70, 0.18)",Ty=v.theme({"&":{color:yt,backgroundColor:wr,height:"100%"},".cm-content":{caretColor:gt,fontFamily:'ui-monospace, "JetBrains Mono", "IBM Plex Mono", Menlo, Consolas, monospace'},".cm-cursor, .cm-dropCursor":{borderLeftColor:gt},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:Py},".cm-gutters":{backgroundColor:wr,color:qd,borderRight:`1px solid ${Xa}`},".cm-activeLine":{backgroundColor:"rgba(10, 10, 10, 0.03)"},".cm-activeLineGutter":{backgroundColor:"rgba(10, 10, 10, 0.04)",color:yt},".cm-selectionMatch":{backgroundColor:"rgba(230, 57, 70, 0.12)"},".cm-matchingBracket, .cm-nonmatchingBracket":{backgroundColor:"rgba(230, 57, 70, 0.18)",outline:"none"},".cm-tooltip":{backgroundColor:wr,color:yt,border:`1px solid ${Xa}`},".cm-panels":{backgroundColor:wr,color:yt,borderTop:`1px solid ${Xa}`}},{dark:!1}),Cy=Zi.define([{tag:m.keyword,color:gt,fontWeight:"600"},{tag:[m.name,m.deleted,m.character,m.macroName],color:yt},{tag:[m.propertyName],color:yt},{tag:[m.function(m.variableName),m.labelName],color:yt,fontWeight:"600"},{tag:[m.color,m.constant(m.name),m.standard(m.name)],color:gt},{tag:[m.definition(m.name),m.separator],color:yt},{tag:[m.typeName,m.className,m.number,m.changed,m.annotation,m.modifier,m.self,m.namespace],color:gt},{tag:[m.operator,m.operatorKeyword,m.url,m.escape,m.regexp,m.link,m.special(m.string)],color:gt},{tag:[m.meta,m.comment],color:qd,fontStyle:"italic"},{tag:m.strong,fontWeight:"700"},{tag:m.emphasis,fontStyle:"italic"},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.link,color:gt,textDecoration:"underline"},{tag:m.heading,fontWeight:"700",color:yt},{tag:[m.atom,m.bool,m.special(m.variableName)],color:gt},{tag:[m.processingInstruction,m.string,m.inserted],color:"#1f6feb"},{tag:m.invalid,color:gt,textDecoration:"underline"}]),Zy=[Ty,Gs(Cy)],Id="sketch.js",Ay=200,My=5e3,Yd=1;function Ea(n){return`ga.studio.${n}`}function Ry(n){try{let e=localStorage.getItem(Ea(n));return e?JSON.parse(e):null}catch{return null}}function Xy(n,e){try{localStorage.setItem(Ea(n),JSON.stringify(e))}catch{}}function Vd(n){try{localStorage.removeItem(Ea(n))}catch{}}async function kr(n,e){let t=await fetch(n,{credentials:"include",...e});if(!t.ok){let i="";try{i=await t.json()}catch{}let s=typeof i=="object"&&i&&"error"in i?i.error:t.statusText,r=new Error(`${t.status}: ${s}`);throw r.status=t.status,r.detail=i,r}return await t.json()}function Xe(n,e={}){let t=document.getElementById("ga-studio-toast");t&&(t.textContent=n,t.dataset.tone=e.tone||"info",t.dataset.show="1",setTimeout(()=>{t.dataset.show="0"},e.ms??2200))}function et(n,e){let t=document.getElementById("ga-studio-status");t&&(t.dataset.state=n,t.textContent=e??{idle:"Idle",dirty:"Unsaved",saving:"Saving\u2026",saved:"Saved",error:"Error"}[n])}var La=class{constructor(e){De(this,"cfg");De(this,"view",null);De(this,"previewIframe",null);De(this,"previewReady",!1);De(this,"currentSha","");De(this,"originalContent","");De(this,"dirty",!1);De(this,"debounceTimer",null);De(this,"autosaveTimer",null);De(this,"exportRequests",new Map);De(this,"project",null);this.cfg=e}async start(){if(!this.cfg.projectId){Xe("Missing ?project=ID in the URL.",{tone:"error",ms:5e3});return}let e=null;try{e=await kr(`${this.cfg.apiBase}/v1/me`)}catch(r){if(r.status===401){this.cfg.onUnauthenticated?.();return}Xe("Failed to verify your session.",{tone:"error",ms:4e3});return}if(!e){this.cfg.onUnauthenticated?.();return}let t;try{t=await kr(`${this.cfg.apiBase}/v1/projects/${this.cfg.projectId}/file?path=${encodeURIComponent(Id)}`)}catch(r){Xe("Failed to load sketch: "+r.message,{tone:"error",ms:5e3});return}this.project=t.project,this.originalContent=t.file.content,this.currentSha=t.file.sha,this.renderHeader();let i=this.originalContent,s=Ry(this.cfg.projectId);if(s&&s.code!==this.originalContent){let r=s.remoteSha&&s.remoteSha!==this.currentSha;i=await this.promptRestore(s,this.originalContent,r)}this.mountEditor(i),this.mountPreviewBridge(),this.bindToolbar(),this.startAutosave(),this.startWindowGuards(),this.scheduleReload(i)}renderHeader(){if(!this.project)return;let e=document.getElementById("ga-studio-title"),t=document.getElementById("ga-studio-meta"),i=document.getElementById("ga-studio-repo");e&&(e.textContent=this.project.title),t&&(t.textContent=`${this.project.engine} \xB7 ${this.project.repo_full}`),i&&this.project.repo_url&&(i.href=this.project.repo_url,i.hidden=!1),document.title=`${this.project.title} \u2014 Studio`,et("idle","Loaded")}async promptRestore(e,t,i){return new Promise(s=>{let r=document.getElementById("ga-studio-restore"),o=document.getElementById("ga-studio-restore-yes"),l=document.getElementById("ga-studio-restore-no");if(!r||!o||!l){s(t);return}let a=r.querySelector("span");a&&(a.textContent=i?"The remote sketch was updated elsewhere AND you have an unsaved local copy.":"An unsaved local copy is newer than the remote."),r.classList.remove("d-none");let h=()=>{r.classList.add("d-none"),o.removeEventListener("click",c),l.removeEventListener("click",f)},c=()=>{h(),this.dirty=!0,et("dirty"),s(e.code)},f=()=>{h(),Vd(this.cfg.projectId),s(t)};o.addEventListener("click",c),l.addEventListener("click",f)})}mountEditor(e){let t=document.getElementById("ga-studio-editor");if(!t)return;let i=new fi,s=v.updateListener.of(l=>{l.docChanged&&(this.dirty=this.view.state.doc.toString()!==this.originalContent,et(this.dirty?"dirty":"idle"),this.scheduleReload())}),r=xe.highest(Qt.of([{key:"Mod-s",preventDefault:!0,run:()=>(this.commit(),!0)},{key:"Mod-e",preventDefault:!0,run:()=>(this.exportPng(),!0)}])),o=Y.create({doc:e,extensions:[_d,Xu(),Zy,v.lineWrapping,i.of(v.editable.of(!0)),r,s]});this.view=new v({state:o,parent:t})}mountPreviewBridge(){this.previewIframe=document.getElementById("ga-studio-preview"),window.addEventListener("message",e=>{if(!this.previewIframe||e.source!==this.previewIframe.contentWindow)return;let t=e.data||{};if(t.type==="studio:ready")this.previewReady=!0,this.scheduleReload();else if(t.type==="studio:png"){let i=this.exportRequests.get(t.requestId);i&&(this.exportRequests.delete(t.requestId),t.error?i(new Error(t.error)):i(t.data_url))}else t.type==="studio:error"&&console.warn("[studio preview]",t.message)})}bindToolbar(){document.getElementById("ga-studio-save")?.addEventListener("click",()=>{this.commit()}),document.getElementById("ga-studio-export")?.addEventListener("click",()=>{this.exportPng()})}scheduleReload(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.pushPreview(e)},Ay)}pushPreview(e){if(!this.previewIframe||!this.previewIframe.contentWindow||!this.previewReady)return;let t=e??this.view?.state.doc.toString()??"";this.previewIframe.contentWindow.postMessage({type:"studio:setSrc",code:t,seed:Yd},"*")}startAutosave(){let e=()=>{if(!this.view)return;let t=this.view.state.doc.toString();t!==this.originalContent&&Xy(this.cfg.projectId,{code:t,remoteSha:this.currentSha,saved_at:Date.now()})};this.autosaveTimer=setInterval(e,My),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()}),window.addEventListener("blur",e)}startWindowGuards(){window.addEventListener("beforeunload",e=>{this.dirty&&(e.preventDefault(),e.returnValue="")})}async commit(){if(!this.view||!this.project)return;let e=this.view.state.doc.toString();if(!this.dirty&&e===this.originalContent){Xe("Nothing to commit.",{tone:"info",ms:1400});return}et("saving");try{let t=await kr(`${this.cfg.apiBase}/v1/projects/${this.project.id}/commit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Id,content:e,sha:this.currentSha||void 0})});this.currentSha=t.commit.content_sha,this.originalContent=e,this.dirty=!1,Vd(this.cfg.projectId),et("saved",`Saved \xB7 ${t.commit.commit_sha.slice(0,7)}`),Xe("Committed "+t.commit.commit_sha.slice(0,7),{tone:"success"})}catch(t){et("error","Save failed");let i=t.status;i===409?Xe("Conflict \u2014 refresh to pull the newer remote.",{tone:"error",ms:4e3}):i===401?this.cfg.onUnauthenticated?.():Xe("Save failed: "+t.message,{tone:"error",ms:4e3})}}async exportPng(){if(!this.previewIframe?.contentWindow||!this.previewReady||!this.project){Xe("Preview isn't ready yet.",{tone:"error"});return}let e=`png-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;et("saving","Exporting\u2026");let t=await new Promise((i,s)=>{this.exportRequests.set(e,r=>{r instanceof Error?s(r):i(r)}),this.previewIframe.contentWindow.postMessage({type:"studio:exportPng",requestId:e},"*"),setTimeout(()=>{this.exportRequests.has(e)&&(this.exportRequests.delete(e),s(new Error("export_timeout")))},8e3)}).catch(i=>(Xe("Export failed: "+i.message,{tone:"error",ms:4e3}),et("idle"),null));if(t)try{let i=await kr(`${this.cfg.apiBase}/v1/projects/${this.project.id}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data_url:t,seed:String(Yd)})});try{await navigator.clipboard.writeText(i.capture.url),Xe("PNG uploaded \u2014 URL copied.",{tone:"success",ms:3e3})}catch{Xe("PNG uploaded: "+i.capture.url,{tone:"success",ms:4e3})}et(this.dirty?"dirty":"idle")}catch(i){if(i.status===503){let r=document.createElement("a");r.href=t,r.download=`${this.project.slug}-${Date.now()}.png`,r.click(),Xe("Captures bucket not configured \u2014 downloaded locally.",{tone:"info",ms:4e3}),et(this.dirty?"dirty":"idle")}else Xe("Upload failed: "+i.message,{tone:"error",ms:4e3}),et("error","Upload failed")}}},jd={mount(n){za({apiBase:n.apiBase,page:"studio"}),new La(n).start()}};window.GAStudio=jd;var gx=jd;export{gx as default}; +}`,{label:"class",detail:"definition",type:"keyword"}),be('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),be('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],v0=Tu.concat([be("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),be("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),be("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),vu=new Rs,Cu=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function vn(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}var $0=["FunctionDeclaration"],P0={FunctionDeclaration:vn("function"),ClassDeclaration:vn("class"),ClassExpression:()=>!0,EnumDeclaration:vn("constant"),TypeAliasDeclaration:vn("type"),NamespaceDeclaration:vn("namespace"),VariableDefinition(n,e){n.matchContext($0)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function Zu(n,e){let t=vu.get(e);if(t)return t;let i=[],s=!0;function r(o,l){let a=n.sliceString(o.from,o.to);i.push({label:a,type:l})}return e.cursor(U.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let l=P0[o.name];if(l&&l(o,r)||Cu.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of Zu(n,o.node))i.push(l);return!1}}),vu.set(e,i),i}var $u=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Au=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function T0(n){let e=ee(n.state).resolveInner(n.pos,-1);if(Au.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&$u.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)Cu.has(s.name)&&(i=i.concat(Zu(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:$u}}var ii=Is.define({name:"javascript",parser:Cf.configure({props:[Nl.add({IfStatement:Gs({except:/^\s*({|else\b)/}),TryStatement:Gs({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:If,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:_f({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Gs({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),Gl.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":qf,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Mu={test:n=>/^JSX/.test(n.name),facet:jl({commentTokens:{block:{open:"{/*",close:"*/}"}}})},C0=ii.configure({dialect:"ts"},"typescript"),Z0=ii.configure({dialect:"jsx",props:[js.add(n=>n.isTop?[Mu]:void 0)]}),A0=ii.configure({dialect:"jsx ts",props:[js.add(n=>n.isTop?[Mu]:void 0)]},"typescript"),Ru=n=>({label:n,type:"keyword"}),Xu="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Ru),M0=Xu.concat(["declare","implements","private","protected","public"].map(Ru));function Lu(n={}){let e=n.jsx?n.typescript?A0:Z0:n.typescript?C0:ii,t=n.typescript?v0.concat(M0):Tu.concat(Xu);return new Ys(e,[ii.data.of({autocomplete:du(Au,aa(t))}),ii.data.of({autocomplete:T0}),n.jsx?L0:[]])}function R0(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function Pu(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}var X0=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),L0=v.inputHandler.of((n,e,t,i,s)=>{if((X0?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!ii.isActiveAt(n.state,e,-1))return!1;let r=s(),{state:o}=r,l=o.changeByRange(a=>{var h;let{head:c}=a,f=ee(o).resolveInner(c-1,-1),u;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(c-1,c)!=i||f.name=="JSXAttributeValue"&&f.to>c)){if(i==">"&&f.name=="JSXFragmentTag")return{range:a,changes:{from:c,insert:""}};if(i=="/"&&f.name=="JSXStartCloseTag"){let d=f.parent,p=d.parent;if(p&&d.from==c-2&&((u=Pu(o.doc,p.firstChild,c))||((h=p.firstChild)===null||h===void 0?void 0:h.name)=="JSXFragmentTag")){let O=`${u}>`;return{range:b.cursor(c+O.length,-1),changes:{from:c,insert:O}}}}else if(i==">"){let d=R0(f);if(d&&d.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(c,c+2))&&(u=Pu(o.doc,d,c)))return{range:a,changes:{from:c,insert:``}}}}return{range:a}});return l.changes.empty?!1:(n.dispatch([r,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});var E0=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=wa(n.state,t.from);return i.line?D0(n):i.block?W0(n):!1};function Sa(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}var D0=Sa(I0,0);var B0=Sa(qu,0);var W0=Sa((n,e)=>qu(n,e,z0(e)),0);function wa(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}var $n=50;function _0(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-$n,i),o=n.sliceDoc(s,s+$n),l=/\s*$/.exec(r)[0].length,a=/^\s*/.exec(o)[0].length,h=r.length-l;if(r.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:s+a,margin:a&&1}};let c,f;s-i<=2*$n?c=f=n.sliceDoc(i,s):(c=n.sliceDoc(i,i+$n),f=n.sliceDoc(s-$n,s));let u=/^\s*/.exec(c)[0].length,d=/\s*$/.exec(f)[0].length,p=f.length-d-t.length;return c.slice(u,u+e.length)==e&&f.slice(p,p+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(c.charAt(u+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(f.charAt(p-1))?1:0}}:null}function z0(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function qu(n,e,t=e.selection.ranges){let i=t.map(r=>wa(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>_0(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,l;os&&(r==o||o>f.from)){s=f.from;let u=/^\s*/.exec(f.text)[0].length,d=u==f.length,p=f.text.slice(u,u+h.length)==h?u:-1;ur.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:l,token:a,indent:h,empty:c,single:f}of i)(f||!c)&&r.push({from:l.from+h,insert:a+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,c=h+a.length;o.text[c-o.from]==" "&&c++,r.push({from:h,to:c})}return{changes:r}}return null}var ga=xe.define(),Y0=xe.define(),q0=$.define(),Vu=$.define({combine(n){return ue(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),ju=K.define({create(){return ni.empty},update(n,e){let t=e.state.facet(Vu),i=e.annotation(ga);if(i){let a=He.fromTransaction(e,i.selection),h=i.side,c=h==0?n.undone:n.done;return a?c=sr(c,c.length,t.minDepth,a):c=Fu(c,e.startState.selection),new ni(h==0?i.rest:c,h==0?c:i.rest)}let s=e.annotation(Y0);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(ie.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=He.fromTransaction(e),o=e.annotation(ie.time),l=e.annotation(ie.userEvent);return r?n=n.addChanges(r,o,l,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new ni(n.done.map(He.fromJSON),n.undone.map(He.fromJSON))}});function Nu(n={}){return[ju,Vu.of(n),v.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?Gu:e.inputType=="historyRedo"?ya:null;return i?(e.preventDefault(),i(t)):!1}})]}function rr(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(ju,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}var Gu=rr(0,!1),ya=rr(1,!1),V0=rr(0,!0),j0=rr(1,!0);var He=class n{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new n(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;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:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new n(e.changes&&me.fromJSON(e.changes),[],e.mapped&&ht.fromJSON(e.mapped),e.startSelection&&b.fromJSON(e.startSelection),e.selectionsAfter.map(b.fromJSON))}static fromTransaction(e,t){let i=qe;for(let s of e.startState.facet(q0)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new n(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,qe)}static selection(e){return new n(void 0,qe,void 0,void 0,e)}};function sr(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function N0(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,l)=>{for(let a=0;a=h&&o<=c&&(i=!0)}}),i}function G0(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function Uu(n,e){return n.length?e.length?n.concat(e):n:e}var qe=[],U0=200;function Fu(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-U0));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),sr(n,n.length-1,1e9,t.setSelAfter(i)))}else return[He.selection([e])]}function F0(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function ma(n,e){if(!n.length)return n;let t=n.length,i=qe;for(;t;){let s=H0(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[He.selection(i)]:qe}function H0(n,e,t){let i=Uu(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):qe,t);if(!n.changes)return He.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new He(s,A.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}var K0=/^(input\.type|delete)($|\.)/,ni=class n{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new n(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||K0.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):or(t,e))}function pe(n){return n.textDirectionAt(n.state.selection.main.head)==z.LTR}var Ju=n=>Ku(n,!pe(n)),ed=n=>Ku(n,pe(n));function td(n,e){return Je(n,t=>t.empty?n.moveByGroup(t,e):or(t,e))}var J0=n=>td(n,!pe(n)),e1=n=>td(n,pe(n));var Vb=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function t1(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function lr(n,e,t){let i=ee(n).resolveInner(e.head),s=t?R.closedBy:R.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;t1(n,h,s)?i=h:a=t?h.to:h.from}let r=i.type.prop(s),o,l;return r&&(o=t?Fe(n,i.from,1):Fe(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,b.cursor(l,t?-1:1)}var i1=n=>Je(n,e=>lr(n.state,e,!pe(n))),n1=n=>Je(n,e=>lr(n.state,e,pe(n)));function id(n,e){return Je(n,t=>{if(!t.empty)return or(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}var nd=n=>id(n,!1),sd=n=>id(n,!0);function rd(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):or(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),l=n.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,h=l.bottom-t.marginBottom;o&&o.top>a&&o.bottomod(n,!1),ba=n=>od(n,!0);function At(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=b.cursor(i.from+r))}return s}var s1=n=>Je(n,e=>At(n,e,!0)),r1=n=>Je(n,e=>At(n,e,!1)),o1=n=>Je(n,e=>At(n,e,!pe(n))),l1=n=>Je(n,e=>At(n,e,pe(n))),a1=n=>Je(n,e=>b.cursor(n.lineBlockAt(e.head).from,1)),h1=n=>Je(n,e=>b.cursor(n.lineBlockAt(e.head).to,-1));function c1(n,e,t){let i=!1,s=Xi(n.selection,r=>{let o=Fe(n,r.head,-1)||Fe(n,r.head,1)||r.head>0&&Fe(n,r.head-1,1)||r.headc1(n,e,!1);function Ve(n,e){let t=Xi(n.state.selection,i=>{let s=e(i);return b.range(i.anchor,s.head,s.goalColumn,s.bidiLevel||void 0,s.assoc)});return t.eq(n.state.selection)?!1:(n.dispatch(Ke(n.state,t)),!0)}function ld(n,e){return Ve(n,t=>n.moveByChar(t,e))}var ad=n=>ld(n,!pe(n)),hd=n=>ld(n,pe(n));function cd(n,e){return Ve(n,t=>n.moveByGroup(t,e))}var u1=n=>cd(n,!pe(n)),d1=n=>cd(n,pe(n));var p1=n=>Ve(n,e=>lr(n.state,e,!pe(n))),O1=n=>Ve(n,e=>lr(n.state,e,pe(n)));function fd(n,e){return Ve(n,t=>n.moveVertically(t,e))}var ud=n=>fd(n,!1),dd=n=>fd(n,!0);function pd(n,e){return Ve(n,t=>n.moveVertically(t,e,rd(n).height))}var Du=n=>pd(n,!1),Bu=n=>pd(n,!0),m1=n=>Ve(n,e=>At(n,e,!0)),g1=n=>Ve(n,e=>At(n,e,!1)),y1=n=>Ve(n,e=>At(n,e,!pe(n))),b1=n=>Ve(n,e=>At(n,e,pe(n))),x1=n=>Ve(n,e=>b.cursor(n.lineBlockAt(e.head).from)),S1=n=>Ve(n,e=>b.cursor(n.lineBlockAt(e.head).to)),Wu=({state:n,dispatch:e})=>(e(Ke(n,{anchor:0})),!0),_u=({state:n,dispatch:e})=>(e(Ke(n,{anchor:n.doc.length})),!0),zu=({state:n,dispatch:e})=>(e(Ke(n,{anchor:n.selection.main.anchor,head:0})),!0),Iu=({state:n,dispatch:e})=>(e(Ke(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),w1=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),k1=({state:n,dispatch:e})=>{let t=ar(n).map(({from:i,to:s})=>b.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:b.create(t),userEvent:"select"})),!0},Q1=({state:n,dispatch:e})=>{let t=Xi(n.selection,i=>{let s=ee(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:l}=o;if((l.from=i.to||l.to>i.to&&l.from<=i.from)&&o.next)return b.range(l.to,l.from)}return i});return t.eq(n.selection)?!1:(e(Ke(n,t)),!0)};function Od(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let l=r;;){let a=n.moveVertically(l,e);if(a.heado.to){s.some(h=>h.head==a.head)||s.push(a);break}else{if(a.head==l.head)break;l=a}}}return s.length==i.ranges.length?!1:(n.dispatch(Ke(t,b.create(s,s.length-1))),!0)}var v1=n=>Od(n,!1),$1=n=>Od(n,!0),P1=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=b.create([t.main]):t.main.empty||(i=b.create([b.cursor(t.main.head)])),i?(e(Ke(n,i)),!0):!1};function Pn(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:l}=r;if(o==l){let a=e(r);ao&&(t="delete.forward",a=nr(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=nr(n,o,!1),l=nr(n,l,!0);return o==l?{range:r}:{changes:{from:o,to:l},range:b.cursor(o,os(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}var md=(n,e,t)=>Pn(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),l,a;if(t&&!e&&s>o.from&&smd(n,!1,!0);var gd=n=>md(n,!0,!1),yd=(n,e)=>Pn(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let l=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let a=te(r.text,i-r.from,e)+r.from,h=r.text.slice(Math.min(i,a)-r.from,Math.max(i,a)-r.from),c=o(h);if(l!=null&&c!=l)break;(h!=" "||i!=t.head)&&(l=c),i=a}return i}),bd=n=>yd(n,!1),T1=n=>yd(n,!0);var C1=n=>Pn(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headPn(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),A1=n=>Pn(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:E.of(["",""])},range:b.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},R1=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:te(r.text,s-r.from,!1)+r.from,l=s==r.to?s+1:te(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:l,insert:n.doc.slice(s,l).append(n.doc.slice(o,s))},range:b.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function ar(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function xd(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of ar(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),l=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let a of r.ranges)s.push(b.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let a of r.ranges)s.push(b.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:b.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}var X1=({state:n,dispatch:e})=>xd(n,e,!1),L1=({state:n,dispatch:e})=>xd(n,e,!0);function Sd(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of ar(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}var E1=({state:n,dispatch:e})=>Sd(n,e,!1),D1=({state:n,dispatch:e})=>Sd(n,e,!0),B1=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(ar(e).map(({from:s,to:r})=>(s>0?s--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),l=n.coordsAtPos(s.head,s.assoc||1);l&&(r=o.bottom+n.documentTop-l.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function W1(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=ee(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(R.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}var Yu=wd(!1),_1=wd(!0);function wd(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,l=e.doc.lineAt(r),a=!n&&r==o&&W1(e,r);n&&(r=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new Kt(e,{simulateBreak:r,simulateDoubleBreak:!!a}),c=Ns(h,r);for(c==null&&(c=ct(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));ol.from&&r{let s=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,s,i),t=l.number),o=l.to+1}let r=n.changes(s);return{changes:s,range:b.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}var z1=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Kt(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=ka(n,(r,o,l)=>{let a=Ns(i,r.from);if(a==null)return;/\S/.test(r.text)||(a=0);let h=/^\s*/.exec(r.text)[0],c=Mi(n,a);(h!=c||l.fromn.readOnly?!1:(e(n.update(ka(n,(t,i)=>{i.push({from:t.from,insert:n.facet(Ai)})}),{userEvent:"input.indent"})),!0),Y1=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(ka(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=ct(s,n.tabSize),o=0,l=Mi(n,Math.max(0,r-bn(n)));for(;o(n.setTabFocusMode(),!0);var V1=[{key:"Ctrl-b",run:Ju,shift:ad,preventDefault:!0},{key:"Ctrl-f",run:ed,shift:hd},{key:"Ctrl-p",run:nd,shift:ud},{key:"Ctrl-n",run:sd,shift:dd},{key:"Ctrl-a",run:a1,shift:x1},{key:"Ctrl-e",run:h1,shift:S1},{key:"Ctrl-d",run:gd},{key:"Ctrl-h",run:xa},{key:"Ctrl-k",run:C1},{key:"Ctrl-Alt-h",run:bd},{key:"Ctrl-o",run:M1},{key:"Ctrl-t",run:R1},{key:"Ctrl-v",run:ba}],j1=[{key:"ArrowLeft",run:Ju,shift:ad,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:J0,shift:u1,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:o1,shift:y1,preventDefault:!0},{key:"ArrowRight",run:ed,shift:hd,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:e1,shift:d1,preventDefault:!0},{mac:"Cmd-ArrowRight",run:l1,shift:b1,preventDefault:!0},{key:"ArrowUp",run:nd,shift:ud,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Wu,shift:zu},{mac:"Ctrl-ArrowUp",run:Eu,shift:Du},{key:"ArrowDown",run:sd,shift:dd,preventDefault:!0},{mac:"Cmd-ArrowDown",run:_u,shift:Iu},{mac:"Ctrl-ArrowDown",run:ba,shift:Bu},{key:"PageUp",run:Eu,shift:Du},{key:"PageDown",run:ba,shift:Bu},{key:"Home",run:r1,shift:g1,preventDefault:!0},{key:"Mod-Home",run:Wu,shift:zu},{key:"End",run:s1,shift:m1,preventDefault:!0},{key:"Mod-End",run:_u,shift:Iu},{key:"Enter",run:Yu,shift:Yu},{key:"Mod-a",run:w1},{key:"Backspace",run:xa,shift:xa,preventDefault:!0},{key:"Delete",run:gd,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:bd,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:T1,preventDefault:!0},{mac:"Mod-Backspace",run:Z1,preventDefault:!0},{mac:"Mod-Delete",run:A1,preventDefault:!0}].concat(V1.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),kd=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:i1,shift:p1},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:n1,shift:O1},{key:"Alt-ArrowUp",run:X1},{key:"Shift-Alt-ArrowUp",run:E1},{key:"Alt-ArrowDown",run:L1},{key:"Shift-Alt-ArrowDown",run:D1},{key:"Mod-Alt-ArrowUp",run:v1},{key:"Mod-Alt-ArrowDown",run:$1},{key:"Escape",run:P1},{key:"Mod-Enter",run:_1},{key:"Alt-l",mac:"Ctrl-l",run:k1},{key:"Mod-i",run:Q1,preventDefault:!0},{key:"Mod-[",run:Y1},{key:"Mod-]",run:I1},{key:"Mod-Alt-\\",run:z1},{key:"Shift-Mod-k",run:B1},{key:"Shift-Mod-\\",run:f1},{key:"Mod-/",run:E0},{key:"Alt-A",run:B0},{key:"Ctrl-m",mac:"Shift-Alt-m",run:q1}].concat(j1);var Qd=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n,Rt=class{constructor(e,t,i=0,s=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=r?l=>r(Qd(l)):Qd,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 le(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=Yi(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=Te(e);let s=this.normalize(t);if(s.length)for(let r=0,o=i,l=!0;;r++){let a=s.charCodeAt(r),h=this.match(a,o,l,this.bufferPos+this.bufferStart,r==s.length-1);if(h)return this.value=h,this;if(r==s.length-1)break;l&&rthis.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 i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=pr(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(ithis.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=i||s.to<=t){let l=new n(t,e.sliceString(t,i));return Qa.set(e,l),l}if(s.from==t&&s.to==i)return s;let{text:r,from:o}=s;return o>t&&(r=e.sliceString(t,o)+r,o=t),s.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 i=this.flat.from+t.index,s=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this.matchPos=pr(this.text,s+(i==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=ur.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<"u"&&(fr.prototype[Symbol.iterator]=dr.prototype[Symbol.iterator]=function(){return this});function N1(n){try{return new RegExp(n,Ca),!0}catch{return!1}}function pr(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e=56320&&i<57344;)e++;return e}var G1=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:i,result:s}=of(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return s.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:i});return}let l=e.doc.lineAt(e.selection.main.head),[,a,h,c,f]=o,u=c?+c.slice(1):0,d=h?+h:l.number;if(h&&f){let g=d/100;a&&(g=g*(a=="-"?-1:1)+l.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else h&&a&&(d=d*(a=="-"?-1:1)+l.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),O=b.cursor(p.from+Math.max(0,Math.min(u,p.length)));n.dispatch({effects:[i,v.scrollIntoView(O.from,{y:"center"})],selection:O})}),!0},U1={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Td=$.define({combine(n){return ue(n,U1,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function Cd(n){let e=[ey,J1];return n&&e.push(Td.of(n)),e}var F1=Z.mark({class:"cm-selectionMatch"}),H1=Z.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function vd(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=q.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=q.Word)}function K1(n,e,t,i){return n(e.sliceDoc(t,t+1))==q.Word&&n(e.sliceDoc(i-1,i))==q.Word}var J1=H.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(Td),{state:t}=n,i=t.selection;if(i.ranges.length>1)return Z.none;let s=i.main,r,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return Z.none;let a=t.wordAt(s.head);if(!a)return Z.none;o=t.charCategorizer(s.head),r=t.sliceDoc(a.from,a.to)}else{let a=s.to-s.from;if(a200)return Z.none;if(e.wholeWords){if(r=t.sliceDoc(s.from,s.to),o=t.charCategorizer(s.head),!(vd(o,t,s.from,s.to)&&K1(o,t,s.from,s.to)))return Z.none}else if(r=t.sliceDoc(s.from,s.to),!r)return Z.none}let l=[];for(let a of n.visibleRanges){let h=new Rt(t.doc,r,a.from,a.to);for(;!h.next().done;){let{from:c,to:f}=h.value;if((!o||vd(o,t,c,f))&&(s.empty&&c<=s.from&&f>=s.to?l.push(H1.range(c,f)):(c>=s.to||f<=s.from)&&l.push(F1.range(c,f)),l.length>e.maxMatches))return Z.none}}return Z.set(l)}},{decorations:n=>n.decorations}),ey=v.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),ty=({state:n,dispatch:e})=>{let{selection:t}=n,i=b.create(t.ranges.map(s=>n.wordAt(s.head)||b.cursor(s.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function iy(n,e){let{main:t,ranges:i}=n.selection,s=n.wordAt(t.head),r=s&&s.from==t.from&&s.to==t.to;for(let o=!1,l=new Rt(n.doc,e,i[i.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new Rt(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(a=>a.from==l.value.from))continue;if(r){let a=n.wordAt(l.value.from);if(!a||a.from!=l.value.from||a.to!=l.value.to)continue}return l.value}}var ny=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return ty({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=i))return!1;let s=iy(n,i);return s?(e(n.update({selection:n.selection.addRange(b.range(s.from,s.to),!1),effects:v.scrollIntoView(s.to)})),!0):!1},Di=$.define({combine(n){return ue(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Ta(e),scrollToMatch:e=>v.scrollIntoView(e)})}});var Or=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||N1(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` +`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new $a(this):new va(this)}getCursor(e,t=0,i){let s=e.doc?e:Y.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?Ei(this,s,t,i):Li(this,s,t,i)}},mr=class{constructor(e){this.spec=e}};function sy(n,e,t){return(i,s,r,o)=>{if(t&&!t(i,s,r,o))return!1;let l=i>=o&&s<=o+r.length?r.slice(i-o,s-o):e.doc.sliceString(i,s);return n(l,e,i,s)}}function Li(n,e,t,i){let s;return n.wholeWord&&(s=ry(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(s=sy(n.test,e,s)),new Rt(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),s)}function ry(n,e){return(t,i,s,r)=>((r>t||r+s.length=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Li(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}};function oy(n,e,t){return(i,s,r)=>(!t||t(i,s,r))&&n(r[0],e,i,s)}function Ei(n,e,t,i){let s;return n.wholeWord&&(s=ly(e.charCategorizer(e.selection.main.head))),n.test&&(s=oy(n.test,e,s)),new fr(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:s},t,i)}function gr(n,e){return n.slice(te(n,e,!1),e)}function yr(n,e){return n.slice(e,te(n,e))}function ly(n){return(e,t,i)=>!i[0].length||(n(gr(i.input,i.index))!=q.Word||n(yr(i.input,i.index))!=q.Word)&&(n(yr(i.input,i.index+i[0].length))!=q.Word||n(gr(i.input,i.index+i[0].length))!=q.Word)}var $a=class extends mr{nextMatch(e,t,i){let s=Ei(this.spec,e,i,e.doc.length).next();return s.done&&(s=Ei(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=Ei(this.spec,e,r,i),l=null;for(;!o.next().done;)l=o.value;if(l&&(r==t||l.from>r+10))return l;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Ei(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}},Cn=A.define(),Za=A.define(),Mt=K.define({create(n){return new Tn(Pa(n).create(),null)},update(n,e){for(let t of e.effects)t.is(Cn)?n=new Tn(t.value.create(),n.panel):t.is(Za)&&(n=new Tn(n.query,t.value?Aa:null));return n},provide:n=>jt.from(n,e=>e.panel)});var Tn=class{constructor(e,t){this.query=e,this.panel=t}},ay=Z.mark({class:"cm-searchMatch"}),hy=Z.mark({class:"cm-searchMatch cm-searchMatch-selected"}),cy=H.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(Mt))}update(n){let e=n.state.field(Mt);(e!=n.startState.field(Mt)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return Z.none;let{view:t}=this,i=new Pe;for(let s=0,r=t.visibleRanges,o=r.length;sr[s+1].from-500;)a=r[++s].to;n.highlight(t.state,l,a,(h,c)=>{let f=t.state.selection.ranges.some(u=>u.from==h&&u.to==c);i.add(h,c,f?hy:ay)})}return i.finish()}},{decorations:n=>n.decorations});function Zn(n){return e=>{let t=e.state.field(Mt,!1);return t&&t.query.spec.valid?n(e,t):Md(e)}}var br=Zn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=b.single(i.from,i.to),r=n.state.facet(Di);return n.dispatch({selection:s,effects:[Ma(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),Ad(n),!0}),xr=Zn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=b.single(s.from,s.to),o=n.state.facet(Di);return n.dispatch({selection:r,effects:[Ma(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),Ad(n),!0}),fy=Zn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:b.create(t.map(i=>b.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),uy=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:s}=t.main,r=[],o=0;for(let l=new Rt(n.doc,n.sliceDoc(i,s));!l.next().done;){if(r.length>1e3)return!1;l.value.from==i&&(o=r.length),r.push(b.range(l.value.from,l.value.to))}return e(n.update({selection:b.create(r,o),userEvent:"select.search.matches"})),!0},$d=Zn((n,{query:e})=>{let{state:t}=n,{from:i,to:s}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,l=[],a,h,c=[];o.precise?o.from==i&&o.to==s&&(h=t.toText(e.getReplacement(o)),l.push({from:o.from,to:o.to,insert:h}),c.push(v.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let f=n.state.changes(l);return o&&(a=b.single(o.from,o.to).map(f),c.push(Ma(n,o)),c.push(t.facet(Di).scrollToMatch(a.main,n))),n.dispatch({changes:f,selection:a,effects:c,userEvent:"input.replace"}),!0}),dy=Zn((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let s of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:l}=s;l&&t.push({from:r,to:o,insert:e.getReplacement(s)})}if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:v.announce.of(i),userEvent:"input.replace.all"}),!0});function Aa(n){return n.state.facet(Di).createPanel(n)}function Pa(n,e){var t,i,s,r,o;let l=n.selection.main,a=l.empty||l.to>l.from+100?"":n.sliceDoc(l.from,l.to);if(e&&!a)return e;let h=n.facet(Di);return new Or({search:((t=e?.literal)!==null&&t!==void 0?t:h.literal)?a:a.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:h.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:h.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:h.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:h.wholeWord})}function Zd(n){let e=hn(n,Aa);return e&&e.dom.querySelector("[main-field]")}function Ad(n){let e=Zd(n);e&&e==n.root.activeElement&&e.select()}var Md=n=>{let e=n.state.field(Mt,!1);if(e&&e.panel){let t=Zd(n);if(t&&t!=n.root.activeElement){let i=Pa(n.state,e.query.spec);i.valid&&n.dispatch({effects:Cn.of(i)}),t.focus(),t.select()}}else n.dispatch({effects:[Za.of(!0),e?Cn.of(Pa(n.state,e.query.spec)):A.appendConfig.of(Oy)]});return!0},Rd=n=>{let e=n.state.field(Mt,!1);if(!e||!e.panel)return!1;let t=hn(n,Aa);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Za.of(!1)}),!0},Xd=[{key:"Mod-f",run:Md,scope:"editor search-panel"},{key:"F3",run:br,shift:xr,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:br,shift:xr,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Rd,scope:"editor search-panel"},{key:"Mod-Shift-l",run:uy},{key:"Mod-Alt-g",run:G1},{key:"Mod-d",run:ny,preventDefault:!0}],Ta=class{constructor(e){this.view=e;let t=this.query=e.state.field(Mt).query.spec;this.commit=this.commit.bind(this),this.searchField=W("input",{value:t.search,placeholder:Re(e,"Find"),"aria-label":Re(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=W("input",{value:t.replace,placeholder:Re(e,"Replace"),"aria-label":Re(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=W("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=W("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=W("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(s,r,o){return W("button",{class:"cm-button",name:s,onclick:r,type:"button"},o)}this.dom=W("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,i("next",()=>br(e),[Re(e,"next")]),i("prev",()=>xr(e),[Re(e,"previous")]),i("select",()=>fy(e),[Re(e,"all")]),W("label",null,[this.caseField,Re(e,"match case")]),W("label",null,[this.reField,Re(e,"regexp")]),W("label",null,[this.wordField,Re(e,"by word")]),...e.state.readOnly?[]:[W("br"),this.replaceField,i("replace",()=>$d(e),[Re(e,"replace")]),i("replaceAll",()=>dy(e),[Re(e,"replace all")])],W("button",{name:"close",onclick:()=>Rd(e),"aria-label":Re(e,"close"),type:"button"},["\xD7"])])}commit(){let e=new Or({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:Cn.of(e)}))}keydown(e){Vc(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?xr:br)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),$d(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(Cn)&&!i.value.eq(this.query)&&this.setQuery(i.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(Di).top}};function Re(n,e){return n.state.phrase(e)}var hr=30,cr=/[\s\.,:;?!]/;function Ma(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),s=n.state.doc.lineAt(t).to,r=Math.max(i.from,e-hr),o=Math.min(s,t+hr),l=n.state.sliceDoc(r,o);if(r!=i.from){for(let a=0;al.length-hr;a--)if(!cr.test(l[a-1])&&cr.test(l[a])){l=l.slice(0,a);break}}return v.announce.of(`${n.state.phrase("current match")}. ${l} ${n.state.phrase("on line")} ${i.number}.`)}var py=v.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"}}),Oy=[Mt,Se.low(cy),py];var wr=class{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}},si=class n{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let s=i.facet(An).markerFilter;s&&(e=s(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new Pe,l=[],a=0,h=i.doc.iter(),c=0,f=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!l.length)break;let O,g;if(l.length)O=a,g=l.reduce((S,C)=>Math.min(S,C.to),p&&p.from>O?p.from:1e8);else{if(O=p.from,O>f)break;g=p.to,l.push(p),d++}for(;dS.from||S.to==O))l.push(S),d++,g=Math.min(S.to,g);else{g=Math.min(S.from,g);break}}g=Math.min(g,f);let y=!1;if(l.some(S=>S.from==O&&(S.to==g||g==f))&&(y=O==g,!y&&g-O<10)){let S=O-(c+h.value.length);S>0&&(h.next(S),c=O);for(let C=O;;){if(C>=g){y=!0;break}if(!h.lineBreak&&c+h.value.length>C)break;C=c+h.value.length,c+=h.value.length,h.next()}}let x=$y(l);if(y)o.add(O,O,Z.widget({widget:new Ra(x),diagnostics:l.slice()}));else{let S=l.reduce((C,w)=>w.markClass?C+" "+w.markClass:C,"");o.add(O,g,Z.mark({class:"cm-lintRange cm-lintRange-"+x+S,diagnostics:l.slice(),inclusiveEnd:l.some(C=>C.to>g)}))}if(a=g,a==f)break;for(let S=0;S{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new wr(s,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new wr(i.from,r,i.diagnostic)}}),i}function my(n,e){let t=e.pos,i=e.end||t,s=n.state.facet(An).hideOn(n,t,i);if(s!=null)return s;let r=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(Dd))||n.changes.touchesRange(r.from,Math.max(r.to,i)))}function gy(n,e){return n.field(Xe,!1)?e:e.concat(A.appendConfig.of(Py))}var Dd=A.define(),Xa=A.define(),Bd=A.define(),Xe=K.define({create(){return new si(Z.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),i=null,s=n.panel;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=Xt(t,n.selected.diagnostic,r)||Xt(t,null,r)}!t.size&&s&&e.state.facet(An).autoPanel&&(s=null),n=new si(t,s,i)}for(let t of e.effects)if(t.is(Dd)){let i=e.state.facet(An).autoPanel?t.value.length?Mn.open:null:n.panel;n=si.init(t.value,i,e.state)}else t.is(Xa)?n=new si(n.diagnostics,t.value?Mn.open:null,n.selected):t.is(Bd)&&(n=new si(n.diagnostics,n.panel,t.value));return n},provide:n=>[jt.from(n,e=>e.panel),v.decorations.from(n,e=>e.diagnostics)]});var yy=Z.mark({class:"cm-lintRange cm-lintRange-active"});function by(n,e,t){let{diagnostics:i}=n.state.field(Xe),s,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(a,h,{spec:c})=>{if(e>=a&&e<=h&&(a==h||(e>a||t>0)&&(ezd(n,t,!1)))}var Sy=n=>{let e=n.state.field(Xe,!1);(!e||!e.panel)&&n.dispatch({effects:gy(n.state,[Xa.of(!0)])});let t=hn(n,Mn.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},Ld=n=>{let e=n.state.field(Xe,!1);return!e||!e.panel?!1:(n.dispatch({effects:Xa.of(!1)}),!0)},wy=n=>{let e=n.state.field(Xe,!1);if(!e)return!1;let t=n.state.selection.main,i=Xt(e.diagnostics,null,t.to+1);return!i&&(i=Xt(e.diagnostics,null,0),!i||i.from==t.from&&i.to==t.to)?!1:(n.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0}),!0)};var Wd=[{key:"Mod-Shift-m",run:Sy,preventDefault:!0},{key:"F8",run:wy}];var An=$.define({combine(n){return{sources:n.map(e=>e.source).filter(e=>e!=null),...ue(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:Ed,tooltipFilter:Ed,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,s,r)=>e(i,s,r)||t(i,s,r):e:t,autoPanel:(e,t)=>e||t})}}});function Ed(n,e){return n?e?(t,i)=>e(n(t,i),i):n:e}function _d(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;ir.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function zd(n,e,t){var i;let s=t?_d(e.actions):[];return W("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},W("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let l=!1,a=d=>{if(d.preventDefault(),l)return;l=!0;let p=Xt(n.state.field(Xe).diagnostics,e);p&&r.apply(n,p.from,p.to)},{name:h}=r,c=s[o]?h.indexOf(s[o]):-1,f=c<0?h:[h.slice(0,c),W("u",h.slice(c,c+1)),h.slice(c+1)],u=r.markClass?" "+r.markClass:"";return W("button",{type:"button",class:"cm-diagnosticAction"+u,onclick:a,onmousedown:a,"aria-label":` Action: ${h}${c<0?"":` (access key "${s[o]})"`}.`},f)}),e.source&&W("div",{class:"cm-diagnosticSource"},e.source))}var Ra=class extends ye{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return W("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}},kr=class{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=zd(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}},Mn=class n{constructor(e){this.view=e,this.items=[];let t=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)Ld(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=_d(r.actions);for(let l=0;l{for(let r=0;rLd(this.view)},"\xD7")),this.update()}get selectedIndex(){let e=this.view.state.field(Xe).selected;if(!e)return-1;for(let t=0;t{for(let c of h.diagnostics){if(o.has(c))continue;o.add(c);let f=-1,u;for(let d=i;di&&(this.items.splice(i,f-i),s=!0)),t&&u.diagnostic==t.diagnostic?u.dom.hasAttribute("aria-selected")||(u.dom.setAttribute("aria-selected","true"),r=u):u.dom.hasAttribute("aria-selected")&&u.dom.removeAttribute("aria-selected"),i++}});i({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:a})=>{let h=a.height/this.list.offsetHeight;l.topa.bottom&&(this.list.scrollTop+=(l.bottom-a.bottom)/h)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(Xe),i=Xt(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:Bd.of(i)})}static open(e){return new n(e)}};function ky(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function Sr(n){return ky(``,'width="6" height="3"')}var Qy=v.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:Sr("#d11")},".cm-lintRange-warning":{backgroundImage:Sr("orange")},".cm-lintRange-info":{backgroundImage:Sr("#999")},".cm-lintRange-hint":{backgroundImage:Sr("#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}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function vy(n){return n=="error"?4:n=="warning"?3:n=="info"?2:1}function $y(n){let e="hint",t=1;for(let i of n){let s=vy(i.severity);s>t&&(t=s,e=i.severity)}return e}var Py=[Xe,v.decorations.compute([Xe],n=>{let{selected:e,panel:t}=n.field(Xe);return!e||!t||e.from==e.to?Z.none:Z.set([yy.range(e.from,e.to)])}),sf(by,{hideOn:my}),Qy];var Id=[cf(),ff(),Jc(),Nu(),Kf(),Uc(),Kc(),Y.allowMultipleSelections.of(!0),Yf(),Fs(eu,{fallback:!0}),su(),bu(),Qu(),tf(),nf(),ef(),Cd(),Qt.of([...wu,...kd,...Xd,...Hu,...Uf,...Oa,...Wd])];var Qr="#FAFAF7",yt="#0A0A0A",gt="#E63946",La="rgba(10, 10, 10, 0.12)",jd="rgba(10, 10, 10, 0.55)",Ty="rgba(230, 57, 70, 0.18)",Cy=v.theme({"&":{color:yt,backgroundColor:Qr,height:"100%"},".cm-content":{caretColor:gt,fontFamily:'ui-monospace, "JetBrains Mono", "IBM Plex Mono", Menlo, Consolas, monospace'},".cm-cursor, .cm-dropCursor":{borderLeftColor:gt},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:Ty},".cm-gutters":{backgroundColor:Qr,color:jd,borderRight:`1px solid ${La}`},".cm-activeLine":{backgroundColor:"rgba(10, 10, 10, 0.03)"},".cm-activeLineGutter":{backgroundColor:"rgba(10, 10, 10, 0.04)",color:yt},".cm-selectionMatch":{backgroundColor:"rgba(230, 57, 70, 0.12)"},".cm-matchingBracket, .cm-nonmatchingBracket":{backgroundColor:"rgba(230, 57, 70, 0.18)",outline:"none"},".cm-tooltip":{backgroundColor:Qr,color:yt,border:`1px solid ${La}`},".cm-panels":{backgroundColor:Qr,color:yt,borderTop:`1px solid ${La}`}},{dark:!1}),Zy=Zi.define([{tag:m.keyword,color:gt,fontWeight:"600"},{tag:[m.name,m.deleted,m.character,m.macroName],color:yt},{tag:[m.propertyName],color:yt},{tag:[m.function(m.variableName),m.labelName],color:yt,fontWeight:"600"},{tag:[m.color,m.constant(m.name),m.standard(m.name)],color:gt},{tag:[m.definition(m.name),m.separator],color:yt},{tag:[m.typeName,m.className,m.number,m.changed,m.annotation,m.modifier,m.self,m.namespace],color:gt},{tag:[m.operator,m.operatorKeyword,m.url,m.escape,m.regexp,m.link,m.special(m.string)],color:gt},{tag:[m.meta,m.comment],color:jd,fontStyle:"italic"},{tag:m.strong,fontWeight:"700"},{tag:m.emphasis,fontStyle:"italic"},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.link,color:gt,textDecoration:"underline"},{tag:m.heading,fontWeight:"700",color:yt},{tag:[m.atom,m.bool,m.special(m.variableName)],color:gt},{tag:[m.processingInstruction,m.string,m.inserted],color:"#1f6feb"},{tag:m.invalid,color:gt,textDecoration:"underline"}]),Ay=[Cy,Fs(Zy)],Yd="sketch.js",My=200,Ry=5e3,qd=1;function Da(n){return`ga.studio.${n}`}function Xy(n){try{let e=localStorage.getItem(Da(n));return e?JSON.parse(e):null}catch{return null}}function Ly(n,e){try{localStorage.setItem(Da(n),JSON.stringify(e))}catch{}}function Vd(n){try{localStorage.removeItem(Da(n))}catch{}}function Rn(n){return n.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}async function Xn(n,e){let t=await fetch(n,{credentials:"include",...e});if(!t.ok){let i="";try{i=await t.json()}catch{}let s=typeof i=="object"&&i&&"error"in i?i.error:t.statusText,r=new Error(`${t.status}: ${s}`);throw r.status=t.status,r.detail=i,r}return await t.json()}function Le(n,e={}){let t=document.getElementById("ga-studio-toast");t&&(t.textContent=n,t.dataset.tone=e.tone||"info",t.dataset.show="1",setTimeout(()=>{t.dataset.show="0"},e.ms??2200))}function et(n,e){let t=document.getElementById("ga-studio-status");t&&(t.dataset.state=n,t.textContent=e??{idle:"Idle",dirty:"Unsaved",saving:"Saving\u2026",saved:"Saved",error:"Error"}[n])}var Ea=class{constructor(e){ce(this,"cfg");ce(this,"view",null);ce(this,"previewIframe",null);ce(this,"previewReady",!1);ce(this,"currentSha","");ce(this,"originalContent","");ce(this,"dirty",!1);ce(this,"debounceTimer",null);ce(this,"autosaveTimer",null);ce(this,"exportRequests",new Map);ce(this,"project",null);ce(this,"copilotMode","generate");ce(this,"pendingSuggestion",null);ce(this,"COPILOT_PRICES",{generate:20,edit:15,explain:5,params:5});ce(this,"COPILOT_PLACEHOLDERS",{generate:"Describe the sketch you want\u2026",edit:'Describe the change \u2014 e.g. "make the background black"\u2026',explain:"(uses your current code \u2014 no input needed)",params:"(uses your current code \u2014 no input needed)"});this.cfg=e}async start(){if(!this.cfg.projectId){Le("Missing ?project=ID in the URL.",{tone:"error",ms:5e3});return}let e=null;try{e=await Xn(`${this.cfg.apiBase}/v1/me`)}catch(r){if(r.status===401){this.cfg.onUnauthenticated?.();return}Le("Failed to verify your session.",{tone:"error",ms:4e3});return}if(!e){this.cfg.onUnauthenticated?.();return}let t;try{t=await Xn(`${this.cfg.apiBase}/v1/projects/${this.cfg.projectId}/file?path=${encodeURIComponent(Yd)}`)}catch(r){Le("Failed to load sketch: "+r.message,{tone:"error",ms:5e3});return}this.project=t.project,this.originalContent=t.file.content,this.currentSha=t.file.sha,this.renderHeader();let i=this.originalContent,s=Xy(this.cfg.projectId);if(s&&s.code!==this.originalContent){let r=s.remoteSha&&s.remoteSha!==this.currentSha;i=await this.promptRestore(s,this.originalContent,r)}this.mountEditor(i),this.mountPreviewBridge(),this.bindToolbar(),this.bindCopilot(),this.startAutosave(),this.startWindowGuards(),this.scheduleReload(i)}renderHeader(){if(!this.project)return;let e=document.getElementById("ga-studio-title"),t=document.getElementById("ga-studio-meta"),i=document.getElementById("ga-studio-repo");e&&(e.textContent=this.project.title),t&&(t.textContent=`${this.project.engine} \xB7 ${this.project.repo_full}`),i&&this.project.repo_url&&(i.href=this.project.repo_url,i.hidden=!1),document.title=`${this.project.title} \u2014 Studio`,et("idle","Loaded")}async promptRestore(e,t,i){return new Promise(s=>{let r=document.getElementById("ga-studio-restore"),o=document.getElementById("ga-studio-restore-yes"),l=document.getElementById("ga-studio-restore-no");if(!r||!o||!l){s(t);return}let a=r.querySelector("span");a&&(a.textContent=i?"The remote sketch was updated elsewhere AND you have an unsaved local copy.":"An unsaved local copy is newer than the remote."),r.classList.remove("d-none");let h=()=>{r.classList.add("d-none"),o.removeEventListener("click",c),l.removeEventListener("click",f)},c=()=>{h(),this.dirty=!0,et("dirty"),s(e.code)},f=()=>{h(),Vd(this.cfg.projectId),s(t)};o.addEventListener("click",c),l.addEventListener("click",f)})}mountEditor(e){let t=document.getElementById("ga-studio-editor");if(!t)return;let i=new fi,s=v.updateListener.of(l=>{l.docChanged&&(this.dirty=this.view.state.doc.toString()!==this.originalContent,et(this.dirty?"dirty":"idle"),this.scheduleReload())}),r=Se.highest(Qt.of([{key:"Mod-s",preventDefault:!0,run:()=>(this.commit(),!0)},{key:"Mod-e",preventDefault:!0,run:()=>(this.exportPng(),!0)}])),o=Y.create({doc:e,extensions:[Id,Lu(),Ay,v.lineWrapping,i.of(v.editable.of(!0)),r,s]});this.view=new v({state:o,parent:t})}mountPreviewBridge(){this.previewIframe=document.getElementById("ga-studio-preview"),window.addEventListener("message",e=>{if(!this.previewIframe||e.source!==this.previewIframe.contentWindow)return;let t=e.data||{};if(t.type==="studio:ready")this.previewReady=!0,this.scheduleReload();else if(t.type==="studio:png"){let i=this.exportRequests.get(t.requestId);i&&(this.exportRequests.delete(t.requestId),t.error?i(new Error(t.error)):i(t.data_url))}else t.type==="studio:error"&&console.warn("[studio preview]",t.message)})}bindToolbar(){document.getElementById("ga-studio-save")?.addEventListener("click",()=>{this.commit()}),document.getElementById("ga-studio-export")?.addEventListener("click",()=>{this.exportPng()})}async refreshCopilotBalance(){let e=document.getElementById("ga-copilot-balance");if(e)try{let t=await Xn(`${this.cfg.apiBase}/v1/tokens/account`);e.textContent=`${t.balance.toLocaleString()} tokens`}catch{e.textContent="\u2014"}}bindCopilot(){let e=document.getElementById("ga-studio-copilot-toggle"),t=document.getElementById("ga-studio-grid");e?.addEventListener("click",()=>{let o=!t?.classList.contains("ga-copilot-open");t?.classList.toggle("ga-copilot-open"),document.getElementById("ga-studio-copilot")?.classList.toggle("d-none",!o),o&&this.refreshCopilotBalance()});let i=document.getElementById("ga-copilot-price"),s=document.getElementById("ga-copilot-input"),r=()=>{if(i&&(i.textContent=`${this.COPILOT_PRICES[this.copilotMode]} tokens`),s){s.placeholder=this.COPILOT_PLACEHOLDERS[this.copilotMode];let o=this.copilotMode==="generate"||this.copilotMode==="edit";s.classList.toggle("d-none",!o)}};r(),document.querySelectorAll(".ga-copilot-mode").forEach(o=>{o.addEventListener("click",()=>{document.querySelectorAll(".ga-copilot-mode").forEach(l=>l.classList.toggle("active",l===o)),this.copilotMode=o.dataset.gaMode||"generate",r()})}),document.getElementById("ga-copilot-run")?.addEventListener("click",()=>{this.runCopilot()})}copilotFeedback(e){let t=document.getElementById("ga-copilot-feedback");t&&(t.textContent=e)}async runCopilot(){let e=document.getElementById("ga-copilot-run"),t=document.getElementById("ga-copilot-result"),i=document.getElementById("ga-copilot-input");if(!t||!this.view)return;let s=this.copilotMode,r=this.view.state.doc.toString(),o=i?.value.trim()||"";if((s==="generate"||s==="edit")&&!o){this.copilotFeedback("Describe what you want first.");return}e&&(e.disabled=!0),this.copilotFeedback("Thinking\u2026"),t.innerHTML="";try{let l,a;s==="generate"?(l="generate",a={prompt:o}):s==="edit"?(l="edit",a={current_code:r,instruction:o}):s==="explain"?(l="explain",a={code:r}):(l="params",a={code:r});let h=await fetch(`${this.cfg.apiBase}/v1/projects/${this.cfg.projectId}/ai/${l}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(h.status===402){let f=await h.json().catch(()=>({}));this.copilotFeedback(`Not enough tokens \u2014 need ${f.shortfall??"more"} more. `),t.innerHTML='Buy tokens';return}if(!h.ok){let f=await h.json().catch(()=>({}));this.copilotFeedback(`Failed: ${f.error??h.statusText}`);return}let c=await h.json();if(this.copilotFeedback(`Spent ${c.price_tokens} tokens.`),this.refreshCopilotBalance(),s==="generate"||s==="edit")this.pendingSuggestion=c.result,t.innerHTML=` +
    ${Rn(this.pendingSuggestion)}
    +
    + + +
    `,t.querySelector("#ga-copilot-accept")?.addEventListener("click",()=>this.acceptSuggestion()),t.querySelector("#ga-copilot-reject")?.addEventListener("click",()=>{this.pendingSuggestion=null,t.innerHTML=""});else if(s==="explain")t.innerHTML=`

    ${Rn(String(c.result))}

    `;else{let f=c.result;t.innerHTML=f.length?`
      ${f.map(u=>`
    • ${Rn(u.name)} (${Rn(u.kind)}, default ${Rn(String(u.default))})
    • `).join("")}
    `:'

    Nothing tunable found.

    '}}catch(l){this.copilotFeedback(`Failed: ${l.message}`)}finally{e&&(e.disabled=!1)}}acceptSuggestion(){!this.view||this.pendingSuggestion===null||(this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:this.pendingSuggestion}}),this.pendingSuggestion=null,document.getElementById("ga-copilot-result").innerHTML="",this.copilotFeedback("Applied to the editor \u2014 remember to Save."))}scheduleReload(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.pushPreview(e)},My)}pushPreview(e){if(!this.previewIframe||!this.previewIframe.contentWindow||!this.previewReady)return;let t=e??this.view?.state.doc.toString()??"";this.previewIframe.contentWindow.postMessage({type:"studio:setSrc",code:t,seed:qd},"*")}startAutosave(){let e=()=>{if(!this.view)return;let t=this.view.state.doc.toString();t!==this.originalContent&&Ly(this.cfg.projectId,{code:t,remoteSha:this.currentSha,saved_at:Date.now()})};this.autosaveTimer=setInterval(e,Ry),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()}),window.addEventListener("blur",e)}startWindowGuards(){window.addEventListener("beforeunload",e=>{this.dirty&&(e.preventDefault(),e.returnValue="")})}async commit(){if(!this.view||!this.project)return;let e=this.view.state.doc.toString();if(!this.dirty&&e===this.originalContent){Le("Nothing to commit.",{tone:"info",ms:1400});return}et("saving");try{let t=await Xn(`${this.cfg.apiBase}/v1/projects/${this.project.id}/commit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Yd,content:e,sha:this.currentSha||void 0})});this.currentSha=t.commit.content_sha,this.originalContent=e,this.dirty=!1,Vd(this.cfg.projectId),et("saved",`Saved \xB7 ${t.commit.commit_sha.slice(0,7)}`),Le("Committed "+t.commit.commit_sha.slice(0,7),{tone:"success"})}catch(t){et("error","Save failed");let i=t.status;i===409?Le("Conflict \u2014 refresh to pull the newer remote.",{tone:"error",ms:4e3}):i===401?this.cfg.onUnauthenticated?.():Le("Save failed: "+t.message,{tone:"error",ms:4e3})}}async exportPng(){if(!this.previewIframe?.contentWindow||!this.previewReady||!this.project){Le("Preview isn't ready yet.",{tone:"error"});return}let e=`png-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;et("saving","Exporting\u2026");let t=await new Promise((i,s)=>{this.exportRequests.set(e,r=>{r instanceof Error?s(r):i(r)}),this.previewIframe.contentWindow.postMessage({type:"studio:exportPng",requestId:e},"*"),setTimeout(()=>{this.exportRequests.has(e)&&(this.exportRequests.delete(e),s(new Error("export_timeout")))},8e3)}).catch(i=>(Le("Export failed: "+i.message,{tone:"error",ms:4e3}),et("idle"),null));if(t)try{let i=await Xn(`${this.cfg.apiBase}/v1/projects/${this.project.id}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data_url:t,seed:String(qd)})});try{await navigator.clipboard.writeText(i.capture.url),Le("PNG uploaded \u2014 URL copied.",{tone:"success",ms:3e3})}catch{Le("PNG uploaded: "+i.capture.url,{tone:"success",ms:4e3})}et(this.dirty?"dirty":"idle")}catch(i){if(i.status===503){let r=document.createElement("a");r.href=t,r.download=`${this.project.slug}-${Date.now()}.png`,r.click(),Le("Captures bucket not configured \u2014 downloaded locally.",{tone:"info",ms:4e3}),et(this.dirty?"dirty":"idle")}else Le("Upload failed: "+i.message,{tone:"error",ms:4e3}),et("error","Upload failed")}}},Nd={mount(n){za({apiBase:n.apiBase,page:"studio"}),new Ea(n).start()}};window.GAStudio=Nd;var yx=Nd;export{yx as default}; //# sourceMappingURL=ga-studio.js.map diff --git a/assets/js/ga-studio.js.map b/assets/js/ga-studio.js.map index e6b93a4..83ca02d 100644 --- a/assets/js/ga-studio.js.map +++ b/assets/js/ga-studio.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../../workers/api/client/lib/clientErrors.ts", "../../workers/api/node_modules/@marijn/find-cluster-break/src/index.js", "../../workers/api/node_modules/@codemirror/state/dist/index.js", "../../workers/api/node_modules/style-mod/src/style-mod.js", "../../workers/api/node_modules/w3c-keyname/index.js", "../../workers/api/node_modules/crelt/index.js", "../../workers/api/node_modules/@codemirror/view/dist/index.js", "../../workers/api/node_modules/@lezer/common/dist/index.js", "../../workers/api/node_modules/@lezer/lr/dist/index.js", "../../workers/api/node_modules/@lezer/highlight/dist/index.js", "../../workers/api/node_modules/@lezer/javascript/dist/index.js", "../../workers/api/node_modules/@codemirror/language/dist/index.js", "../../workers/api/node_modules/@codemirror/autocomplete/dist/index.js", "../../workers/api/node_modules/@codemirror/lang-javascript/dist/index.js", "../../workers/api/node_modules/@codemirror/commands/dist/index.js", "../../workers/api/node_modules/@codemirror/search/dist/index.js", "../../workers/api/node_modules/@codemirror/lint/dist/index.js", "../../workers/api/node_modules/codemirror/dist/index.js", "../../workers/api/client/studio.ts"], - "sourcesContent": ["// Window onerror / unhandledrejection \u2192 POST /v1/internal/client-error.\n// Per-page de-dupe and 10-report cap; the Worker rate-limits per IP\n// and forwards to Sentry via SENTRY_DSN_PUBLIC server-side.\n//\n// Why not @sentry/browser? Bundle size is the deciding factor:\n// @sentry/browser min+gz is ~25KB, which is larger than every\n// per-page bundle this app ships (galleries 18KB, studio 100KB,\n// dashboard 7KB). The proxy pattern below has equivalent delivery\n// (the worker uses ctx.waitUntil for the forward), preserves stack\n// fidelity (we POST the raw `Error.stack` string verbatim), and\n// keeps the public DSN out of the client where it would otherwise\n// be visible to scrapers. The trade-off is that we don't get the\n// SDK's auto-capture of breadcrumbs / fetch/console hooks; for v1\n// observability that's an acceptable gap given the size budget.\n\nconst SEEN = new Set();\nconst MAX_REPORTS_PER_PAGE = 10;\nlet installed = false;\nlet configured: { apiBase: string; page: string } | null = null;\n\nexport interface ClientErrorReporterConfig {\n apiBase: string;\n /** Short page identifier \u2014 \"studio\", \"dashboard\", \"galleries\" etc. */\n page: string;\n}\n\nexport function installClientErrorReporter(cfg: ClientErrorReporterConfig): void {\n if (installed) return;\n installed = true;\n configured = cfg;\n window.addEventListener(\"error\", (ev) => {\n const message =\n (ev.error && ev.error.message) || ev.message || \"unknown_error\";\n const stack =\n (ev.error && ev.error.stack) ||\n `${ev.filename ?? \"\"}:${ev.lineno ?? 0}:${ev.colno ?? 0}`;\n void report(message, stack);\n });\n window.addEventListener(\"unhandledrejection\", (ev) => {\n const reason = (ev as PromiseRejectionEvent).reason;\n const message =\n reason instanceof Error\n ? reason.message\n : typeof reason === \"string\"\n ? reason\n : \"unhandled_rejection\";\n const stack = reason instanceof Error ? reason.stack ?? \"\" : \"\";\n void report(message, stack);\n });\n}\n\n// PII scrub: strip query string and hash from any URL we forward\n// so signed-upload tokens, ?email=, ?invite=, fragment-encoded\n// session bits, etc. never leave the browser. Also caps length.\nfunction scrubUrl(raw: string): string {\n try {\n const u = new URL(raw, location.origin);\n return `${u.origin}${u.pathname}`.slice(0, 200);\n } catch {\n return raw.split(\"?\")[0].split(\"#\")[0].slice(0, 200);\n }\n}\n\nasync function report(message: string, stack: string): Promise {\n if (!configured) return;\n // Per-page de-dupe + cap so a hot-loop error doesn't DoS the\n // /v1/internal/client-error endpoint.\n if (SEEN.size >= MAX_REPORTS_PER_PAGE) return;\n const key = `${message}::${stack.slice(0, 80)}`;\n if (SEEN.has(key)) return;\n SEEN.add(key);\n\n try {\n await fetch(`${configured.apiBase}/v1/internal/client-error`, {\n method: \"POST\",\n credentials: \"include\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n message: String(message).slice(0, 500),\n stack: String(stack).slice(0, 4000),\n page: configured.page,\n url: scrubUrl(location.href),\n ts: Date.now(),\n }),\n keepalive: true,\n });\n } catch {\n // never escalate a reporter failure into another error event\n }\n}\n", "// These are filled with ranges (rangeFrom[i] up to but not including\n// rangeTo[i]) of code points that count as extending characters.\nlet rangeFrom = [], rangeTo = []\n\n;(() => {\n // Compressed representation of the Grapheme_Cluster_Break=Extend\n // information from\n // http://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.\n // Each pair of elements represents a range, as an offet from the\n // previous range and a length. Numbers are in base-36, with the empty\n // string being a shorthand for 1.\n let numbers = \"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o\".split(\",\").map(s => s ? parseInt(s, 36) : 1)\n for (let i = 0, n = 0; i < numbers.length; i++)\n (i % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i])\n})()\n\nexport function isExtendingChar(code) {\n if (code < 768) return false\n for (let from = 0, to = rangeFrom.length;;) {\n let mid = (from + to) >> 1\n if (code < rangeFrom[mid]) to = mid\n else if (code >= rangeTo[mid]) from = mid + 1\n else return true\n if (from == to) return false\n }\n}\n\nfunction isRegionalIndicator(code) {\n return code >= 0x1F1E6 && code <= 0x1F1FF\n}\n\nfunction check(code) {\n for (let i = 0; i < rangeFrom.length; i++) {\n if (rangeTo[i] > code) return rangeFrom[i] <= code\n }\n return false\n}\n\nconst ZWJ = 0x200d\n\nexport function findClusterBreak(str, pos, forward = true, includeExtending = true) {\n return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending)\n}\n\nfunction nextClusterBreak(str, pos, includeExtending) {\n if (pos == str.length) return pos\n // If pos is in the middle of a surrogate pair, move to its start\n if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--\n let prev = codePointAt(str, pos)\n pos += codePointSize(prev)\n while (pos < str.length) {\n let next = codePointAt(str, pos)\n if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {\n pos += codePointSize(next)\n prev = next\n } else if (isRegionalIndicator(next)) {\n let countBefore = 0, i = pos - 2\n while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { countBefore++; i -= 2 }\n if (countBefore % 2 == 0) break\n else pos += 2\n } else {\n break\n }\n }\n return pos\n}\n\nfunction prevClusterBreak(str, pos, includeExtending) {\n while (pos > 0) {\n let found = nextClusterBreak(str, pos - 2, includeExtending)\n if (found < pos) return found\n pos--\n }\n return 0\n}\n\nfunction codePointAt(str, pos) {\n let code0 = str.charCodeAt(pos)\n if (!surrogateHigh(code0) || pos + 1 == str.length) return code0\n let code1 = str.charCodeAt(pos + 1)\n if (!surrogateLow(code1)) return code0\n return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000\n}\n\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000 }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00 }\nfunction codePointSize(code) { return code < 0x10000 ? 1 : 2 }\n", "import { findClusterBreak as findClusterBreak$1 } from '@marijn/find-cluster-break';\n\n/**\nThe data structure for documents. @nonabstract\n*/\nclass Text {\n /**\n Get the line description around the given position.\n */\n lineAt(pos) {\n if (pos < 0 || pos > this.length)\n throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);\n return this.lineInner(pos, false, 1, 0);\n }\n /**\n Get the description for the given (1-based) line number.\n */\n line(n) {\n if (n < 1 || n > this.lines)\n throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);\n return this.lineInner(n, true, 1, 0);\n }\n /**\n Replace a range of the text with the given content.\n */\n replace(from, to, text) {\n [from, to] = clip(this, from, to);\n let parts = [];\n this.decompose(0, from, parts, 2 /* Open.To */);\n if (text.length)\n text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);\n this.decompose(to, this.length, parts, 1 /* Open.From */);\n return TextNode.from(parts, this.length - (to - from) + text.length);\n }\n /**\n Append another document to this one.\n */\n append(other) {\n return this.replace(this.length, this.length, other);\n }\n /**\n Retrieve the text between the given points.\n */\n slice(from, to = this.length) {\n [from, to] = clip(this, from, to);\n let parts = [];\n this.decompose(from, to, parts, 0);\n return TextNode.from(parts, to - from);\n }\n /**\n Test whether this text is equal to another instance.\n */\n eq(other) {\n if (other == this)\n return true;\n if (other.length != this.length || other.lines != this.lines)\n return false;\n let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);\n let a = new RawTextCursor(this), b = new RawTextCursor(other);\n for (let skip = start, pos = start;;) {\n a.next(skip);\n b.next(skip);\n skip = 0;\n if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)\n return false;\n pos += a.value.length;\n if (a.done || pos >= end)\n return true;\n }\n }\n /**\n Iterate over the text. When `dir` is `-1`, iteration happens\n from end to start. This will return lines and the breaks between\n them as separate strings.\n */\n iter(dir = 1) { return new RawTextCursor(this, dir); }\n /**\n Iterate over a range of the text. When `from` > `to`, the\n iterator will run in reverse.\n */\n iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }\n /**\n Return a cursor that iterates over the given range of lines,\n _without_ returning the line breaks between, and yielding empty\n strings for empty lines.\n \n When `from` and `to` are given, they should be 1-based line numbers.\n */\n iterLines(from, to) {\n let inner;\n if (from == null) {\n inner = this.iter();\n }\n else {\n if (to == null)\n to = this.lines + 1;\n let start = this.line(from).from;\n inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));\n }\n return new LineCursor(inner);\n }\n /**\n Return the document as a string, using newline characters to\n separate lines.\n */\n toString() { return this.sliceString(0); }\n /**\n Convert the document to an array of lines (which can be\n deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).\n */\n toJSON() {\n let lines = [];\n this.flatten(lines);\n return lines;\n }\n /**\n @internal\n */\n constructor() { }\n /**\n Create a `Text` instance for the given array of lines.\n */\n static of(text) {\n if (text.length == 0)\n throw new RangeError(\"A document must have at least one line\");\n if (text.length == 1 && !text[0])\n return Text.empty;\n return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));\n }\n}\n// Leaves store an array of line strings. There are always line breaks\n// between these strings. Leaves are limited in size and have to be\n// contained in TextNode instances for bigger documents.\nclass TextLeaf extends Text {\n constructor(text, length = textLength(text)) {\n super();\n this.text = text;\n this.length = length;\n }\n get lines() { return this.text.length; }\n get children() { return null; }\n lineInner(target, isLine, line, offset) {\n for (let i = 0;; i++) {\n let string = this.text[i], end = offset + string.length;\n if ((isLine ? line : end) >= target)\n return new Line(offset, end, line, string);\n offset = end + 1;\n line++;\n }\n }\n decompose(from, to, target, open) {\n let text = from <= 0 && to >= this.length ? this\n : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));\n if (open & 1 /* Open.From */) {\n let prev = target.pop();\n let joined = appendText(text.text, prev.text.slice(), 0, text.length);\n if (joined.length <= 32 /* Tree.Branch */) {\n target.push(new TextLeaf(joined, prev.length + text.length));\n }\n else {\n let mid = joined.length >> 1;\n target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));\n }\n }\n else {\n target.push(text);\n }\n }\n replace(from, to, text) {\n if (!(text instanceof TextLeaf))\n return super.replace(from, to, text);\n [from, to] = clip(this, from, to);\n let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);\n let newLen = this.length + text.length - (to - from);\n if (lines.length <= 32 /* Tree.Branch */)\n return new TextLeaf(lines, newLen);\n return TextNode.from(TextLeaf.split(lines, []), newLen);\n }\n sliceString(from, to = this.length, lineSep = \"\\n\") {\n [from, to] = clip(this, from, to);\n let result = \"\";\n for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {\n let line = this.text[i], end = pos + line.length;\n if (pos > from && i)\n result += lineSep;\n if (from < end && to > pos)\n result += line.slice(Math.max(0, from - pos), to - pos);\n pos = end + 1;\n }\n return result;\n }\n flatten(target) {\n for (let line of this.text)\n target.push(line);\n }\n scanIdentical() { return 0; }\n static split(text, target) {\n let part = [], len = -1;\n for (let line of text) {\n part.push(line);\n len += line.length + 1;\n if (part.length == 32 /* Tree.Branch */) {\n target.push(new TextLeaf(part, len));\n part = [];\n len = -1;\n }\n }\n if (len > -1)\n target.push(new TextLeaf(part, len));\n return target;\n }\n}\n// Nodes provide the tree structure of the `Text` type. They store a\n// number of other nodes or leaves, taking care to balance themselves\n// on changes. There are implied line breaks _between_ the children of\n// a node (but not before the first or after the last child).\nclass TextNode extends Text {\n constructor(children, length) {\n super();\n this.children = children;\n this.length = length;\n this.lines = 0;\n for (let child of children)\n this.lines += child.lines;\n }\n lineInner(target, isLine, line, offset) {\n for (let i = 0;; i++) {\n let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;\n if ((isLine ? endLine : end) >= target)\n return child.lineInner(target, isLine, line, offset);\n offset = end + 1;\n line = endLine + 1;\n }\n }\n decompose(from, to, target, open) {\n for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n if (from <= end && to >= pos) {\n let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));\n if (pos >= from && end <= to && !childOpen)\n target.push(child);\n else\n child.decompose(from - pos, to - pos, target, childOpen);\n }\n pos = end + 1;\n }\n }\n replace(from, to, text) {\n [from, to] = clip(this, from, to);\n if (text.lines < this.lines)\n for (let i = 0, pos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n // Fast path: if the change only affects one child and the\n // child's size remains in the acceptable range, only update\n // that child\n if (from >= pos && to <= end) {\n let updated = child.replace(from - pos, to - pos, text);\n let totalLines = this.lines - child.lines + updated.lines;\n if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&\n updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {\n let copy = this.children.slice();\n copy[i] = updated;\n return new TextNode(copy, this.length - (to - from) + text.length);\n }\n return super.replace(pos, end, updated);\n }\n pos = end + 1;\n }\n return super.replace(from, to, text);\n }\n sliceString(from, to = this.length, lineSep = \"\\n\") {\n [from, to] = clip(this, from, to);\n let result = \"\";\n for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {\n let child = this.children[i], end = pos + child.length;\n if (pos > from && i)\n result += lineSep;\n if (from < end && to > pos)\n result += child.sliceString(from - pos, to - pos, lineSep);\n pos = end + 1;\n }\n return result;\n }\n flatten(target) {\n for (let child of this.children)\n child.flatten(target);\n }\n scanIdentical(other, dir) {\n if (!(other instanceof TextNode))\n return 0;\n let length = 0;\n let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]\n : [this.children.length - 1, other.children.length - 1, -1, -1];\n for (;; iA += dir, iB += dir) {\n if (iA == eA || iB == eB)\n return length;\n let chA = this.children[iA], chB = other.children[iB];\n if (chA != chB)\n return length + chA.scanIdentical(chB, dir);\n length += chA.length + 1;\n }\n }\n static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {\n let lines = 0;\n for (let ch of children)\n lines += ch.lines;\n if (lines < 32 /* Tree.Branch */) {\n let flat = [];\n for (let ch of children)\n ch.flatten(flat);\n return new TextLeaf(flat, length);\n }\n let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;\n let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];\n function add(child) {\n let last;\n if (child.lines > maxChunk && child instanceof TextNode) {\n for (let node of child.children)\n add(node);\n }\n else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {\n flush();\n chunked.push(child);\n }\n else if (child instanceof TextLeaf && currentLines &&\n (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&\n child.lines + last.lines <= 32 /* Tree.Branch */) {\n currentLines += child.lines;\n currentLen += child.length + 1;\n currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);\n }\n else {\n if (currentLines + child.lines > chunk)\n flush();\n currentLines += child.lines;\n currentLen += child.length + 1;\n currentChunk.push(child);\n }\n }\n function flush() {\n if (currentLines == 0)\n return;\n chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));\n currentLen = -1;\n currentLines = currentChunk.length = 0;\n }\n for (let child of children)\n add(child);\n flush();\n return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);\n }\n}\nText.empty = /*@__PURE__*/new TextLeaf([\"\"], 0);\nfunction textLength(text) {\n let length = -1;\n for (let line of text)\n length += line.length + 1;\n return length;\n}\nfunction appendText(text, target, from = 0, to = 1e9) {\n for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {\n let line = text[i], end = pos + line.length;\n if (end >= from) {\n if (end > to)\n line = line.slice(0, to - pos);\n if (pos < from)\n line = line.slice(from - pos);\n if (first) {\n target[target.length - 1] += line;\n first = false;\n }\n else\n target.push(line);\n }\n pos = end + 1;\n }\n return target;\n}\nfunction sliceText(text, from, to) {\n return appendText(text, [\"\"], from, to);\n}\nclass RawTextCursor {\n constructor(text, dir = 1) {\n this.dir = dir;\n this.done = false;\n this.lineBreak = false;\n this.value = \"\";\n this.nodes = [text];\n this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];\n }\n nextInner(skip, dir) {\n this.done = this.lineBreak = false;\n for (;;) {\n let last = this.nodes.length - 1;\n let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;\n let size = top instanceof TextLeaf ? top.text.length : top.children.length;\n if (offset == (dir > 0 ? size : 0)) {\n if (last == 0) {\n this.done = true;\n this.value = \"\";\n return this;\n }\n if (dir > 0)\n this.offsets[last - 1]++;\n this.nodes.pop();\n this.offsets.pop();\n }\n else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {\n this.offsets[last] += dir;\n if (skip == 0) {\n this.lineBreak = true;\n this.value = \"\\n\";\n return this;\n }\n skip--;\n }\n else if (top instanceof TextLeaf) {\n // Move to the next string\n let next = top.text[offset + (dir < 0 ? -1 : 0)];\n this.offsets[last] += dir;\n if (next.length > Math.max(0, skip)) {\n this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);\n return this;\n }\n skip -= next.length;\n }\n else {\n let next = top.children[offset + (dir < 0 ? -1 : 0)];\n if (skip > next.length) {\n skip -= next.length;\n this.offsets[last] += dir;\n }\n else {\n if (dir < 0)\n this.offsets[last]--;\n this.nodes.push(next);\n this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);\n }\n }\n }\n }\n next(skip = 0) {\n if (skip < 0) {\n this.nextInner(-skip, (-this.dir));\n skip = this.value.length;\n }\n return this.nextInner(skip, this.dir);\n }\n}\nclass PartialTextCursor {\n constructor(text, start, end) {\n this.value = \"\";\n this.done = false;\n this.cursor = new RawTextCursor(text, start > end ? -1 : 1);\n this.pos = start > end ? text.length : 0;\n this.from = Math.min(start, end);\n this.to = Math.max(start, end);\n }\n nextInner(skip, dir) {\n if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {\n this.value = \"\";\n this.done = true;\n return this;\n }\n skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);\n let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;\n if (skip > limit)\n skip = limit;\n limit -= skip;\n let { value } = this.cursor.next(skip);\n this.pos += (value.length + skip) * dir;\n this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);\n this.done = !this.value;\n return this;\n }\n next(skip = 0) {\n if (skip < 0)\n skip = Math.max(skip, this.from - this.pos);\n else if (skip > 0)\n skip = Math.min(skip, this.to - this.pos);\n return this.nextInner(skip, this.cursor.dir);\n }\n get lineBreak() { return this.cursor.lineBreak && this.value != \"\"; }\n}\nclass LineCursor {\n constructor(inner) {\n this.inner = inner;\n this.afterBreak = true;\n this.value = \"\";\n this.done = false;\n }\n next(skip = 0) {\n let { done, lineBreak, value } = this.inner.next(skip);\n if (done && this.afterBreak) {\n this.value = \"\";\n this.afterBreak = false;\n }\n else if (done) {\n this.done = true;\n this.value = \"\";\n }\n else if (lineBreak) {\n if (this.afterBreak) {\n this.value = \"\";\n }\n else {\n this.afterBreak = true;\n this.next();\n }\n }\n else {\n this.value = value;\n this.afterBreak = false;\n }\n return this;\n }\n get lineBreak() { return false; }\n}\nif (typeof Symbol != \"undefined\") {\n Text.prototype[Symbol.iterator] = function () { return this.iter(); };\n RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =\n LineCursor.prototype[Symbol.iterator] = function () { return this; };\n}\n/**\nThis type describes a line in the document. It is created\non-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).\n*/\nclass Line {\n /**\n @internal\n */\n constructor(\n /**\n The position of the start of the line.\n */\n from, \n /**\n The position at the end of the line (_before_ the line break,\n or at the end of document for the last line).\n */\n to, \n /**\n This line's line number (1-based).\n */\n number, \n /**\n The line's content.\n */\n text) {\n this.from = from;\n this.to = to;\n this.number = number;\n this.text = text;\n }\n /**\n The length of the line (not including any line break after it).\n */\n get length() { return this.to - this.from; }\n}\nfunction clip(text, from, to) {\n from = Math.max(0, Math.min(text.length, from));\n return [from, Math.max(from, Math.min(text.length, to))];\n}\n\n/**\nReturns a next grapheme cluster break _after_ (not equal to)\n`pos`, if `forward` is true, or before otherwise. Returns `pos`\nitself if no further cluster break is available in the string.\nMoves across surrogate pairs, extending characters (when\n`includeExtending` is true), characters joined with zero-width\njoiners, and flag emoji.\n*/\nfunction findClusterBreak(str, pos, forward = true, includeExtending = true) {\n return findClusterBreak$1(str, pos, forward, includeExtending);\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n/**\nFind the code point at the given position in a string (like the\n[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)\nstring method).\n*/\nfunction codePointAt(str, pos) {\n let code0 = str.charCodeAt(pos);\n if (!surrogateHigh(code0) || pos + 1 == str.length)\n return code0;\n let code1 = str.charCodeAt(pos + 1);\n if (!surrogateLow(code1))\n return code0;\n return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;\n}\n/**\nGiven a Unicode codepoint, return the JavaScript string that\nrespresents it (like\n[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).\n*/\nfunction fromCodePoint(code) {\n if (code <= 0xffff)\n return String.fromCharCode(code);\n code -= 0x10000;\n return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);\n}\n/**\nThe amount of positions a character takes up in a JavaScript string.\n*/\nfunction codePointSize(code) { return code < 0x10000 ? 1 : 2; }\n\nconst DefaultSplit = /\\r\\n?|\\n/;\n/**\nDistinguishes different ways in which positions can be mapped.\n*/\nvar MapMode = /*@__PURE__*/(function (MapMode) {\n /**\n Map a position to a valid new position, even when its context\n was deleted.\n */\n MapMode[MapMode[\"Simple\"] = 0] = \"Simple\";\n /**\n Return null if deletion happens across the position.\n */\n MapMode[MapMode[\"TrackDel\"] = 1] = \"TrackDel\";\n /**\n Return null if the character _before_ the position is deleted.\n */\n MapMode[MapMode[\"TrackBefore\"] = 2] = \"TrackBefore\";\n /**\n Return null if the character _after_ the position is deleted.\n */\n MapMode[MapMode[\"TrackAfter\"] = 3] = \"TrackAfter\";\nreturn MapMode})(MapMode || (MapMode = {}));\n/**\nA change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)\nthat doesn't store the inserted text. As such, it can't be\napplied, but is cheaper to store and manipulate.\n*/\nclass ChangeDesc {\n // Sections are encoded as pairs of integers. The first is the\n // length in the current document, and the second is -1 for\n // unaffected sections, and the length of the replacement content\n // otherwise. So an insertion would be (0, n>0), a deletion (n>0,\n // 0), and a replacement two positive numbers.\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n sections) {\n this.sections = sections;\n }\n /**\n The length of the document before the change.\n */\n get length() {\n let result = 0;\n for (let i = 0; i < this.sections.length; i += 2)\n result += this.sections[i];\n return result;\n }\n /**\n The length of the document after the change.\n */\n get newLength() {\n let result = 0;\n for (let i = 0; i < this.sections.length; i += 2) {\n let ins = this.sections[i + 1];\n result += ins < 0 ? this.sections[i] : ins;\n }\n return result;\n }\n /**\n False when there are actual changes in this set.\n */\n get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }\n /**\n Iterate over the unchanged parts left by these changes. `posA`\n provides the position of the range in the old document, `posB`\n the new position in the changed document.\n */\n iterGaps(f) {\n for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0) {\n f(posA, posB, len);\n posB += len;\n }\n else {\n posB += ins;\n }\n posA += len;\n }\n }\n /**\n Iterate over the ranges changed by these changes. (See\n [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a\n variant that also provides you with the inserted text.)\n `fromA`/`toA` provides the extent of the change in the starting\n document, `fromB`/`toB` the extent of the replacement in the\n changed document.\n \n When `individual` is true, adjacent changes (which are kept\n separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are\n reported separately.\n */\n iterChangedRanges(f, individual = false) {\n iterChanges(this, f, individual);\n }\n /**\n Get a description of the inverted form of these changes.\n */\n get invertedDesc() {\n let sections = [];\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0)\n sections.push(len, ins);\n else\n sections.push(ins, len);\n }\n return new ChangeDesc(sections);\n }\n /**\n Compute the combined effect of applying another set of changes\n after this one. The length of the document after this set should\n match the length before `other`.\n */\n composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }\n /**\n Map this description, which should start with the same document\n as `other`, over another set of changes, so that it can be\n applied after it. When `before` is true, map as if the changes\n in `this` happened before the ones in `other`.\n */\n mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }\n mapPos(pos, assoc = -1, mode = MapMode.Simple) {\n let posA = 0, posB = 0;\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;\n if (ins < 0) {\n if (endA > pos)\n return posB + (pos - posA);\n posB += len;\n }\n else {\n if (mode != MapMode.Simple && endA >= pos &&\n (mode == MapMode.TrackDel && posA < pos && endA > pos ||\n mode == MapMode.TrackBefore && posA < pos ||\n mode == MapMode.TrackAfter && endA > pos))\n return null;\n if (endA > pos || endA == pos && assoc < 0 && !len)\n return pos == posA || assoc < 0 ? posB : posB + ins;\n posB += ins;\n }\n posA = endA;\n }\n if (pos > posA)\n throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);\n return posB;\n }\n /**\n Check whether these changes touch a given range. When one of the\n changes entirely covers the range, the string `\"cover\"` is\n returned.\n */\n touchesRange(from, to = from) {\n for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {\n let len = this.sections[i++], ins = this.sections[i++], end = pos + len;\n if (ins >= 0 && pos <= to && end >= from)\n return pos < from && end > to ? \"cover\" : true;\n pos = end;\n }\n return false;\n }\n /**\n @internal\n */\n toString() {\n let result = \"\";\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n result += (result ? \" \" : \"\") + len + (ins >= 0 ? \":\" + ins : \"\");\n }\n return result;\n }\n /**\n Serialize this change desc to a JSON-representable value.\n */\n toJSON() { return this.sections; }\n /**\n Create a change desc from its JSON representation (as produced\n by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).\n */\n static fromJSON(json) {\n if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != \"number\"))\n throw new RangeError(\"Invalid JSON representation of ChangeDesc\");\n return new ChangeDesc(json);\n }\n /**\n @internal\n */\n static create(sections) { return new ChangeDesc(sections); }\n}\n/**\nA change set represents a group of modifications to a document. It\nstores the document length, and can only be applied to documents\nwith exactly that length.\n*/\nclass ChangeSet extends ChangeDesc {\n constructor(sections, \n /**\n @internal\n */\n inserted) {\n super(sections);\n this.inserted = inserted;\n }\n /**\n Apply the changes to a document, returning the modified\n document.\n */\n apply(doc) {\n if (this.length != doc.length)\n throw new RangeError(\"Applying change set to a document with the wrong length\");\n iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);\n return doc;\n }\n mapDesc(other, before = false) { return mapSet(this, other, before, true); }\n /**\n Given the document as it existed _before_ the changes, return a\n change set that represents the inverse of this set, which could\n be used to go from the document created by the changes back to\n the document as it existed before the changes.\n */\n invert(doc) {\n let sections = this.sections.slice(), inserted = [];\n for (let i = 0, pos = 0; i < sections.length; i += 2) {\n let len = sections[i], ins = sections[i + 1];\n if (ins >= 0) {\n sections[i] = ins;\n sections[i + 1] = len;\n let index = i >> 1;\n while (inserted.length < index)\n inserted.push(Text.empty);\n inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);\n }\n pos += len;\n }\n return new ChangeSet(sections, inserted);\n }\n /**\n Combine two subsequent change sets into a single set. `other`\n must start in the document produced by `this`. If `this` goes\n `docA` \u2192 `docB` and `other` represents `docB` \u2192 `docC`, the\n returned value will represent the change `docA` \u2192 `docC`.\n */\n compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }\n /**\n Given another change set starting in the same document, maps this\n change set over the other, producing a new change set that can be\n applied to the document produced by applying `other`. When\n `before` is `true`, order changes as if `this` comes before\n `other`, otherwise (the default) treat `other` as coming first.\n \n Given two changes `A` and `B`, `A.compose(B.map(A))` and\n `B.compose(A.map(B, true))` will produce the same document. This\n provides a basic form of [operational\n transformation](https://en.wikipedia.org/wiki/Operational_transformation),\n and can be used for collaborative editing.\n */\n map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }\n /**\n Iterate over the changed ranges in the document, calling `f` for\n each, with the range in the original document (`fromA`-`toA`)\n and the range that replaces it in the new document\n (`fromB`-`toB`).\n \n When `individual` is true, adjacent changes are reported\n separately.\n */\n iterChanges(f, individual = false) {\n iterChanges(this, f, individual);\n }\n /**\n Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change\n set.\n */\n get desc() { return ChangeDesc.create(this.sections); }\n /**\n @internal\n */\n filter(ranges) {\n let resultSections = [], resultInserted = [], filteredSections = [];\n let iter = new SectionIter(this);\n done: for (let i = 0, pos = 0;;) {\n let next = i == ranges.length ? 1e9 : ranges[i++];\n while (pos < next || pos == next && iter.len == 0) {\n if (iter.done)\n break done;\n let len = Math.min(iter.len, next - pos);\n addSection(filteredSections, len, -1);\n let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;\n addSection(resultSections, len, ins);\n if (ins > 0)\n addInsert(resultInserted, resultSections, iter.text);\n iter.forward(len);\n pos += len;\n }\n let end = ranges[i++];\n while (pos < end) {\n if (iter.done)\n break done;\n let len = Math.min(iter.len, end - pos);\n addSection(resultSections, len, -1);\n addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);\n iter.forward(len);\n pos += len;\n }\n }\n return { changes: new ChangeSet(resultSections, resultInserted),\n filtered: ChangeDesc.create(filteredSections) };\n }\n /**\n Serialize this change set to a JSON-representable value.\n */\n toJSON() {\n let parts = [];\n for (let i = 0; i < this.sections.length; i += 2) {\n let len = this.sections[i], ins = this.sections[i + 1];\n if (ins < 0)\n parts.push(len);\n else if (ins == 0)\n parts.push([len]);\n else\n parts.push([len].concat(this.inserted[i >> 1].toJSON()));\n }\n return parts;\n }\n /**\n Create a change set for the given changes, for a document of the\n given length, using `lineSep` as line separator.\n */\n static of(changes, length, lineSep) {\n let sections = [], inserted = [], pos = 0;\n let total = null;\n function flush(force = false) {\n if (!force && !sections.length)\n return;\n if (pos < length)\n addSection(sections, length - pos, -1);\n let set = new ChangeSet(sections, inserted);\n total = total ? total.compose(set.map(total)) : set;\n sections = [];\n inserted = [];\n pos = 0;\n }\n function process(spec) {\n if (Array.isArray(spec)) {\n for (let sub of spec)\n process(sub);\n }\n else if (spec instanceof ChangeSet) {\n if (spec.length != length)\n throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);\n flush();\n total = total ? total.compose(spec.map(total)) : spec;\n }\n else {\n let { from, to = from, insert } = spec;\n if (from > to || from < 0 || to > length)\n throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);\n let insText = !insert ? Text.empty : typeof insert == \"string\" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;\n let insLen = insText.length;\n if (from == to && insLen == 0)\n return;\n if (from < pos)\n flush();\n if (from > pos)\n addSection(sections, from - pos, -1);\n addSection(sections, to - from, insLen);\n addInsert(inserted, sections, insText);\n pos = to;\n }\n }\n process(changes);\n flush(!total);\n return total;\n }\n /**\n Create an empty changeset of the given length.\n */\n static empty(length) {\n return new ChangeSet(length ? [length, -1] : [], []);\n }\n /**\n Create a changeset from its JSON representation (as produced by\n [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).\n */\n static fromJSON(json) {\n if (!Array.isArray(json))\n throw new RangeError(\"Invalid JSON representation of ChangeSet\");\n let sections = [], inserted = [];\n for (let i = 0; i < json.length; i++) {\n let part = json[i];\n if (typeof part == \"number\") {\n sections.push(part, -1);\n }\n else if (!Array.isArray(part) || typeof part[0] != \"number\" || part.some((e, i) => i && typeof e != \"string\")) {\n throw new RangeError(\"Invalid JSON representation of ChangeSet\");\n }\n else if (part.length == 1) {\n sections.push(part[0], 0);\n }\n else {\n while (inserted.length < i)\n inserted.push(Text.empty);\n inserted[i] = Text.of(part.slice(1));\n sections.push(part[0], inserted[i].length);\n }\n }\n return new ChangeSet(sections, inserted);\n }\n /**\n @internal\n */\n static createSet(sections, inserted) {\n return new ChangeSet(sections, inserted);\n }\n}\nfunction addSection(sections, len, ins, forceJoin = false) {\n if (len == 0 && ins <= 0)\n return;\n let last = sections.length - 2;\n if (last >= 0 && ins <= 0 && ins == sections[last + 1])\n sections[last] += len;\n else if (last >= 0 && len == 0 && sections[last] == 0)\n sections[last + 1] += ins;\n else if (forceJoin) {\n sections[last] += len;\n sections[last + 1] += ins;\n }\n else\n sections.push(len, ins);\n}\nfunction addInsert(values, sections, value) {\n if (value.length == 0)\n return;\n let index = (sections.length - 2) >> 1;\n if (index < values.length) {\n values[values.length - 1] = values[values.length - 1].append(value);\n }\n else {\n while (values.length < index)\n values.push(Text.empty);\n values.push(value);\n }\n}\nfunction iterChanges(desc, f, individual) {\n let inserted = desc.inserted;\n for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {\n let len = desc.sections[i++], ins = desc.sections[i++];\n if (ins < 0) {\n posA += len;\n posB += len;\n }\n else {\n let endA = posA, endB = posB, text = Text.empty;\n for (;;) {\n endA += len;\n endB += ins;\n if (ins && inserted)\n text = text.append(inserted[(i - 2) >> 1]);\n if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)\n break;\n len = desc.sections[i++];\n ins = desc.sections[i++];\n }\n f(posA, endA, posB, endB, text);\n posA = endA;\n posB = endB;\n }\n }\n}\nfunction mapSet(setA, setB, before, mkSet = false) {\n // Produce a copy of setA that applies to the document after setB\n // has been applied (assuming both start at the same document).\n let sections = [], insert = mkSet ? [] : null;\n let a = new SectionIter(setA), b = new SectionIter(setB);\n // Iterate over both sets in parallel. inserted tracks, for changes\n // in A that have to be processed piece-by-piece, whether their\n // content has been inserted already, and refers to the section\n // index.\n for (let inserted = -1;;) {\n if (a.done && b.len || b.done && a.len) {\n throw new Error(\"Mismatched change set lengths\");\n }\n else if (a.ins == -1 && b.ins == -1) {\n // Move across ranges skipped by both sets.\n let len = Math.min(a.len, b.len);\n addSection(sections, len, -1);\n a.forward(len);\n b.forward(len);\n }\n else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {\n // If there's a change in B that comes before the next change in\n // A (ordered by start pos, then len, then before flag), skip\n // that (and process any changes in A it covers).\n let len = b.len;\n addSection(sections, b.ins, -1);\n while (len) {\n let piece = Math.min(a.len, len);\n if (a.ins >= 0 && inserted < a.i && a.len <= piece) {\n addSection(sections, 0, a.ins);\n if (insert)\n addInsert(insert, sections, a.text);\n inserted = a.i;\n }\n a.forward(piece);\n len -= piece;\n }\n b.next();\n }\n else if (a.ins >= 0) {\n // Process the part of a change in A up to the start of the next\n // non-deletion change in B (if overlapping).\n let len = 0, left = a.len;\n while (left) {\n if (b.ins == -1) {\n let piece = Math.min(left, b.len);\n len += piece;\n left -= piece;\n b.forward(piece);\n }\n else if (b.ins == 0 && b.len < left) {\n left -= b.len;\n b.next();\n }\n else {\n break;\n }\n }\n addSection(sections, len, inserted < a.i ? a.ins : 0);\n if (insert && inserted < a.i)\n addInsert(insert, sections, a.text);\n inserted = a.i;\n a.forward(a.len - left);\n }\n else if (a.done && b.done) {\n return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);\n }\n else {\n throw new Error(\"Mismatched change set lengths\");\n }\n }\n}\nfunction composeSets(setA, setB, mkSet = false) {\n let sections = [];\n let insert = mkSet ? [] : null;\n let a = new SectionIter(setA), b = new SectionIter(setB);\n for (let open = false;;) {\n if (a.done && b.done) {\n return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);\n }\n else if (a.ins == 0) { // Deletion in A\n addSection(sections, a.len, 0, open);\n a.next();\n }\n else if (b.len == 0 && !b.done) { // Insertion in B\n addSection(sections, 0, b.ins, open);\n if (insert)\n addInsert(insert, sections, b.text);\n b.next();\n }\n else if (a.done || b.done) {\n throw new Error(\"Mismatched change set lengths\");\n }\n else {\n let len = Math.min(a.len2, b.len), sectionLen = sections.length;\n if (a.ins == -1) {\n let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;\n addSection(sections, len, insB, open);\n if (insert && insB)\n addInsert(insert, sections, b.text);\n }\n else if (b.ins == -1) {\n addSection(sections, a.off ? 0 : a.len, len, open);\n if (insert)\n addInsert(insert, sections, a.textBit(len));\n }\n else {\n addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);\n if (insert && !b.off)\n addInsert(insert, sections, b.text);\n }\n open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);\n a.forward2(len);\n b.forward(len);\n }\n }\n}\nclass SectionIter {\n constructor(set) {\n this.set = set;\n this.i = 0;\n this.next();\n }\n next() {\n let { sections } = this.set;\n if (this.i < sections.length) {\n this.len = sections[this.i++];\n this.ins = sections[this.i++];\n }\n else {\n this.len = 0;\n this.ins = -2;\n }\n this.off = 0;\n }\n get done() { return this.ins == -2; }\n get len2() { return this.ins < 0 ? this.len : this.ins; }\n get text() {\n let { inserted } = this.set, index = (this.i - 2) >> 1;\n return index >= inserted.length ? Text.empty : inserted[index];\n }\n textBit(len) {\n let { inserted } = this.set, index = (this.i - 2) >> 1;\n return index >= inserted.length && !len ? Text.empty\n : inserted[index].slice(this.off, len == null ? undefined : this.off + len);\n }\n forward(len) {\n if (len == this.len)\n this.next();\n else {\n this.len -= len;\n this.off += len;\n }\n }\n forward2(len) {\n if (this.ins == -1)\n this.forward(len);\n else if (len == this.ins)\n this.next();\n else {\n this.ins -= len;\n this.off += len;\n }\n }\n}\n\n/**\nA single selection range. When\n[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)\nis enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold\nmultiple ranges. By default, selections hold exactly one range.\n*/\nclass SelectionRange {\n constructor(\n /**\n The lower boundary of the range.\n */\n from, \n /**\n The upper boundary of the range.\n */\n to, flags) {\n this.from = from;\n this.to = to;\n this.flags = flags;\n }\n /**\n The anchor of the range\u2014the side that doesn't move when you\n extend it.\n */\n get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }\n /**\n The head of the range, which is moved when the range is\n [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).\n */\n get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }\n /**\n True when `anchor` and `head` are at the same position.\n */\n get empty() { return this.from == this.to; }\n /**\n If this is a cursor that is explicitly associated with the\n character on one of its sides, this returns the side. -1 means\n the character before its position, 1 the character after, and 0\n means no association.\n */\n get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }\n /**\n The bidirectional text level associated with this cursor, if\n any.\n */\n get bidiLevel() {\n let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;\n return level == 7 ? null : level;\n }\n /**\n The goal column (stored vertical offset) associated with a\n cursor. This is used to preserve the vertical position when\n [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across\n lines of different length.\n */\n get goalColumn() {\n let value = this.flags >> 6 /* RangeFlag.GoalColumnOffset */;\n return value == 16777215 /* RangeFlag.NoGoalColumn */ ? undefined : value;\n }\n /**\n Map this range through a change, producing a valid range in the\n updated document.\n */\n map(change, assoc = -1) {\n let from, to;\n if (this.empty) {\n from = to = change.mapPos(this.from, assoc);\n }\n else {\n from = change.mapPos(this.from, 1);\n to = change.mapPos(this.to, -1);\n }\n return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);\n }\n /**\n Extend this range to cover at least `from` to `to`.\n */\n extend(from, to = from, assoc = 0) {\n if (from <= this.anchor && to >= this.anchor)\n return EditorSelection.range(from, to, undefined, undefined, assoc);\n let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;\n return EditorSelection.range(this.anchor, head, undefined, undefined, assoc);\n }\n /**\n Compare this range to another range.\n */\n eq(other, includeAssoc = false) {\n return this.anchor == other.anchor && this.head == other.head && this.goalColumn == other.goalColumn &&\n (!includeAssoc || !this.empty || this.assoc == other.assoc);\n }\n /**\n Return a JSON-serializable object representing the range.\n */\n toJSON() { return { anchor: this.anchor, head: this.head }; }\n /**\n Convert a JSON representation of a range to a `SelectionRange`\n instance.\n */\n static fromJSON(json) {\n if (!json || typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid JSON representation for SelectionRange\");\n return EditorSelection.range(json.anchor, json.head);\n }\n /**\n @internal\n */\n static create(from, to, flags) {\n return new SelectionRange(from, to, flags);\n }\n}\n/**\nAn editor selection holds one or more selection ranges.\n*/\nclass EditorSelection {\n constructor(\n /**\n The ranges in the selection, sorted by position. Ranges cannot\n overlap (but they may touch, if they aren't empty).\n */\n ranges, \n /**\n The index of the _main_ range in the selection (which is\n usually the range that was added last).\n */\n mainIndex) {\n this.ranges = ranges;\n this.mainIndex = mainIndex;\n }\n /**\n Map a selection through a change. Used to adjust the selection\n position for changes.\n */\n map(change, assoc = -1) {\n if (change.empty)\n return this;\n return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);\n }\n /**\n Compare this selection to another selection. By default, ranges\n are compared only by position. When `includeAssoc` is true,\n cursor ranges must also have the same\n [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.\n */\n eq(other, includeAssoc = false) {\n if (this.ranges.length != other.ranges.length ||\n this.mainIndex != other.mainIndex)\n return false;\n for (let i = 0; i < this.ranges.length; i++)\n if (!this.ranges[i].eq(other.ranges[i], includeAssoc))\n return false;\n return true;\n }\n /**\n Get the primary selection range. Usually, you should make sure\n your code applies to _all_ ranges, by using methods like\n [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).\n */\n get main() { return this.ranges[this.mainIndex]; }\n /**\n Make sure the selection only has one range. Returns a selection\n holding only the main range from this selection.\n */\n asSingle() {\n return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);\n }\n /**\n Extend this selection with an extra range.\n */\n addRange(range, main = true) {\n return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);\n }\n /**\n Replace a given range with another range, and then normalize the\n selection to merge and sort ranges if necessary.\n */\n replaceRange(range, which = this.mainIndex) {\n let ranges = this.ranges.slice();\n ranges[which] = range;\n return EditorSelection.create(ranges, this.mainIndex);\n }\n /**\n Convert this selection to an object that can be serialized to\n JSON.\n */\n toJSON() {\n return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };\n }\n /**\n Create a selection from a JSON representation.\n */\n static fromJSON(json) {\n if (!json || !Array.isArray(json.ranges) || typeof json.main != \"number\" || json.main >= json.ranges.length)\n throw new RangeError(\"Invalid JSON representation for EditorSelection\");\n return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);\n }\n /**\n Create a selection holding a single range.\n */\n static single(anchor, head = anchor) {\n return new EditorSelection([EditorSelection.range(anchor, head)], 0);\n }\n /**\n Sort and merge the given set of ranges, creating a valid\n selection.\n */\n static create(ranges, mainIndex = 0) {\n if (ranges.length == 0)\n throw new RangeError(\"A selection needs at least one range\");\n for (let pos = 0, i = 0; i < ranges.length; i++) {\n let range = ranges[i];\n if (range.empty ? range.from <= pos : range.from < pos)\n return EditorSelection.normalized(ranges.slice(), mainIndex);\n pos = range.to;\n }\n return new EditorSelection(ranges, mainIndex);\n }\n /**\n Create a cursor selection range at the given position. You can\n safely ignore the optional arguments in most situations.\n */\n static cursor(pos, assoc = 0, bidiLevel, goalColumn) {\n return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |\n (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) |\n ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */));\n }\n /**\n Create a selection range.\n */\n static range(anchor, head, goalColumn, bidiLevel, assoc) {\n let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */) |\n (bidiLevel == null ? 7 : Math.min(6, bidiLevel));\n if (!assoc && anchor != head)\n assoc = head < anchor ? 1 : -1;\n return head < anchor ? SelectionRange.create(head, anchor, 32 /* RangeFlag.Inverted */ | 16 /* RangeFlag.AssocAfter */ | flags)\n : SelectionRange.create(anchor, head, (!assoc ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) | flags);\n }\n /**\n @internal\n */\n static normalized(ranges, mainIndex = 0) {\n let main = ranges[mainIndex];\n ranges.sort((a, b) => a.from - b.from);\n mainIndex = ranges.indexOf(main);\n for (let i = 1; i < ranges.length; i++) {\n let range = ranges[i], prev = ranges[i - 1];\n if (range.empty ? range.from <= prev.to : range.from < prev.to) {\n let from = prev.from, to = Math.max(range.to, prev.to);\n if (i <= mainIndex)\n mainIndex--;\n ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));\n }\n }\n return new EditorSelection(ranges, mainIndex);\n }\n}\nfunction checkSelection(selection, docLength) {\n for (let range of selection.ranges)\n if (range.to > docLength)\n throw new RangeError(\"Selection points outside of document\");\n}\n\nlet nextID = 0;\n/**\nA facet is a labeled value that is associated with an editor\nstate. It takes inputs from any number of extensions, and combines\nthose into a single output value.\n\nExamples of uses of facets are the [tab\nsize](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor\nattributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update\nlisteners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).\n\nNote that `Facet` instances can be used anywhere where\n[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.\n*/\nclass Facet {\n constructor(\n /**\n @internal\n */\n combine, \n /**\n @internal\n */\n compareInput, \n /**\n @internal\n */\n compare, isStatic, enables) {\n this.combine = combine;\n this.compareInput = compareInput;\n this.compare = compare;\n this.isStatic = isStatic;\n /**\n @internal\n */\n this.id = nextID++;\n this.default = combine([]);\n this.extensions = typeof enables == \"function\" ? enables(this) : enables;\n }\n /**\n Returns a facet reader for this facet, which can be used to\n [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.\n */\n get reader() { return this; }\n /**\n Define a new facet.\n */\n static define(config = {}) {\n return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables);\n }\n /**\n Returns an extension that adds the given value to this facet.\n */\n of(value) {\n return new FacetProvider([], this, 0 /* Provider.Static */, value);\n }\n /**\n Create an extension that computes a value for the facet from a\n state. You must take care to declare the parts of the state that\n this value depends on, since your function is only called again\n for a new state when one of those parts changed.\n \n In cases where your value depends only on a single field, you'll\n want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.\n */\n compute(deps, get) {\n if (this.isStatic)\n throw new Error(\"Can't compute a static facet\");\n return new FacetProvider(deps, this, 1 /* Provider.Single */, get);\n }\n /**\n Create an extension that computes zero or more values for this\n facet from a state.\n */\n computeN(deps, get) {\n if (this.isStatic)\n throw new Error(\"Can't compute a static facet\");\n return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);\n }\n from(field, get) {\n if (!get)\n get = x => x;\n return this.compute([field], state => get(state.field(field)));\n }\n}\nfunction sameArray(a, b) {\n return a == b || a.length == b.length && a.every((e, i) => e === b[i]);\n}\nclass FacetProvider {\n constructor(dependencies, facet, type, value) {\n this.dependencies = dependencies;\n this.facet = facet;\n this.type = type;\n this.value = value;\n this.id = nextID++;\n }\n dynamicSlot(addresses) {\n var _a;\n let getter = this.value;\n let compare = this.facet.compareInput;\n let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;\n let depDoc = false, depSel = false, depAddrs = [];\n for (let dep of this.dependencies) {\n if (dep == \"doc\")\n depDoc = true;\n else if (dep == \"selection\")\n depSel = true;\n else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)\n depAddrs.push(addresses[dep.id]);\n }\n return {\n create(state) {\n state.values[idx] = getter(state);\n return 1 /* SlotStatus.Changed */;\n },\n update(state, tr) {\n if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {\n let newVal = getter(state);\n if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {\n state.values[idx] = newVal;\n return 1 /* SlotStatus.Changed */;\n }\n }\n return 0;\n },\n reconfigure: (state, oldState) => {\n let newVal, oldAddr = oldState.config.address[id];\n if (oldAddr != null) {\n let oldVal = getAddr(oldState, oldAddr);\n if (this.dependencies.every(dep => {\n return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :\n dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;\n }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {\n state.values[idx] = oldVal;\n return 0;\n }\n }\n else {\n newVal = getter(state);\n }\n state.values[idx] = newVal;\n return 1 /* SlotStatus.Changed */;\n }\n };\n }\n}\nfunction compareArray(a, b, compare) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compare(a[i], b[i]))\n return false;\n return true;\n}\nfunction ensureAll(state, addrs) {\n let changed = false;\n for (let addr of addrs)\n if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)\n changed = true;\n return changed;\n}\nfunction dynamicFacetSlot(addresses, facet, providers) {\n let providerAddrs = providers.map(p => addresses[p.id]);\n let providerTypes = providers.map(p => p.type);\n let dynamic = providerAddrs.filter(p => !(p & 1));\n let idx = addresses[facet.id] >> 1;\n function get(state) {\n let values = [];\n for (let i = 0; i < providerAddrs.length; i++) {\n let value = getAddr(state, providerAddrs[i]);\n if (providerTypes[i] == 2 /* Provider.Multi */)\n for (let val of value)\n values.push(val);\n else\n values.push(value);\n }\n return facet.combine(values);\n }\n return {\n create(state) {\n for (let addr of providerAddrs)\n ensureAddr(state, addr);\n state.values[idx] = get(state);\n return 1 /* SlotStatus.Changed */;\n },\n update(state, tr) {\n if (!ensureAll(state, dynamic))\n return 0;\n let value = get(state);\n if (facet.compare(value, state.values[idx]))\n return 0;\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n },\n reconfigure(state, oldState) {\n let depChanged = ensureAll(state, providerAddrs);\n let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);\n if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {\n state.values[idx] = oldValue;\n return 0;\n }\n let value = get(state);\n if (facet.compare(value, oldValue)) {\n state.values[idx] = oldValue;\n return 0;\n }\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n }\n };\n}\nconst initField = /*@__PURE__*/Facet.define({ static: true });\n/**\nFields can store additional information in an editor state, and\nkeep it in sync with the rest of the state.\n*/\nclass StateField {\n constructor(\n /**\n @internal\n */\n id, createF, updateF, compareF, \n /**\n @internal\n */\n spec) {\n this.id = id;\n this.createF = createF;\n this.updateF = updateF;\n this.compareF = compareF;\n this.spec = spec;\n /**\n @internal\n */\n this.provides = undefined;\n }\n /**\n Define a state field.\n */\n static define(config) {\n let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);\n if (config.provide)\n field.provides = config.provide(field);\n return field;\n }\n create(state) {\n let init = state.facet(initField).find(i => i.field == this);\n return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);\n }\n /**\n @internal\n */\n slot(addresses) {\n let idx = addresses[this.id] >> 1;\n return {\n create: (state) => {\n state.values[idx] = this.create(state);\n return 1 /* SlotStatus.Changed */;\n },\n update: (state, tr) => {\n let oldVal = state.values[idx];\n let value = this.updateF(oldVal, tr);\n if (this.compareF(oldVal, value))\n return 0;\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n },\n reconfigure: (state, oldState) => {\n let init = state.facet(initField), oldInit = oldState.facet(initField), reInit;\n if ((reInit = init.find(i => i.field == this)) && reInit != oldInit.find(i => i.field == this)) {\n state.values[idx] = reInit.create(state);\n return 1 /* SlotStatus.Changed */;\n }\n if (oldState.config.address[this.id] != null) {\n state.values[idx] = oldState.field(this);\n return 0;\n }\n state.values[idx] = this.create(state);\n return 1 /* SlotStatus.Changed */;\n }\n };\n }\n /**\n Returns an extension that enables this field and overrides the\n way it is initialized. Can be useful when you need to provide a\n non-default starting value for the field.\n */\n init(create) {\n return [this, initField.of({ field: this, create })];\n }\n /**\n State field instances can be used as\n [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a\n given state.\n */\n get extension() { return this; }\n}\nconst Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };\nfunction prec(value) {\n return (ext) => new PrecExtension(ext, value);\n}\n/**\nBy default extensions are registered in the order they are found\nin the flattened form of nested array that was provided.\nIndividual extension values can be assigned a precedence to\noverride this. Extensions that do not have a precedence set get\nthe precedence of the nearest parent with a precedence, or\n[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The\nfinal ordering of extensions is determined by first sorting by\nprecedence and then by order within each precedence.\n*/\nconst Prec = {\n /**\n The highest precedence level, for extensions that should end up\n near the start of the precedence ordering.\n */\n highest: /*@__PURE__*/prec(Prec_.highest),\n /**\n A higher-than-default precedence, for extensions that should\n come before those with default precedence.\n */\n high: /*@__PURE__*/prec(Prec_.high),\n /**\n The default precedence, which is also used for extensions\n without an explicit precedence.\n */\n default: /*@__PURE__*/prec(Prec_.default),\n /**\n A lower-than-default precedence.\n */\n low: /*@__PURE__*/prec(Prec_.low),\n /**\n The lowest precedence level. Meant for things that should end up\n near the end of the extension order.\n */\n lowest: /*@__PURE__*/prec(Prec_.lowest)\n};\nclass PrecExtension {\n constructor(inner, prec) {\n this.inner = inner;\n this.prec = prec;\n }\n}\n/**\nExtension compartments can be used to make a configuration\ndynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your\nconfiguration in a compartment, you can later\n[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a\ntransaction.\n*/\nclass Compartment {\n /**\n Create an instance of this compartment to add to your [state\n configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).\n */\n of(ext) { return new CompartmentInstance(this, ext); }\n /**\n Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that\n reconfigures this compartment.\n */\n reconfigure(content) {\n return Compartment.reconfigure.of({ compartment: this, extension: content });\n }\n /**\n Get the current content of the compartment in the state, or\n `undefined` if it isn't present.\n */\n get(state) {\n return state.config.compartments.get(this);\n }\n}\nclass CompartmentInstance {\n constructor(compartment, inner) {\n this.compartment = compartment;\n this.inner = inner;\n }\n}\nclass Configuration {\n constructor(base, compartments, dynamicSlots, address, staticValues, facets) {\n this.base = base;\n this.compartments = compartments;\n this.dynamicSlots = dynamicSlots;\n this.address = address;\n this.staticValues = staticValues;\n this.facets = facets;\n this.statusTemplate = [];\n while (this.statusTemplate.length < dynamicSlots.length)\n this.statusTemplate.push(0 /* SlotStatus.Unresolved */);\n }\n staticFacet(facet) {\n let addr = this.address[facet.id];\n return addr == null ? facet.default : this.staticValues[addr >> 1];\n }\n static resolve(base, compartments, oldState) {\n let fields = [];\n let facets = Object.create(null);\n let newCompartments = new Map();\n for (let ext of flatten(base, compartments, newCompartments)) {\n if (ext instanceof StateField)\n fields.push(ext);\n else\n (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);\n }\n let address = Object.create(null);\n let staticValues = [];\n let dynamicSlots = [];\n for (let field of fields) {\n address[field.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => field.slot(a));\n }\n let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;\n for (let id in facets) {\n let providers = facets[id], facet = providers[0].facet;\n let oldProviders = oldFacets && oldFacets[id] || [];\n if (providers.every(p => p.type == 0 /* Provider.Static */)) {\n address[facet.id] = (staticValues.length << 1) | 1;\n if (sameArray(oldProviders, providers)) {\n staticValues.push(oldState.facet(facet));\n }\n else {\n let value = facet.combine(providers.map(p => p.value));\n staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);\n }\n }\n else {\n for (let p of providers) {\n if (p.type == 0 /* Provider.Static */) {\n address[p.id] = (staticValues.length << 1) | 1;\n staticValues.push(p.value);\n }\n else {\n address[p.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => p.dynamicSlot(a));\n }\n }\n address[facet.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));\n }\n }\n let dynamic = dynamicSlots.map(f => f(address));\n return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);\n }\n}\nfunction flatten(extension, compartments, newCompartments) {\n let result = [[], [], [], [], []];\n let seen = new Map();\n function inner(ext, prec) {\n let known = seen.get(ext);\n if (known != null) {\n if (known <= prec)\n return;\n let found = result[known].indexOf(ext);\n if (found > -1)\n result[known].splice(found, 1);\n if (ext instanceof CompartmentInstance)\n newCompartments.delete(ext.compartment);\n }\n seen.set(ext, prec);\n if (Array.isArray(ext)) {\n for (let e of ext)\n inner(e, prec);\n }\n else if (ext instanceof CompartmentInstance) {\n if (newCompartments.has(ext.compartment))\n throw new RangeError(`Duplicate use of compartment in extensions`);\n let content = compartments.get(ext.compartment) || ext.inner;\n newCompartments.set(ext.compartment, content);\n inner(content, prec);\n }\n else if (ext instanceof PrecExtension) {\n inner(ext.inner, ext.prec);\n }\n else if (ext instanceof StateField) {\n result[prec].push(ext);\n if (ext.provides)\n inner(ext.provides, prec);\n }\n else if (ext instanceof FacetProvider) {\n result[prec].push(ext);\n if (ext.facet.extensions)\n inner(ext.facet.extensions, Prec_.default);\n }\n else {\n let content = ext.extension;\n if (!content)\n throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);\n inner(content, prec);\n }\n }\n inner(extension, Prec_.default);\n return result.reduce((a, b) => a.concat(b));\n}\nfunction ensureAddr(state, addr) {\n if (addr & 1)\n return 2 /* SlotStatus.Computed */;\n let idx = addr >> 1;\n let status = state.status[idx];\n if (status == 4 /* SlotStatus.Computing */)\n throw new Error(\"Cyclic dependency between fields and/or facets\");\n if (status & 2 /* SlotStatus.Computed */)\n return status;\n state.status[idx] = 4 /* SlotStatus.Computing */;\n let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);\n return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;\n}\nfunction getAddr(state, addr) {\n return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];\n}\n\nconst languageData = /*@__PURE__*/Facet.define();\nconst allowMultipleSelections = /*@__PURE__*/Facet.define({\n combine: values => values.some(v => v),\n static: true\n});\nconst lineSeparator = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : undefined,\n static: true\n});\nconst changeFilter = /*@__PURE__*/Facet.define();\nconst transactionFilter = /*@__PURE__*/Facet.define();\nconst transactionExtender = /*@__PURE__*/Facet.define();\nconst readOnly = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : false\n});\n\n/**\nAnnotations are tagged values that are used to add metadata to\ntransactions in an extensible way. They should be used to model\nthings that effect the entire transaction (such as its [time\nstamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its\n[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen\n_alongside_ the other changes made by the transaction, [state\neffects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.\n*/\nclass Annotation {\n /**\n @internal\n */\n constructor(\n /**\n The annotation type.\n */\n type, \n /**\n The value of this annotation.\n */\n value) {\n this.type = type;\n this.value = value;\n }\n /**\n Define a new type of annotation.\n */\n static define() { return new AnnotationType(); }\n}\n/**\nMarker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).\n*/\nclass AnnotationType {\n /**\n Create an instance of this annotation.\n */\n of(value) { return new Annotation(this, value); }\n}\n/**\nRepresentation of a type of state effect. Defined with\n[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).\n*/\nclass StateEffectType {\n /**\n @internal\n */\n constructor(\n // The `any` types in these function types are there to work\n // around TypeScript issue #37631, where the type guard on\n // `StateEffect.is` mysteriously stops working when these properly\n // have type `Value`.\n /**\n @internal\n */\n map) {\n this.map = map;\n }\n /**\n Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this\n type.\n */\n of(value) { return new StateEffect(this, value); }\n}\n/**\nState effects can be used to represent additional effects\nassociated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They\nare often useful to model changes to custom [state\nfields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in\ndocument or selection changes.\n*/\nclass StateEffect {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n type, \n /**\n The value of this effect.\n */\n value) {\n this.type = type;\n this.value = value;\n }\n /**\n Map this effect through a position mapping. Will return\n `undefined` when that ends up deleting the effect.\n */\n map(mapping) {\n let mapped = this.type.map(this.value, mapping);\n return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);\n }\n /**\n Tells you whether this effect object is of a given\n [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).\n */\n is(type) { return this.type == type; }\n /**\n Define a new effect type. The type parameter indicates the type\n of values that his effect holds. It should be a type that\n doesn't include `undefined`, since that is used in\n [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is\n removed.\n */\n static define(spec = {}) {\n return new StateEffectType(spec.map || (v => v));\n }\n /**\n Map an array of effects through a change set.\n */\n static mapEffects(effects, mapping) {\n if (!effects.length)\n return effects;\n let result = [];\n for (let effect of effects) {\n let mapped = effect.map(mapping);\n if (mapped)\n result.push(mapped);\n }\n return result;\n }\n}\n/**\nThis effect can be used to reconfigure the root extensions of\nthe editor. Doing this will discard any extensions\n[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset\nthe content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)\ncompartments.\n*/\nStateEffect.reconfigure = /*@__PURE__*/StateEffect.define();\n/**\nAppend extensions to the top-level configuration of the editor.\n*/\nStateEffect.appendConfig = /*@__PURE__*/StateEffect.define();\n/**\nChanges to the editor state are grouped into transactions.\nTypically, a user action creates a single transaction, which may\ncontain any number of document changes, may change the selection,\nor have other effects. Create a transaction by calling\n[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately\ndispatch one by calling\n[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).\n*/\nclass Transaction {\n constructor(\n /**\n The state from which the transaction starts.\n */\n startState, \n /**\n The document changes made by this transaction.\n */\n changes, \n /**\n The selection set by this transaction, or undefined if it\n doesn't explicitly set a selection.\n */\n selection, \n /**\n The effects added to the transaction.\n */\n effects, \n /**\n @internal\n */\n annotations, \n /**\n Whether the selection should be scrolled into view after this\n transaction is dispatched.\n */\n scrollIntoView) {\n this.startState = startState;\n this.changes = changes;\n this.selection = selection;\n this.effects = effects;\n this.annotations = annotations;\n this.scrollIntoView = scrollIntoView;\n /**\n @internal\n */\n this._doc = null;\n /**\n @internal\n */\n this._state = null;\n if (selection)\n checkSelection(selection, changes.newLength);\n if (!annotations.some((a) => a.type == Transaction.time))\n this.annotations = annotations.concat(Transaction.time.of(Date.now()));\n }\n /**\n @internal\n */\n static create(startState, changes, selection, effects, annotations, scrollIntoView) {\n return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);\n }\n /**\n The new document produced by the transaction. Contrary to\n [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't\n force the entire new state to be computed right away, so it is\n recommended that [transaction\n filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter\n when they need to look at the new document.\n */\n get newDoc() {\n return this._doc || (this._doc = this.changes.apply(this.startState.doc));\n }\n /**\n The new selection produced by the transaction. If\n [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,\n this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's\n current selection through the changes made by the transaction.\n */\n get newSelection() {\n return this.selection || this.startState.selection.map(this.changes);\n }\n /**\n The new state created by the transaction. Computed on demand\n (but retained for subsequent access), so it is recommended not to\n access it in [transaction\n filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.\n */\n get state() {\n if (!this._state)\n this.startState.applyTransaction(this);\n return this._state;\n }\n /**\n Get the value of the given annotation type, if any.\n */\n annotation(type) {\n for (let ann of this.annotations)\n if (ann.type == type)\n return ann.value;\n return undefined;\n }\n /**\n Indicates whether the transaction changed the document.\n */\n get docChanged() { return !this.changes.empty; }\n /**\n Indicates whether this transaction reconfigures the state\n (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or\n with a top-level configuration\n [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).\n */\n get reconfigured() { return this.startState.config != this.state.config; }\n /**\n Returns true if the transaction has a [user\n event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to\n or more specific than `event`. For example, if the transaction\n has `\"select.pointer\"` as user event, `\"select\"` and\n `\"select.pointer\"` will match it.\n */\n isUserEvent(event) {\n let e = this.annotation(Transaction.userEvent);\n return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == \".\"));\n }\n}\n/**\nAnnotation used to store transaction timestamps. Automatically\nadded to every transaction, holding `Date.now()`.\n*/\nTransaction.time = /*@__PURE__*/Annotation.define();\n/**\nAnnotation used to associate a transaction with a user interface\nevent. Holds a string identifying the event, using a\ndot-separated format to support attaching more specific\ninformation. The events used by the core libraries are:\n\n - `\"input\"` when content is entered\n - `\"input.type\"` for typed input\n - `\"input.type.compose\"` for composition\n - `\"input.paste\"` for pasted input\n - `\"input.drop\"` when adding content with drag-and-drop\n - `\"input.complete\"` when autocompleting\n - `\"delete\"` when the user deletes content\n - `\"delete.selection\"` when deleting the selection\n - `\"delete.forward\"` when deleting forward from the selection\n - `\"delete.backward\"` when deleting backward from the selection\n - `\"delete.cut\"` when cutting to the clipboard\n - `\"move\"` when content is moved\n - `\"move.drop\"` when content is moved within the editor through drag-and-drop\n - `\"select\"` when explicitly changing the selection\n - `\"select.pointer\"` when selecting with a mouse or other pointing device\n - `\"undo\"` and `\"redo\"` for history actions\n\nUse [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check\nwhether the annotation matches a given event.\n*/\nTransaction.userEvent = /*@__PURE__*/Annotation.define();\n/**\nAnnotation indicating whether a transaction should be added to\nthe undo history or not.\n*/\nTransaction.addToHistory = /*@__PURE__*/Annotation.define();\n/**\nAnnotation indicating (when present and true) that a transaction\nrepresents a change made by some other actor, not the user. This\nis used, for example, to tag other people's changes in\ncollaborative editing.\n*/\nTransaction.remote = /*@__PURE__*/Annotation.define();\nfunction joinRanges(a, b) {\n let result = [];\n for (let iA = 0, iB = 0;;) {\n let from, to;\n if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {\n from = a[iA++];\n to = a[iA++];\n }\n else if (iB < b.length) {\n from = b[iB++];\n to = b[iB++];\n }\n else\n return result;\n if (!result.length || result[result.length - 1] < from)\n result.push(from, to);\n else if (result[result.length - 1] < to)\n result[result.length - 1] = to;\n }\n}\nfunction mergeTransaction(a, b, sequential) {\n var _a;\n let mapForA, mapForB, changes;\n if (sequential) {\n mapForA = b.changes;\n mapForB = ChangeSet.empty(b.changes.length);\n changes = a.changes.compose(b.changes);\n }\n else {\n mapForA = b.changes.map(a.changes);\n mapForB = a.changes.mapDesc(b.changes, true);\n changes = a.changes.compose(mapForA);\n }\n return {\n changes,\n selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),\n effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),\n annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,\n scrollIntoView: a.scrollIntoView || b.scrollIntoView\n };\n}\nfunction resolveTransactionInner(state, spec, docSize) {\n let sel = spec.selection, annotations = asArray(spec.annotations);\n if (spec.userEvent)\n annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));\n return {\n changes: spec.changes instanceof ChangeSet ? spec.changes\n : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),\n selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),\n effects: asArray(spec.effects),\n annotations,\n scrollIntoView: !!spec.scrollIntoView\n };\n}\nfunction resolveTransaction(state, specs, filter) {\n let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);\n if (specs.length && specs[0].filter === false)\n filter = false;\n for (let i = 1; i < specs.length; i++) {\n if (specs[i].filter === false)\n filter = false;\n let seq = !!specs[i].sequential;\n s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);\n }\n let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);\n return extendTransaction(filter ? filterTransaction(tr) : tr);\n}\n// Finish a transaction by applying filters if necessary.\nfunction filterTransaction(tr) {\n let state = tr.startState;\n // Change filters\n let result = true;\n for (let filter of state.facet(changeFilter)) {\n let value = filter(tr);\n if (value === false) {\n result = false;\n break;\n }\n if (Array.isArray(value))\n result = result === true ? value : joinRanges(result, value);\n }\n if (result !== true) {\n let changes, back;\n if (result === false) {\n back = tr.changes.invertedDesc;\n changes = ChangeSet.empty(state.doc.length);\n }\n else {\n let filtered = tr.changes.filter(result);\n changes = filtered.changes;\n back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;\n }\n tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);\n }\n // Transaction filters\n let filters = state.facet(transactionFilter);\n for (let i = filters.length - 1; i >= 0; i--) {\n let filtered = filters[i](tr);\n if (filtered instanceof Transaction)\n tr = filtered;\n else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)\n tr = filtered[0];\n else\n tr = resolveTransaction(state, asArray(filtered), false);\n }\n return tr;\n}\nfunction extendTransaction(tr) {\n let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;\n for (let i = extenders.length - 1; i >= 0; i--) {\n let extension = extenders[i](tr);\n if (extension && Object.keys(extension).length)\n spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);\n }\n return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);\n}\nconst none = [];\nfunction asArray(value) {\n return value == null ? none : Array.isArray(value) ? value : [value];\n}\n\n/**\nThe categories produced by a [character\ncategorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used\ndo things like selecting by word.\n*/\nvar CharCategory = /*@__PURE__*/(function (CharCategory) {\n /**\n Word characters.\n */\n CharCategory[CharCategory[\"Word\"] = 0] = \"Word\";\n /**\n Whitespace.\n */\n CharCategory[CharCategory[\"Space\"] = 1] = \"Space\";\n /**\n Anything else.\n */\n CharCategory[CharCategory[\"Other\"] = 2] = \"Other\";\nreturn CharCategory})(CharCategory || (CharCategory = {}));\nconst nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\nlet wordChar;\ntry {\n wordChar = /*@__PURE__*/new RegExp(\"[\\\\p{Alphabetic}\\\\p{Number}_]\", \"u\");\n}\ncatch (_) { }\nfunction hasWordChar(str) {\n if (wordChar)\n return wordChar.test(str);\n for (let i = 0; i < str.length; i++) {\n let ch = str[i];\n if (/\\w/.test(ch) || ch > \"\\x80\" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))\n return true;\n }\n return false;\n}\nfunction makeCategorizer(wordChars) {\n return (char) => {\n if (!/\\S/.test(char))\n return CharCategory.Space;\n if (hasWordChar(char))\n return CharCategory.Word;\n for (let i = 0; i < wordChars.length; i++)\n if (char.indexOf(wordChars[i]) > -1)\n return CharCategory.Word;\n return CharCategory.Other;\n };\n}\n\n/**\nThe editor state class is a persistent (immutable) data structure.\nTo update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a\n[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state\ninstance, without modifying the original object.\n\nAs such, _never_ mutate properties of a state directly. That'll\njust break things.\n*/\nclass EditorState {\n constructor(\n /**\n @internal\n */\n config, \n /**\n The current document.\n */\n doc, \n /**\n The current selection.\n */\n selection, \n /**\n @internal\n */\n values, computeSlot, tr) {\n this.config = config;\n this.doc = doc;\n this.selection = selection;\n this.values = values;\n this.status = config.statusTemplate.slice();\n this.computeSlot = computeSlot;\n // Fill in the computed state immediately, so that further queries\n // for it made during the update return this state\n if (tr)\n tr._state = this;\n for (let i = 0; i < this.config.dynamicSlots.length; i++)\n ensureAddr(this, i << 1);\n this.computeSlot = null;\n }\n field(field, require = true) {\n let addr = this.config.address[field.id];\n if (addr == null) {\n if (require)\n throw new RangeError(\"Field is not present in this state\");\n return undefined;\n }\n ensureAddr(this, addr);\n return getAddr(this, addr);\n }\n /**\n Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this\n state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)\n can be passed. Unless\n [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the\n [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec\n are assumed to start in the _current_ document (not the document\n produced by previous specs), and its\n [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and\n [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer\n to the document created by its _own_ changes. The resulting\n transaction contains the combined effect of all the different\n specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later\n specs take precedence over earlier ones.\n */\n update(...specs) {\n return resolveTransaction(this, specs, true);\n }\n /**\n @internal\n */\n applyTransaction(tr) {\n let conf = this.config, { base, compartments } = conf;\n for (let effect of tr.effects) {\n if (effect.is(Compartment.reconfigure)) {\n if (conf) {\n compartments = new Map;\n conf.compartments.forEach((val, key) => compartments.set(key, val));\n conf = null;\n }\n compartments.set(effect.value.compartment, effect.value.extension);\n }\n else if (effect.is(StateEffect.reconfigure)) {\n conf = null;\n base = effect.value;\n }\n else if (effect.is(StateEffect.appendConfig)) {\n conf = null;\n base = asArray(base).concat(effect.value);\n }\n }\n let startValues;\n if (!conf) {\n conf = Configuration.resolve(base, compartments, this);\n let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);\n startValues = intermediateState.values;\n }\n else {\n startValues = tr.startState.values.slice();\n }\n let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();\n new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);\n }\n /**\n Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that\n replaces every selection range with the given content.\n */\n replaceSelection(text) {\n if (typeof text == \"string\")\n text = this.toText(text);\n return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },\n range: EditorSelection.cursor(range.from + text.length) }));\n }\n /**\n Create a set of changes and a new selection by running the given\n function for each range in the active selection. The function\n can return an optional set of changes (in the coordinate space\n of the start document), plus an updated range (in the coordinate\n space of the document produced by the call's own changes). This\n method will merge all the changes and ranges into a single\n changeset and selection, and return it as a [transaction\n spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to\n [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).\n */\n changeByRange(f) {\n let sel = this.selection;\n let result1 = f(sel.ranges[0]);\n let changes = this.changes(result1.changes), ranges = [result1.range];\n let effects = asArray(result1.effects);\n for (let i = 1; i < sel.ranges.length; i++) {\n let result = f(sel.ranges[i]);\n let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);\n for (let j = 0; j < i; j++)\n ranges[j] = ranges[j].map(newMapped);\n let mapBy = changes.mapDesc(newChanges, true);\n ranges.push(result.range.map(mapBy));\n changes = changes.compose(newMapped);\n effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));\n }\n return {\n changes,\n selection: EditorSelection.create(ranges, sel.mainIndex),\n effects\n };\n }\n /**\n Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change\n description, taking the state's document length and line\n separator into account.\n */\n changes(spec = []) {\n if (spec instanceof ChangeSet)\n return spec;\n return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));\n }\n /**\n Using the state's [line\n separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a\n [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.\n */\n toText(string) {\n return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));\n }\n /**\n Return the given range of the document as a string.\n */\n sliceDoc(from = 0, to = this.doc.length) {\n return this.doc.sliceString(from, to, this.lineBreak);\n }\n /**\n Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).\n */\n facet(facet) {\n let addr = this.config.address[facet.id];\n if (addr == null)\n return facet.default;\n ensureAddr(this, addr);\n return getAddr(this, addr);\n }\n /**\n Convert this state to a JSON-serializable object. When custom\n fields should be serialized, you can pass them in as an object\n mapping property names (in the resulting object, which should\n not use `doc` or `selection`) to fields.\n */\n toJSON(fields) {\n let result = {\n doc: this.sliceDoc(),\n selection: this.selection.toJSON()\n };\n if (fields)\n for (let prop in fields) {\n let value = fields[prop];\n if (value instanceof StateField && this.config.address[value.id] != null)\n result[prop] = value.spec.toJSON(this.field(fields[prop]), this);\n }\n return result;\n }\n /**\n Deserialize a state from its JSON representation. When custom\n fields should be deserialized, pass the same object you passed\n to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as\n third argument.\n */\n static fromJSON(json, config = {}, fields) {\n if (!json || typeof json.doc != \"string\")\n throw new RangeError(\"Invalid JSON representation for EditorState\");\n let fieldInit = [];\n if (fields)\n for (let prop in fields) {\n if (Object.prototype.hasOwnProperty.call(json, prop)) {\n let field = fields[prop], value = json[prop];\n fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));\n }\n }\n return EditorState.create({\n doc: json.doc,\n selection: EditorSelection.fromJSON(json.selection),\n extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit\n });\n }\n /**\n Create a new state. You'll usually only need this when\n initializing an editor\u2014updated states are created by applying\n transactions.\n */\n static create(config = {}) {\n let configuration = Configuration.resolve(config.extensions || [], new Map);\n let doc = config.doc instanceof Text ? config.doc\n : Text.of((config.doc || \"\").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));\n let selection = !config.selection ? EditorSelection.single(0)\n : config.selection instanceof EditorSelection ? config.selection\n : EditorSelection.single(config.selection.anchor, config.selection.head);\n checkSelection(selection, doc.length);\n if (!configuration.staticFacet(allowMultipleSelections))\n selection = selection.asSingle();\n return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);\n }\n /**\n The size (in columns) of a tab in the document, determined by\n the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.\n */\n get tabSize() { return this.facet(EditorState.tabSize); }\n /**\n Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)\n string for this state.\n */\n get lineBreak() { return this.facet(EditorState.lineSeparator) || \"\\n\"; }\n /**\n Returns true when the editor is\n [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.\n */\n get readOnly() { return this.facet(readOnly); }\n /**\n Look up a translation for the given phrase (via the\n [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the\n original string if no translation is found.\n \n If additional arguments are passed, they will be inserted in\n place of markers like `$1` (for the first value) and `$2`, etc.\n A single `$` is equivalent to `$1`, and `$$` will produce a\n literal dollar sign.\n */\n phrase(phrase, ...insert) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase)) {\n phrase = map[phrase];\n break;\n }\n if (insert.length)\n phrase = phrase.replace(/\\$(\\$|\\d*)/g, (m, i) => {\n if (i == \"$\")\n return \"$\";\n let n = +(i || 1);\n return !n || n > insert.length ? m : insert[n - 1];\n });\n return phrase;\n }\n /**\n Find the values for a given language data field, provided by the\n the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.\n \n Examples of language data fields are...\n \n - [`\"commentTokens\"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying\n comment syntax.\n - [`\"autocomplete\"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)\n for providing language-specific completion sources.\n - [`\"wordChars\"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding\n characters that should be considered part of words in this\n language.\n - [`\"closeBrackets\"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls\n bracket closing behavior.\n */\n languageDataAt(name, pos, side = -1) {\n let values = [];\n for (let provider of this.facet(languageData)) {\n for (let result of provider(this, pos, side)) {\n if (Object.prototype.hasOwnProperty.call(result, name))\n values.push(result[name]);\n }\n }\n return values;\n }\n /**\n Return a function that can categorize strings (expected to\n represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))\n into one of:\n \n - Word (contains an alphanumeric character or a character\n explicitly listed in the local language's `\"wordChars\"`\n language data, which should be a string)\n - Space (contains only whitespace)\n - Other (anything else)\n */\n charCategorizer(at) {\n let chars = this.languageDataAt(\"wordChars\", at);\n return makeCategorizer(chars.length ? chars[0] : \"\");\n }\n /**\n Find the word at the given position, meaning the range\n containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters\n around it. If no word characters are adjacent to the position,\n this returns null.\n */\n wordAt(pos) {\n let { text, from, length } = this.doc.lineAt(pos);\n let cat = this.charCategorizer(pos);\n let start = pos - from, end = pos - from;\n while (start > 0) {\n let prev = findClusterBreak(text, start, false);\n if (cat(text.slice(prev, start)) != CharCategory.Word)\n break;\n start = prev;\n }\n while (end < length) {\n let next = findClusterBreak(text, end);\n if (cat(text.slice(end, next)) != CharCategory.Word)\n break;\n end = next;\n }\n return start == end ? null : EditorSelection.range(start + from, end + from);\n }\n}\n/**\nA facet that, when enabled, causes the editor to allow multiple\nranges to be selected. Be careful though, because by default the\neditor relies on the native DOM selection, which cannot handle\nmultiple selections. An extension like\n[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make\nsecondary selections visible to the user.\n*/\nEditorState.allowMultipleSelections = allowMultipleSelections;\n/**\nConfigures the tab size to use in this state. The first\n(highest-precedence) value of the facet is used. If no value is\ngiven, this defaults to 4.\n*/\nEditorState.tabSize = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : 4\n});\n/**\nThe line separator to use. By default, any of `\"\\n\"`, `\"\\r\\n\"`\nand `\"\\r\"` is treated as a separator when splitting lines, and\nlines are joined with `\"\\n\"`.\n\nWhen you configure a value here, only that precise separator\nwill be used, allowing you to round-trip documents through the\neditor without normalizing line separators.\n*/\nEditorState.lineSeparator = lineSeparator;\n/**\nThis facet controls the value of the\n[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is\nconsulted by commands and extensions that implement editing\nfunctionality to determine whether they should apply. It\ndefaults to false, but when its highest-precedence value is\n`true`, such functionality disables itself.\n\nNot to be confused with\n[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which\ncontrols whether the editor's DOM is set to be editable (and\nthus focusable).\n*/\nEditorState.readOnly = readOnly;\n/**\nRegisters translation phrases. The\n[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through\nall objects registered with this facet to find translations for\nits argument.\n*/\nEditorState.phrases = /*@__PURE__*/Facet.define({\n compare(a, b) {\n let kA = Object.keys(a), kB = Object.keys(b);\n return kA.length == kB.length && kA.every(k => a[k] == b[k]);\n }\n});\n/**\nA facet used to register [language\ndata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.\n*/\nEditorState.languageData = languageData;\n/**\nFacet used to register change filters, which are called for each\ntransaction (unless explicitly\n[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress\npart of the transaction's changes.\n\nSuch a function can return `true` to indicate that it doesn't\nwant to do anything, `false` to completely stop the changes in\nthe transaction, or a set of ranges in which changes should be\nsuppressed. Such ranges are represented as an array of numbers,\nwith each pair of two numbers indicating the start and end of a\nrange. So for example `[10, 20, 100, 110]` suppresses changes\nbetween 10 and 20, and between 100 and 110.\n*/\nEditorState.changeFilter = changeFilter;\n/**\nFacet used to register a hook that gets a chance to update or\nreplace transaction specs before they are applied. This will\nonly be applied for transactions that don't have\n[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You\ncan either return a single transaction spec (possibly the input\ntransaction), or an array of specs (which will be combined in\nthe same way as the arguments to\n[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).\n\nWhen possible, it is recommended to avoid accessing\n[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,\nsince it will force creation of a state that will then be\ndiscarded again, if the transaction is actually filtered.\n\n(This functionality should be used with care. Indiscriminately\nmodifying transaction is likely to break something or degrade\nthe user experience.)\n*/\nEditorState.transactionFilter = transactionFilter;\n/**\nThis is a more limited form of\n[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),\nwhich can only add\n[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and\n[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type\nof filter runs even if the transaction has disabled regular\n[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable\nfor effects that don't need to touch the changes or selection,\nbut do want to process every transaction.\n\nExtenders run _after_ filters, when both are present.\n*/\nEditorState.transactionExtender = transactionExtender;\nCompartment.reconfigure = /*@__PURE__*/StateEffect.define();\n\n/**\nUtility function for combining behaviors to fill in a config\nobject from an array of provided configs. `defaults` should hold\ndefault values for all optional fields in `Config`.\n\nThe function will, by default, error\nwhen a field gets two values that aren't `===`-equal, but you can\nprovide combine functions per field to do something else.\n*/\nfunction combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that\ncombine = {}) {\n let result = {};\n for (let config of configs)\n for (let key of Object.keys(config)) {\n let value = config[key], current = result[key];\n if (current === undefined)\n result[key] = value;\n else if (current === value || value === undefined) ; // No conflict\n else if (Object.hasOwnProperty.call(combine, key))\n result[key] = combine[key](current, value);\n else\n throw new Error(\"Config merge conflict for field \" + key);\n }\n for (let key in defaults)\n if (result[key] === undefined)\n result[key] = defaults[key];\n return result;\n}\n\n/**\nEach range is associated with a value, which must inherit from\nthis class.\n*/\nclass RangeValue {\n /**\n Compare this value with another value. Used when comparing\n rangesets. The default implementation compares by identity.\n Unless you are only creating a fixed number of unique instances\n of your value type, it is a good idea to implement this\n properly.\n */\n eq(other) { return this == other; }\n /**\n Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.\n */\n range(from, to = from) { return Range.create(from, to, this); }\n}\nRangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;\nRangeValue.prototype.point = false;\nRangeValue.prototype.mapMode = MapMode.TrackDel;\nfunction cmpVal(a, b) {\n return a == b || a.constructor == b.constructor && a.eq(b);\n}\n/**\nA range associates a value with a range of positions.\n*/\nclass Range {\n constructor(\n /**\n The range's start position.\n */\n from, \n /**\n Its end position.\n */\n to, \n /**\n The value associated with this range.\n */\n value) {\n this.from = from;\n this.to = to;\n this.value = value;\n }\n /**\n @internal\n */\n static create(from, to, value) {\n return new Range(from, to, value);\n }\n}\nfunction cmpRange(a, b) {\n return a.from - b.from || a.value.startSide - b.value.startSide;\n}\nclass Chunk {\n constructor(from, to, value, \n // Chunks are marked with the largest point that occurs\n // in them (or -1 for no points), so that scans that are\n // only interested in points (such as the\n // heightmap-related logic) can skip range-only chunks.\n maxPoint) {\n this.from = from;\n this.to = to;\n this.value = value;\n this.maxPoint = maxPoint;\n }\n get length() { return this.to[this.to.length - 1]; }\n // Find the index of the given position and side. Use the ranges'\n // `from` pos when `end == false`, `to` when `end == true`.\n findIndex(pos, side, end, startAt = 0) {\n let arr = end ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }\n between(offset, from, to, f) {\n for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)\n if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)\n return false;\n }\n map(offset, changes) {\n let value = [], from = [], to = [], newPos = -1, maxPoint = -1;\n for (let i = 0; i < this.value.length; i++) {\n let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;\n if (curFrom == curTo) {\n let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);\n if (mapped == null)\n continue;\n newFrom = newTo = mapped;\n if (val.startSide != val.endSide) {\n newTo = changes.mapPos(curFrom, val.endSide);\n if (newTo < newFrom)\n continue;\n }\n }\n else {\n newFrom = changes.mapPos(curFrom, val.startSide);\n newTo = changes.mapPos(curTo, val.endSide);\n if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)\n continue;\n }\n if ((newTo - newFrom || val.endSide - val.startSide) < 0)\n continue;\n if (newPos < 0)\n newPos = newFrom;\n if (val.point)\n maxPoint = Math.max(maxPoint, newTo - newFrom);\n value.push(val);\n from.push(newFrom - newPos);\n to.push(newTo - newPos);\n }\n return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };\n }\n}\n/**\nA range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a\nway that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and\n[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data\nstructure.\n*/\nclass RangeSet {\n constructor(\n /**\n @internal\n */\n chunkPos, \n /**\n @internal\n */\n chunk, \n /**\n @internal\n */\n nextLayer, \n /**\n @internal\n */\n maxPoint) {\n this.chunkPos = chunkPos;\n this.chunk = chunk;\n this.nextLayer = nextLayer;\n this.maxPoint = maxPoint;\n }\n /**\n @internal\n */\n static create(chunkPos, chunk, nextLayer, maxPoint) {\n return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);\n }\n /**\n @internal\n */\n get length() {\n let last = this.chunk.length - 1;\n return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);\n }\n /**\n The number of ranges in the set.\n */\n get size() {\n if (this.isEmpty)\n return 0;\n let size = this.nextLayer.size;\n for (let chunk of this.chunk)\n size += chunk.value.length;\n return size;\n }\n /**\n @internal\n */\n chunkEnd(index) {\n return this.chunkPos[index] + this.chunk[index].length;\n }\n /**\n Update the range set, optionally adding new ranges or filtering\n out existing ones.\n \n (Note: The type parameter is just there as a kludge to work\n around TypeScript variance issues that prevented `RangeSet`\n from being a subtype of `RangeSet` when `X` is a subtype of\n `Y`.)\n */\n update(updateSpec) {\n let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;\n let filter = updateSpec.filter;\n if (add.length == 0 && !filter)\n return this;\n if (sort)\n add = add.slice().sort(cmpRange);\n if (this.isEmpty)\n return add.length ? RangeSet.of(add) : this;\n let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];\n let builder = new RangeSetBuilder();\n while (cur.value || i < add.length) {\n if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {\n let range = add[i++];\n if (!builder.addInner(range.from, range.to, range.value))\n spill.push(range);\n }\n else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&\n (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&\n (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&\n builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {\n cur.nextChunk();\n }\n else {\n if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {\n if (!builder.addInner(cur.from, cur.to, cur.value))\n spill.push(Range.create(cur.from, cur.to, cur.value));\n }\n cur.next();\n }\n }\n return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty\n : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));\n }\n /**\n Map this range set through a set of changes, return the new set.\n */\n map(changes) {\n if (changes.empty || this.isEmpty)\n return this;\n let chunks = [], chunkPos = [], maxPoint = -1;\n for (let i = 0; i < this.chunk.length; i++) {\n let start = this.chunkPos[i], chunk = this.chunk[i];\n let touch = changes.touchesRange(start, start + chunk.length);\n if (touch === false) {\n maxPoint = Math.max(maxPoint, chunk.maxPoint);\n chunks.push(chunk);\n chunkPos.push(changes.mapPos(start));\n }\n else if (touch === true) {\n let { mapped, pos } = chunk.map(start, changes);\n if (mapped) {\n maxPoint = Math.max(maxPoint, mapped.maxPoint);\n chunks.push(mapped);\n chunkPos.push(pos);\n }\n }\n }\n let next = this.nextLayer.map(changes);\n return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);\n }\n /**\n Iterate over the ranges that touch the region `from` to `to`,\n calling `f` for each. There is no guarantee that the ranges will\n be reported in any specific order. When the callback returns\n `false`, iteration stops.\n */\n between(from, to, f) {\n if (this.isEmpty)\n return;\n for (let i = 0; i < this.chunk.length; i++) {\n let start = this.chunkPos[i], chunk = this.chunk[i];\n if (to >= start && from <= start + chunk.length &&\n chunk.between(start, from - start, to - start, f) === false)\n return;\n }\n this.nextLayer.between(from, to, f);\n }\n /**\n Iterate over the ranges in this set, in order, including all\n ranges that end at or after `from`.\n */\n iter(from = 0) {\n return HeapCursor.from([this]).goto(from);\n }\n /**\n @internal\n */\n get isEmpty() { return this.nextLayer == this; }\n /**\n Iterate over the ranges in a collection of sets, in order,\n starting from `from`.\n */\n static iter(sets, from = 0) {\n return HeapCursor.from(sets).goto(from);\n }\n /**\n Iterate over two groups of sets, calling methods on `comparator`\n to notify it of possible differences.\n */\n static compare(oldSets, newSets, \n /**\n This indicates how the underlying data changed between these\n ranges, and is needed to synchronize the iteration.\n */\n textDiff, comparator, \n /**\n Can be used to ignore all non-point ranges, and points below\n the given size. When -1, all ranges are compared.\n */\n minPointSize = -1) {\n let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);\n let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);\n let sharedChunks = findSharedChunks(a, b, textDiff);\n let sideA = new SpanCursor(a, sharedChunks, minPointSize);\n let sideB = new SpanCursor(b, sharedChunks, minPointSize);\n textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));\n if (textDiff.empty && textDiff.length == 0)\n compare(sideA, 0, sideB, 0, 0, comparator);\n }\n /**\n Compare the contents of two groups of range sets, returning true\n if they are equivalent in the given range.\n */\n static eq(oldSets, newSets, from = 0, to) {\n if (to == null)\n to = 1000000000 /* C.Far */ - 1;\n let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);\n let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);\n if (a.length != b.length)\n return false;\n if (!a.length)\n return true;\n let sharedChunks = findSharedChunks(a, b);\n let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);\n for (;;) {\n if (sideA.to != sideB.to ||\n !sameValues(sideA.active, sideB.active) ||\n sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point)))\n return false;\n if (sideA.to > to)\n return true;\n sideA.next();\n sideB.next();\n }\n }\n /**\n Iterate over a group of range sets at the same time, notifying\n the iterator about the ranges covering every given piece of\n content. Returns the open count (see\n [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end\n of the iteration.\n */\n static spans(sets, from, to, iterator, \n /**\n When given and greater than -1, only points of at least this\n size are taken into account.\n */\n minPointSize = -1) {\n let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;\n let openRanges = cursor.openStart;\n for (;;) {\n let curTo = Math.min(cursor.to, to);\n if (cursor.point) {\n let active = cursor.activeForPoint(cursor.to);\n let openCount = cursor.pointFrom < from ? active.length + 1\n : cursor.point.startSide < 0 ? active.length\n : Math.min(active.length, openRanges);\n iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);\n openRanges = Math.min(cursor.openEnd(curTo), active.length);\n }\n else if (curTo > pos) {\n iterator.span(pos, curTo, cursor.active, openRanges);\n openRanges = cursor.openEnd(curTo);\n }\n if (cursor.to > to)\n return openRanges + (cursor.point && cursor.to > to ? 1 : 0);\n pos = cursor.to;\n cursor.next();\n }\n }\n /**\n Create a range set for the given range or array of ranges. By\n default, this expects the ranges to be _sorted_ (by start\n position and, if two start at the same position,\n `value.startSide`). You can pass `true` as second argument to\n cause the method to sort them.\n */\n static of(ranges, sort = false) {\n let build = new RangeSetBuilder();\n for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)\n build.add(range.from, range.to, range.value);\n return build.finish();\n }\n /**\n Join an array of range sets into a single set.\n */\n static join(sets) {\n if (!sets.length)\n return RangeSet.empty;\n let result = sets[sets.length - 1];\n for (let i = sets.length - 2; i >= 0; i--) {\n for (let layer = sets[i]; layer != RangeSet.empty; layer = layer.nextLayer)\n result = new RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint));\n }\n return result;\n }\n}\n/**\nThe empty set of ranges.\n*/\nRangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);\nfunction lazySort(ranges) {\n if (ranges.length > 1)\n for (let prev = ranges[0], i = 1; i < ranges.length; i++) {\n let cur = ranges[i];\n if (cmpRange(prev, cur) > 0)\n return ranges.slice().sort(cmpRange);\n prev = cur;\n }\n return ranges;\n}\nRangeSet.empty.nextLayer = RangeSet.empty;\n/**\nA range set builder is a data structure that helps build up a\n[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating\nan array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.\n*/\nclass RangeSetBuilder {\n finishChunk(newArrays) {\n this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));\n this.chunkPos.push(this.chunkStart);\n this.chunkStart = -1;\n this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);\n this.maxPoint = -1;\n if (newArrays) {\n this.from = [];\n this.to = [];\n this.value = [];\n }\n }\n /**\n Create an empty builder.\n */\n constructor() {\n this.chunks = [];\n this.chunkPos = [];\n this.chunkStart = -1;\n this.last = null;\n this.lastFrom = -1000000000 /* C.Far */;\n this.lastTo = -1000000000 /* C.Far */;\n this.from = [];\n this.to = [];\n this.value = [];\n this.maxPoint = -1;\n this.setMaxPoint = -1;\n this.nextLayer = null;\n }\n /**\n Add a range. Ranges should be added in sorted (by `from` and\n `value.startSide`) order.\n */\n add(from, to, value) {\n if (!this.addInner(from, to, value))\n (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);\n }\n /**\n @internal\n */\n addInner(from, to, value) {\n let diff = from - this.lastTo || value.startSide - this.last.endSide;\n if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)\n throw new Error(\"Ranges must be added sorted by `from` position and `startSide`\");\n if (diff < 0)\n return false;\n if (this.from.length == 250 /* C.ChunkSize */)\n this.finishChunk(true);\n if (this.chunkStart < 0)\n this.chunkStart = from;\n this.from.push(from - this.chunkStart);\n this.to.push(to - this.chunkStart);\n this.last = value;\n this.lastFrom = from;\n this.lastTo = to;\n this.value.push(value);\n if (value.point)\n this.maxPoint = Math.max(this.maxPoint, to - from);\n return true;\n }\n /**\n @internal\n */\n addChunk(from, chunk) {\n if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)\n return false;\n if (this.from.length)\n this.finishChunk(true);\n this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);\n this.chunks.push(chunk);\n this.chunkPos.push(from);\n let last = chunk.value.length - 1;\n this.last = chunk.value[last];\n this.lastFrom = chunk.from[last] + from;\n this.lastTo = chunk.to[last] + from;\n return true;\n }\n /**\n Finish the range set. Returns the new set. The builder can't be\n used anymore after this has been called.\n */\n finish() { return this.finishInner(RangeSet.empty); }\n /**\n @internal\n */\n finishInner(next) {\n if (this.from.length)\n this.finishChunk(false);\n if (this.chunks.length == 0)\n return next;\n let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);\n this.from = null; // Make sure further `add` calls produce errors\n return result;\n }\n}\nfunction findSharedChunks(a, b, textDiff) {\n let inA = new Map();\n for (let set of a)\n for (let i = 0; i < set.chunk.length; i++)\n if (set.chunk[i].maxPoint <= 0)\n inA.set(set.chunk[i], set.chunkPos[i]);\n let shared = new Set();\n for (let set of b)\n for (let i = 0; i < set.chunk.length; i++) {\n let known = inA.get(set.chunk[i]);\n if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&\n !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))\n shared.add(set.chunk[i]);\n }\n return shared;\n}\nclass LayerCursor {\n constructor(layer, skip, minPoint, rank = 0) {\n this.layer = layer;\n this.skip = skip;\n this.minPoint = minPoint;\n this.rank = rank;\n }\n get startSide() { return this.value ? this.value.startSide : 0; }\n get endSide() { return this.value ? this.value.endSide : 0; }\n goto(pos, side = -1000000000 /* C.Far */) {\n this.chunkIndex = this.rangeIndex = 0;\n this.gotoInner(pos, side, false);\n return this;\n }\n gotoInner(pos, side, forward) {\n while (this.chunkIndex < this.layer.chunk.length) {\n let next = this.layer.chunk[this.chunkIndex];\n if (!(this.skip && this.skip.has(next) ||\n this.layer.chunkEnd(this.chunkIndex) < pos ||\n next.maxPoint < this.minPoint))\n break;\n this.chunkIndex++;\n forward = false;\n }\n if (this.chunkIndex < this.layer.chunk.length) {\n let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);\n if (!forward || this.rangeIndex < rangeIndex)\n this.setRangeIndex(rangeIndex);\n }\n this.next();\n }\n forward(pos, side) {\n if ((this.to - pos || this.endSide - side) < 0)\n this.gotoInner(pos, side, true);\n }\n next() {\n for (;;) {\n if (this.chunkIndex == this.layer.chunk.length) {\n this.from = this.to = 1000000000 /* C.Far */;\n this.value = null;\n break;\n }\n else {\n let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];\n let from = chunkPos + chunk.from[this.rangeIndex];\n this.from = from;\n this.to = chunkPos + chunk.to[this.rangeIndex];\n this.value = chunk.value[this.rangeIndex];\n this.setRangeIndex(this.rangeIndex + 1);\n if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)\n break;\n }\n }\n }\n setRangeIndex(index) {\n if (index == this.layer.chunk[this.chunkIndex].value.length) {\n this.chunkIndex++;\n if (this.skip) {\n while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))\n this.chunkIndex++;\n }\n this.rangeIndex = 0;\n }\n else {\n this.rangeIndex = index;\n }\n }\n nextChunk() {\n this.chunkIndex++;\n this.rangeIndex = 0;\n this.next();\n }\n compare(other) {\n return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||\n this.to - other.to || this.endSide - other.endSide;\n }\n}\nclass HeapCursor {\n constructor(heap) {\n this.heap = heap;\n }\n static from(sets, skip = null, minPoint = -1) {\n let heap = [];\n for (let i = 0; i < sets.length; i++) {\n for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {\n if (cur.maxPoint >= minPoint)\n heap.push(new LayerCursor(cur, skip, minPoint, i));\n }\n }\n return heap.length == 1 ? heap[0] : new HeapCursor(heap);\n }\n get startSide() { return this.value ? this.value.startSide : 0; }\n goto(pos, side = -1000000000 /* C.Far */) {\n for (let cur of this.heap)\n cur.goto(pos, side);\n for (let i = this.heap.length >> 1; i >= 0; i--)\n heapBubble(this.heap, i);\n this.next();\n return this;\n }\n forward(pos, side) {\n for (let cur of this.heap)\n cur.forward(pos, side);\n for (let i = this.heap.length >> 1; i >= 0; i--)\n heapBubble(this.heap, i);\n if ((this.to - pos || this.value.endSide - side) < 0)\n this.next();\n }\n next() {\n if (this.heap.length == 0) {\n this.from = this.to = 1000000000 /* C.Far */;\n this.value = null;\n this.rank = -1;\n }\n else {\n let top = this.heap[0];\n this.from = top.from;\n this.to = top.to;\n this.value = top.value;\n this.rank = top.rank;\n if (top.value)\n top.next();\n heapBubble(this.heap, 0);\n }\n }\n}\nfunction heapBubble(heap, index) {\n for (let cur = heap[index];;) {\n let childIndex = (index << 1) + 1;\n if (childIndex >= heap.length)\n break;\n let child = heap[childIndex];\n if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {\n child = heap[childIndex + 1];\n childIndex++;\n }\n if (cur.compare(child) < 0)\n break;\n heap[childIndex] = cur;\n heap[index] = child;\n index = childIndex;\n }\n}\nclass SpanCursor {\n constructor(sets, skip, minPoint) {\n this.minPoint = minPoint;\n this.active = [];\n this.activeTo = [];\n this.activeRank = [];\n this.minActive = -1;\n // A currently active point range, if any\n this.point = null;\n this.pointFrom = 0;\n this.pointRank = 0;\n this.to = -1000000000 /* C.Far */;\n this.endSide = 0;\n // The amount of open active ranges at the start of the iterator.\n // Not including points.\n this.openStart = -1;\n this.cursor = HeapCursor.from(sets, skip, minPoint);\n }\n goto(pos, side = -1000000000 /* C.Far */) {\n this.cursor.goto(pos, side);\n this.active.length = this.activeTo.length = this.activeRank.length = 0;\n this.minActive = -1;\n this.to = pos;\n this.endSide = side;\n this.openStart = -1;\n this.next();\n return this;\n }\n forward(pos, side) {\n while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)\n this.removeActive(this.minActive);\n this.cursor.forward(pos, side);\n }\n removeActive(index) {\n remove(this.active, index);\n remove(this.activeTo, index);\n remove(this.activeRank, index);\n this.minActive = findMinIndex(this.active, this.activeTo);\n }\n addActive(trackOpen) {\n let i = 0, { value, to, rank } = this.cursor;\n // Organize active marks by rank first, then by size\n while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)\n i++;\n insert(this.active, i, value);\n insert(this.activeTo, i, to);\n insert(this.activeRank, i, rank);\n if (trackOpen)\n insert(trackOpen, i, this.cursor.from);\n this.minActive = findMinIndex(this.active, this.activeTo);\n }\n // After calling this, if `this.point` != null, the next range is a\n // point. Otherwise, it's a regular range, covered by `this.active`.\n next() {\n let from = this.to, wasPoint = this.point;\n this.point = null;\n let trackOpen = this.openStart < 0 ? [] : null;\n for (;;) {\n let a = this.minActive;\n if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {\n if (this.activeTo[a] > from) {\n this.to = this.activeTo[a];\n this.endSide = this.active[a].endSide;\n break;\n }\n this.removeActive(a);\n if (trackOpen)\n remove(trackOpen, a);\n }\n else if (!this.cursor.value) {\n this.to = this.endSide = 1000000000 /* C.Far */;\n break;\n }\n else if (this.cursor.from > from) {\n this.to = this.cursor.from;\n this.endSide = this.cursor.startSide;\n break;\n }\n else {\n let nextVal = this.cursor.value;\n if (!nextVal.point) { // Opening a range\n this.addActive(trackOpen);\n this.cursor.next();\n }\n else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {\n // Ignore any non-empty points that end precisely at the end of the prev point\n this.cursor.next();\n }\n else { // New point\n this.point = nextVal;\n this.pointFrom = this.cursor.from;\n this.pointRank = this.cursor.rank;\n this.to = this.cursor.to;\n this.endSide = nextVal.endSide;\n this.cursor.next();\n this.forward(this.to, this.endSide);\n break;\n }\n }\n }\n if (trackOpen) {\n this.openStart = 0;\n for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)\n this.openStart++;\n }\n }\n activeForPoint(to) {\n if (!this.active.length)\n return this.active;\n let active = [];\n for (let i = this.active.length - 1; i >= 0; i--) {\n if (this.activeRank[i] < this.pointRank)\n break;\n if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)\n active.push(this.active[i]);\n }\n return active.reverse();\n }\n openEnd(to) {\n let open = 0;\n for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)\n open++;\n return open;\n }\n}\nfunction compare(a, startA, b, startB, length, comparator) {\n a.goto(startA);\n b.goto(startB);\n let endB = startB + length;\n let pos = startB, dPos = startB - startA;\n let bounds = !!comparator.boundChange;\n for (let boundChange = false;;) {\n let dEnd = (a.to + dPos) - b.to, diff = dEnd || a.endSide - b.endSide;\n let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);\n let point = a.point || b.point;\n if (point) {\n if (!(a.point && b.point && cmpVal(a.point, b.point) &&\n sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))\n comparator.comparePoint(pos, clipEnd, a.point, b.point);\n boundChange = false;\n }\n else {\n if (boundChange)\n comparator.boundChange(pos);\n if (clipEnd > pos && !sameValues(a.active, b.active))\n comparator.compareRange(pos, clipEnd, a.active, b.active);\n if (bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b.openEnd(end)))\n boundChange = true;\n }\n if (end > endB)\n break;\n pos = end;\n if (diff <= 0)\n a.next();\n if (diff >= 0)\n b.next();\n }\n}\nfunction sameValues(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (a[i] != b[i] && !cmpVal(a[i], b[i]))\n return false;\n return true;\n}\nfunction remove(array, index) {\n for (let i = index, e = array.length - 1; i < e; i++)\n array[i] = array[i + 1];\n array.pop();\n}\nfunction insert(array, index, value) {\n for (let i = array.length - 1; i >= index; i--)\n array[i + 1] = array[i];\n array[index] = value;\n}\nfunction findMinIndex(value, array) {\n let found = -1, foundPos = 1000000000 /* C.Far */;\n for (let i = 0; i < array.length; i++)\n if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {\n found = i;\n foundPos = array[i];\n }\n return found;\n}\n\n/**\nCount the column position at the given offset into the string,\ntaking extending characters and tab size into account.\n*/\nfunction countColumn(string, tabSize, to = string.length) {\n let n = 0;\n for (let i = 0; i < to && i < string.length;) {\n if (string.charCodeAt(i) == 9) {\n n += tabSize - (n % tabSize);\n i++;\n }\n else {\n n++;\n i = findClusterBreak(string, i);\n }\n }\n return n;\n}\n/**\nFind the offset that corresponds to the given column position in a\nstring, taking extending characters and tab size into account. By\ndefault, the string length is returned when it is too short to\nreach the column. Pass `strict` true to make it return -1 in that\nsituation.\n*/\nfunction findColumn(string, col, tabSize, strict) {\n for (let i = 0, n = 0;;) {\n if (n >= col)\n return i;\n if (i == string.length)\n break;\n n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;\n i = findClusterBreak(string, i);\n }\n return strict === true ? -1 : string.length;\n}\n\nexport { Annotation, AnnotationType, ChangeDesc, ChangeSet, CharCategory, Compartment, EditorSelection, EditorState, Facet, Line, MapMode, Prec, Range, RangeSet, RangeSetBuilder, RangeValue, SelectionRange, StateEffect, StateEffectType, StateField, Text, Transaction, codePointAt, codePointSize, combineConfig, countColumn, findClusterBreak, findColumn, fromCodePoint };\n", "const C = \"\\u037c\"\nconst COUNT = typeof Symbol == \"undefined\" ? \"__\" + C : Symbol.for(C)\nconst SET = typeof Symbol == \"undefined\" ? \"__styleSet\" + Math.floor(Math.random() * 1e8) : Symbol(\"styleSet\")\nconst top = typeof globalThis != \"undefined\" ? globalThis : typeof window != \"undefined\" ? window : {}\n\n// :: - Style modules encapsulate a set of CSS rules defined from\n// JavaScript. Their definitions are only available in a given DOM\n// root after it has been _mounted_ there with `StyleModule.mount`.\n//\n// Style modules should be created once and stored somewhere, as\n// opposed to re-creating them every time you need them. The amount of\n// CSS rules generated for a given DOM root is bounded by the amount\n// of style modules that were used. So to avoid leaking rules, don't\n// create these dynamically, but treat them as one-time allocations.\nexport class StyleModule {\n // :: (Object diff --git a/datasets/detail/index.html b/datasets/detail/index.html new file mode 100644 index 0000000..a419aa9 --- /dev/null +++ b/datasets/detail/index.html @@ -0,0 +1,118 @@ +--- +layout: default +permalink: /datasets/detail/ +title: "Dataset — GeneratedArt" +meta_title: "Dataset — GeneratedArt" +meta_description: | + A dataset on GeneratedArt — curated images and video, and the AI art + models trained from it. +header_image: "/assets/images/art/bg31.webp" +--- + +{% comment %} + Query-string routed (?slug=X), matching /models/detail/?slug=X — Jekyll + can't statically generate a page per D1 row. +{% endcomment %} + +{% include layouts/nav/nav-10.html default_logo="black" drop_search=true %} + +
    +
    +
    +
    +

    …

    +

    Loading…

    +

    +
    + +
    +
    +

    Items

    +
    +

    Drag images or video here, or click to choose files.

    + +
    +

    + +
    + +

    Train a model

    +

    Needs at least 5 items to train.

    +
    + +
    +
    + + +
    +
    + + +
    +
    +
    + + +
    + +
    +
    + + +
    +
    +
    +
    + + + + + + +{% include layouts/footer/footer-1.html %} diff --git a/datasets/index.html b/datasets/index.html new file mode 100644 index 0000000..2adbfae --- /dev/null +++ b/datasets/index.html @@ -0,0 +1,110 @@ +--- +layout: default +permalink: /datasets/ +title: "Dataset Library — GeneratedArt" +meta_title: "Dataset Library — GeneratedArt" +meta_description: | + Your curated images and video, private by default — the source + material for training custom AI art models on GeneratedArt. +header_image: "/assets/images/art/bg31.webp" +--- + +{% include layouts/nav/nav-10.html default_logo="black" drop_search=true %} + +
    +
    +
    +
    +
    +

    Dataset Library

    +

    Your own images and video, private by default. Only the models you publish are public.

    +
    + +
    + +
    +
    Loading…
    +
    + + +
    + +
    +

    You need to sign in first.

    +

    Connect your wallet to see your datasets.

    + Connect wallet +
    +
    +
    + + + + + + +{% include layouts/footer/footer-1.html %} diff --git a/explore/index.html b/explore/index.html index 06580ab..27ab470 100644 --- a/explore/index.html +++ b/explore/index.html @@ -2,10 +2,11 @@ layout: default permalink: /explore/ title: "Explore — GeneratedArt" -meta_title: "Explore generative art" +meta_title: "Explore AI art models and code sketches" meta_description: | - Browse generative-art projects from artists on GeneratedArt. Recent uploads, - trending pieces from the last seven days, and curator-featured work. + Browse code sketches from artists on GeneratedArt. Recent uploads, + trending pieces from the last seven days, and curator-featured work — no + account required. Looking for AI art models instead? See /models/. header_image: "/assets/images/art/bg31.webp" --- @@ -13,9 +14,12 @@
    -
    -

    Explore

    -

    Recent uploads, trending pieces, and curator-featured work — no account required.

    +
    +
    +

    Explore code sketches

    +

    Recent uploads, trending pieces, and curator-featured work — no account required.

    +
    + Browse AI art models →
    diff --git a/index.html b/index.html index 2f41939..b7727f5 100644 --- a/index.html +++ b/index.html @@ -1,12 +1,12 @@ --- layout: default -title: GeneratedArt — code-based generative art, on-chain on Base -meta_title: GeneratedArt — community-run generative art platform & NFT marketplace +title: GeneratedArt — AI Art Creative Coding, owned by the people who train it +meta_title: GeneratedArt — AI Art Creative Coding platform & NFT marketplace meta_description: >- - GeneratedArt is a community-run platform and NFT marketplace for code-based - generative art — hand-written p5.js, three.js, WebGL and GLSL. A spiritual - successor to fxhash and Art Blocks, with a physical-digital bridge through - the Geneva gallery. + GeneratedArt is where AI Creative Coders build the models that make the + art — train a custom AI model on your own dataset, or hand-code a p5.js / + three.js sketch. Every model and every sketch ships with full on-chain + provenance and a physical-digital bridge through the Geneva gallery. custom_color: red --- {% include layouts/nav/nav-1.html drop_search=false %} @@ -14,21 +14,24 @@

    v0.1.0 · hackathon · base sepolia

    -

    Code-based generative art, owned by the people who write it.

    +

    GeneratedArt is where AI Creative Coders build the models that make the art.

    - Sketch in the browser. Commit to a real GitHub repo. Mint editions on Base. - Hand-written p5.js, three.js, WebGL and GLSL — no closed plugins, no ML - reproductions, no hidden middlemen. + Curate a dataset. Train a custom AI art model. Or hand-code a p5.js, + three.js, WebGL, or GLSL sketch. Either way the artifact is code with + disclosed provenance — pinned to IPFS, minted on Base, never a rented + aesthetic from a closed prompt box.

    +

    The Code Sketch path

    +

    Hand-writing p5.js, three.js, or GLSL is still a fully respected craft here — the three steps below are how it works. Training a custom AI art model instead? See the Model path →

    01 — Repo as project

    @@ -55,14 +58,14 @@

    Open editions, on-chain royalties.

    Manifesto · short version

    - Code is the artifact. The browser is the gallery. The chain is the ledger. The community is the curator. + Code is the artifact — a sketch, or the model that made it. The chain is the ledger. The community is the curator.

    • No closed plugins. Hand-written p5.js, three.js, WebGL, GLSL — readable in the repo.
    • No hidden middlemen. Stewards rotate; treasury splits are on-chain.
    • -
    • No ML-generated images. Tools that pattern-match human work are not welcome here.
    • +
    • No undisclosed models. Every AI art model publishes its base model, training method, and dataset note.
    • Physical-digital bridge. Token holders can claim a print at the Geneva gallery.
    @@ -75,12 +78,33 @@

    What's live · v0.1.0-hackathon

    -

    Six surfaces, all shipped.

    +

    Nine surfaces, all shipped.

    Every link below is a real, live surface backed by the Worker, D1, and Base Sepolia.

    +
    +
    +

    LIVE

    +

    AI art models

    +

    Publish a code-writing or custom-trained model with disclosed provenance; earn tokens when others render it. Browse models →

    +
    +
    +
    +
    +

    LIVE

    +

    Token wallet

    +

    Prepaid render tokens, bought on-chain — no payment processor, no subscription. Open wallet →

    +
    +
    +
    +
    +

    LIVE

    +

    Studio Copilot

    +

    Generate, edit, and explain sketch code from the editor — the code stays what's frozen and minted. Open studio →

    +
    +

    LIVE

    diff --git a/models/detail/index.html b/models/detail/index.html new file mode 100644 index 0000000..804a515 --- /dev/null +++ b/models/detail/index.html @@ -0,0 +1,123 @@ +--- +layout: default +permalink: /models/detail/ +title: "AI Art Model — GeneratedArt" +meta_title: "AI Art Model — GeneratedArt" +meta_description: | + An AI art model on GeneratedArt — provenance, versions, and a live + render form. +header_image: "/assets/images/art/bg31.webp" +--- + +{% comment %} + Model detail is query-string routed (?slug=X), matching /p/?id=N and + /t/?p=N&id=T — Jekyll can't statically generate a page per D1 row. +{% endcomment %} + +{% include layouts/nav/nav-10.html default_logo="black" drop_search=true %} + +
    +
    +
    +
    +

    …

    +

    Loading…

    +

    +
    + +
    +
    +

    Versions & provenance

    +
      + +
      +

      Publish a new version

      +

      +
      + +
      + + +
      +
      + + +
      + +
      + + +
      + +
      +
      +
      + + +
      +
      + + +
      +
      +
      + + +
      +
      + + +
      +
      + + +
      +
      +
      + + +
      +
      +
      +
      + + + + + + +{% include layouts/footer/footer-1.html %} diff --git a/models/index.html b/models/index.html new file mode 100644 index 0000000..ab82b6d --- /dev/null +++ b/models/index.html @@ -0,0 +1,122 @@ +--- +layout: default +permalink: /models/ +title: "AI Art Models — GeneratedArt" +meta_title: "AI Art Models — GeneratedArt" +meta_description: | + Browse AI art models on GeneratedArt — code-writing copilots and + creator-trained custom art models, published with full provenance. +header_image: "/assets/images/art/bg31.webp" +--- + +{% include layouts/nav/nav-10.html default_logo="black" drop_search=true %} + +
      +
      +
      +
      +
      +

      AI Art models

      +

      Code-writing copilots and creator-trained custom art models, published with provenance.

      +
      +
      +
      + + + +
      +
      +
      + +
      +
      Loading…
      +
      + +
      +
      +

      Your models

      + +
      +
      +
      Loading…
      +
      +
      + + +
      +
      +
      + + + + + + +{% include layouts/footer/footer-1.html %} diff --git a/studio/index.html b/studio/index.html index a248eb4..49cdbc7 100644 --- a/studio/index.html +++ b/studio/index.html @@ -20,6 +20,7 @@
      Idle + @@ -32,7 +33,7 @@
      -
      +
      +
      @@ -70,6 +92,14 @@

      You need to sign in to open the studio.

      .ga-studio-status[data-state="error"] { color: var(--ga-accent); border-color: var(--ga-accent); background: rgba(230, 57, 70, 0.08); } .ga-studio-restore { display: flex; align-items: center; gap: 12px; padding: 8px 16px; background: rgba(230, 57, 70, 0.06); color: var(--ga-ink); border-bottom: 1px solid var(--ga-accent); } .ga-studio-grid { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); min-height: 0; } + .ga-studio-grid.ga-copilot-open { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 320px; } + .ga-studio-copilot { border-left: 1px solid var(--ga-rule); background: var(--ga-paper); display: flex; flex-direction: column; min-height: 0; overflow-y: auto; } + .ga-copilot-head { display: flex; justify-content: space-between; align-items: center; padding: 10px 14px; border-bottom: 1px solid var(--ga-rule); font-family: var(--ga-font-mono); font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em; } + .ga-copilot-body { padding: 14px; } + .ga-copilot-mode.active { background: var(--ga-ink); color: var(--ga-paper); border-color: var(--ga-ink); } + .ga-copilot-suggestion { background: var(--ga-ink); color: var(--ga-paper); padding: 12px; font-size: 11px; max-height: 260px; overflow-y: auto; white-space: pre-wrap; margin-bottom: 8px; } + .ga-copilot-params-list { list-style: none; padding: 0; margin: 0 0 8px; font-family: var(--ga-font-mono); font-size: 12px; } + .ga-copilot-params-list li { padding: 4px 0; border-bottom: 1px dashed var(--ga-rule); } .ga-studio-editor { min-height: 0; height: 100%; overflow: hidden; background: var(--ga-paper); } .ga-studio-editor .cm-editor { height: 100%; font-size: 0.92rem; } .ga-studio-preview-wrap { background: var(--ga-paper); border-left: 1px solid var(--ga-rule); display: flex; align-items: center; justify-content: center; padding: 16px; min-height: 0; } diff --git a/wallet/index.html b/wallet/index.html new file mode 100644 index 0000000..e17ed0c --- /dev/null +++ b/wallet/index.html @@ -0,0 +1,118 @@ +--- +layout: default +permalink: /wallet/ +title: "Wallet — GeneratedArt" +meta_title: "Wallet — GeneratedArt" +meta_description: | + Your render-token balance, purchase history, and token packs on + GeneratedArt. +header_image: "/assets/images/art/bg31.webp" +--- + +{% include layouts/nav/nav-10.html default_logo="black" drop_search=true %} + +
      +
      +
      +
      +

      Wallet

      +

      Prepaid render tokens — spend them running AI art models, earn them when others run yours.

      +
      + +
      +
      +

      Balance

      +

      …

      +
      +
      +
      Purchased
      …
      +
      Spent
      …
      +
      Earned
      …
      +
      +
      + +

      + +

      Buy tokens

      +
      +
      Loading…
      +
      + +

      Activity

      +
      + + + + + + + + + + + + + +
      WhenKindMemoAmountBalance
      Loading…
      +
      +
      + +
      +
      + +
      +

      You need to sign in first.

      +

      Connect your wallet to see your token balance.

      + Connect wallet +
      +
      +
      + + + + + + +{% include layouts/footer/footer-1.html %} diff --git a/workers/api/.dev.vars.example b/workers/api/.dev.vars.example index 8d311f4..32c8441 100644 --- a/workers/api/.dev.vars.example +++ b/workers/api/.dev.vars.example @@ -89,6 +89,12 @@ RENDER_MOCK="1" # fal.ai's queue API. Production must NEVER set TRAINING_MOCK. TRAINING_MOCK="1" +# --- Studio Copilot ---------------------------------------------------- +# OPT-IN ONLY, same convention as RENDER_MOCK/TRAINING_MOCK. The four +# /v1/projects/:id/ai/* routes return canned output with no network +# call. Production must NEVER set AI_MOCK. +AI_MOCK="1" + # --- Task #20: observability (all optional; unset = the surface no-ops) ---- # ADMIN_HANDLES gates /v1/internal/*; empty means those routes 403 with # `admin_unconfigured`. Set it to your own handle to use /v1/internal/stats diff --git a/workers/api/client/dashboard.ts b/workers/api/client/dashboard.ts index c3c2e7f..5f9a749 100644 --- a/workers/api/client/dashboard.ts +++ b/workers/api/client/dashboard.ts @@ -263,8 +263,46 @@ const GADashboard = { if (modalRoot && !modalRoot.innerHTML.trim()) modalRoot.innerHTML = renderModal(); attachEvents(cfg); await loadProjects(cfg); + await loadWorkspaceTiles(cfg); }, }; +/** + * Workspace tie-together (design brief Step 9, simplified): quiet stat + * tiles linking to Datasets/Models/Wallet from the project dashboard. + * Each is best-effort — a failed fetch leaves that tile's "…" rather + * than blocking the rest of the dashboard. + */ +async function loadWorkspaceTiles(cfg: DashboardConfig): Promise { + const datasetsEl = cfg.rootEl.querySelector("#ga-tile-datasets"); + const modelsEl = cfg.rootEl.querySelector("#ga-tile-models"); + const walletEl = cfg.rootEl.querySelector("#ga-tile-wallet"); + + if (datasetsEl) { + try { + const data = await fetchJson<{ datasets: unknown[] }>(`${cfg.apiBase}/v1/datasets/mine`); + datasetsEl.textContent = String(data.datasets.length); + } catch { + datasetsEl.textContent = "—"; + } + } + if (modelsEl) { + try { + const data = await fetchJson<{ models: unknown[] }>(`${cfg.apiBase}/v1/models/mine`); + modelsEl.textContent = String(data.models.length); + } catch { + modelsEl.textContent = "—"; + } + } + if (walletEl) { + try { + const data = await fetchJson<{ balance: number }>(`${cfg.apiBase}/v1/tokens/account`); + walletEl.textContent = `${data.balance.toLocaleString()} tokens`; + } catch { + walletEl.textContent = "—"; + } + } +} + window.GADashboard = GADashboard; export default GADashboard; diff --git a/workers/api/client/datasets.ts b/workers/api/client/datasets.ts new file mode 100644 index 0000000..36aaccc --- /dev/null +++ b/workers/api/client/datasets.ts @@ -0,0 +1,436 @@ +/** + * /datasets/ — the Dataset Library: a creator's own curated + * images/video, private by default. + * /datasets/detail/?slug=X — one dataset: item grid, upload/import, + * and the train-a-model flow that turns it into a fal_custom render + * model version. + * + * Two Jekyll pages share this module (query-string routed like + * /models/detail/?slug=X) — mount() reads cfg.mode to pick which one. + */ +import { installClientErrorReporter } from "./lib/clientErrors"; +import { TRAINABLE_BASE_MODELS } from "./lib/trainableBaseModels"; + +interface DatasetsConfig { + apiBase: string; + rootEl: HTMLElement; + mode: "library" | "detail"; + onUnauthenticated?: () => void; +} + +interface Dataset { + id: number; + slug: string; + title: string; + description: string | null; + rights_declaration: string; + visibility: string; + item_count: number; + created_at: number; + updated_at: number; +} + +interface DatasetItem { + id: number; + kind: string; + caption: string | null; + byte_size: number; + width: number | null; + height: number | null; + duration_seconds: number | null; + status: string; + flag_reason: string | null; + created_at: number; +} + +interface TrainingJob { + id: number; + dataset_id: number; + base_model: string; + training_method: string; + price_tokens: number; + render_price_tokens: number; + status: string; + model_id: number | null; + model_version_id: number | null; + error_code: string | null; + created_at: number; + started_at: number | null; + finished_at: number | null; +} + +function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (ch) => { + switch (ch) { + case "&": return "&"; + case "<": return "<"; + case ">": return ">"; + case '"': return """; + default: return "'"; + } + }); +} + +async function fetchJson(url: string, init?: RequestInit): Promise { + const res = await fetch(url, { credentials: "include", ...init }); + if (!res.ok) { + let detail = ""; + try { detail = JSON.stringify(await res.json()); } catch {} + throw new Error(`${res.status}: ${detail || res.statusText}`); + } + return (await res.json()) as T; +} + +function readFileAsDataUrl(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as string); + reader.onerror = () => reject(reader.error ?? new Error("file read failed")); + reader.readAsDataURL(file); + }); +} + +const RIGHTS_LABELS: Record = { + own: "My own work", + licensed: "Licensed to me", + public_domain: "Public domain / CC0", +}; + +function renderDatasetCard(d: Dataset): string { + return ` + +
      +

      ${escapeHtml(d.title)}

      +

      ${escapeHtml(d.description || "No description yet.")}

      +

      ${d.item_count} item${d.item_count === 1 ? "" : "s"} · ${escapeHtml(RIGHTS_LABELS[d.rights_declaration] || d.rights_declaration)} · ${escapeHtml(d.visibility)}

      +
      +
      `; +} + +// --------------------------------------------------------------------------- +// Library page +// --------------------------------------------------------------------------- + +class LibraryPage { + private cfg!: DatasetsConfig; + + async mount(cfg: DatasetsConfig): Promise { + this.cfg = cfg; + let me: unknown = null; + try { + me = await fetchJson(`${cfg.apiBase}/v1/me`); + } catch { + me = null; + } + if (!me) { + cfg.onUnauthenticated?.(); + return; + } + await this.loadDatasets(); + this.attachEvents(); + } + + private async loadDatasets(): Promise { + const el = this.cfg.rootEl.querySelector("#ga-datasets-list"); + if (!el) return; + try { + const data = await fetchJson<{ datasets: Dataset[] }>(`${this.cfg.apiBase}/v1/datasets/mine`); + el.innerHTML = data.datasets.length + ? data.datasets.map(renderDatasetCard).join("") + : `

      No datasets yet. Your source material stays private — only the models you publish are public.

      `; + } catch (err) { + el.innerHTML = `
      Failed to load: ${escapeHtml(String(err))}
      `; + } + } + + private attachEvents(): void { + const form = this.cfg.rootEl.querySelector("#ga-new-dataset-form"); + form?.addEventListener("submit", async (ev) => { + ev.preventDefault(); + const errEl = this.cfg.rootEl.querySelector("#ga-new-dataset-error"); + errEl?.classList.add("d-none"); + const title = this.cfg.rootEl.querySelector("#ga-nd-title")!.value.trim(); + const description = this.cfg.rootEl.querySelector("#ga-nd-description")!.value.trim(); + const rights = this.cfg.rootEl.querySelector("#ga-nd-rights")!.value; + try { + const data = await fetchJson<{ dataset: Dataset }>(`${this.cfg.apiBase}/v1/datasets`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ title, description: description || undefined, rights_declaration: rights }), + }); + window.location.href = `/datasets/detail/?slug=${encodeURIComponent(data.dataset.slug)}`; + } catch (err) { + if (errEl) { + errEl.textContent = `Couldn't create dataset: ${String(err)}`; + errEl.classList.remove("d-none"); + } + } + }); + } +} + +// --------------------------------------------------------------------------- +// Detail page +// --------------------------------------------------------------------------- + +class DetailPage { + private cfg!: DatasetsConfig; + private slug = ""; + private dataset: Dataset | null = null; + private pollTimer: ReturnType | null = null; + + async mount(cfg: DatasetsConfig): Promise { + this.cfg = cfg; + const params = new URLSearchParams(window.location.search); + this.slug = params.get("slug") || ""; + if (!this.slug) { + cfg.rootEl.innerHTML = `

      Bad URL — dataset pages look like /datasets/detail/?slug=your-dataset.

      `; + return; + } + try { + const data = await fetchJson<{ dataset: Dataset }>(`${cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`); + this.dataset = data.dataset; + } catch (err) { + const status = (err as Error).message.startsWith("404") ? 404 : 0; + if (status === 404) { + cfg.onUnauthenticated?.(); + return; + } + cfg.rootEl.innerHTML = `

      Failed to load dataset: ${escapeHtml(String(err))}

      `; + return; + } + + this.renderHeader(); + this.populateBaseModelOptions(); + await this.loadItems(); + await this.loadTrainingJobs(); + this.attachEvents(); + } + + private renderHeader(): void { + const d = this.dataset!; + const root = this.cfg.rootEl; + root.querySelector("#ga-dataset-title")!.textContent = d.title; + root.querySelector("#ga-dataset-desc")!.textContent = d.description || "No curatorial statement yet."; + root.querySelector("#ga-dataset-meta")!.textContent = + `${d.item_count} item${d.item_count === 1 ? "" : "s"} · ${RIGHTS_LABELS[d.rights_declaration] || d.rights_declaration} · ${d.visibility}`; + const trainBtn = root.querySelector("#ga-train-submit"); + if (trainBtn) trainBtn.disabled = d.item_count < 5; + const trainHint = root.querySelector("#ga-train-min-hint"); + if (trainHint) trainHint.classList.toggle("d-none", d.item_count >= 5); + } + + private populateBaseModelOptions(): void { + const sel = this.cfg.rootEl.querySelector("#ga-train-base-model"); + if (!sel) return; + sel.innerHTML = Object.entries(TRAINABLE_BASE_MODELS) + .map(([key, base]) => ``) + .join(""); + } + + private async loadItems(): Promise { + const grid = this.cfg.rootEl.querySelector("#ga-dataset-items"); + if (!grid) return; + try { + const data = await fetchJson<{ items: DatasetItem[] }>( + `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items?limit=100`, + ); + grid.innerHTML = data.items.length + ? data.items.map((i) => this.renderItem(i)).join("") + : `

      No items yet — drop images or video below.

      `; + } catch (err) { + grid.innerHTML = `
      Failed to load items: ${escapeHtml(String(err))}
      `; + } + } + + private renderItem(i: DatasetItem): string { + const fileUrl = `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items/${i.id}/file`; + const flagged = i.status === "flagged"; + const thumb = i.kind === "image" + ? `${escapeHtml(i.caption || ` + : ``; + return ` +
      + ${thumb} + ${flagged ? `

      ${escapeHtml(i.flag_reason || "flagged")}

      ` : ""} + +
      `; + } + + private async loadTrainingJobs(): Promise { + const el = this.cfg.rootEl.querySelector("#ga-training-jobs"); + if (!el) return; + try { + const data = await fetchJson<{ jobs: TrainingJob[] }>( + `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/training`, + ); + el.innerHTML = data.jobs.length + ? data.jobs.map((j) => this.renderTrainingJob(j)).join("") + : `

      No training runs yet.

      `; + // Poll while any job is still in flight — training is genuinely + // async at the provider (minutes to hours in production; instant + // under TRAINING_MOCK). + const inFlight = data.jobs.some((j) => j.status === "queued" || j.status === "training"); + if (inFlight && !this.pollTimer) { + this.pollTimer = setInterval(() => void this.loadTrainingJobs(), 4000); + } else if (!inFlight && this.pollTimer) { + clearInterval(this.pollTimer); + this.pollTimer = null; + } + } catch (err) { + el.innerHTML = `
      Failed to load: ${escapeHtml(String(err))}
      `; + } + } + + private renderTrainingJob(j: TrainingJob): string { + const base = TRAINABLE_BASE_MODELS[j.base_model]?.label ?? j.base_model; + const when = new Date(j.created_at * 1000).toLocaleString(); + let statusLine: string; + if (j.status === "succeeded" && j.model_id) { + statusLine = `View model →`; + } else if (j.status === "failed") { + statusLine = `Failed (${escapeHtml(j.error_code || "unknown")}) — ${j.price_tokens} tokens refunded`; + } else { + statusLine = "In progress…"; + } + return ` +
    • +
      + ${escapeHtml(base)} · ${escapeHtml(j.training_method)} + ${escapeHtml(j.status)} +
      +

      ${escapeHtml(when)} · ${statusLine}

      +
    • `; + } + + private feedback(id: string, msg: string): void { + const el = this.cfg.rootEl.querySelector(id); + if (el) el.textContent = msg; + } + + private async uploadFiles(files: FileList): Promise { + this.feedback("#ga-upload-feedback", `Uploading ${files.length} item(s)…`); + let ok = 0; + let dup = 0; + let failed = 0; + for (const file of Array.from(files)) { + try { + const dataUrl = await readFileAsDataUrl(file); + const res = await fetch( + `${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items`, + { + method: "POST", + credentials: "include", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ data_url: dataUrl }), + }, + ); + if (res.status === 201) ok++; + else if (res.status === 200) dup++; + else failed++; + } catch { + failed++; + } + } + this.feedback( + "#ga-upload-feedback", + `${ok} added, ${dup} duplicate${dup === 1 ? "" : "s"} skipped, ${failed} failed.`, + ); + const fresh = await fetchJson<{ dataset: Dataset }>(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`); + this.dataset = fresh.dataset; + this.renderHeader(); + await this.loadItems(); + } + + private async deleteItem(itemId: number): Promise { + if (!confirm("Remove this item from the dataset?")) return; + try { + await fetchJson(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/items/${itemId}`, { + method: "DELETE", + }); + const fresh = await fetchJson<{ dataset: Dataset }>(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}`); + this.dataset = fresh.dataset; + this.renderHeader(); + await this.loadItems(); + } catch (err) { + alert(`Failed to remove item: ${err}`); + } + } + + private async submitTraining(): Promise { + const root = this.cfg.rootEl; + const errEl = root.querySelector("#ga-train-error"); + errEl?.classList.add("d-none"); + const baseModel = root.querySelector("#ga-train-base-model")!.value; + const method = root.querySelector("#ga-train-method")!.value; + const renderPrice = parseInt(root.querySelector("#ga-train-render-price")!.value, 10) || 25; + const btn = root.querySelector("#ga-train-submit"); + if (btn) { btn.disabled = true; btn.textContent = "Starting…"; } + try { + await fetchJson(`${this.cfg.apiBase}/v1/datasets/${encodeURIComponent(this.slug)}/train`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ base_model: baseModel, training_method: method, render_price_tokens: renderPrice }), + }); + await this.loadTrainingJobs(); + } catch (err) { + if (errEl) { + errEl.textContent = `Couldn't start training: ${String(err)}`; + errEl.classList.remove("d-none"); + } + } finally { + if (btn) { btn.disabled = (this.dataset?.item_count ?? 0) < 5; btn.textContent = "Train"; } + } + } + + private attachEvents(): void { + const root = this.cfg.rootEl; + const dropzone = root.querySelector("#ga-dataset-dropzone"); + const fileInput = root.querySelector("#ga-dataset-file-input"); + dropzone?.addEventListener("click", () => fileInput?.click()); + fileInput?.addEventListener("change", () => { + if (fileInput.files?.length) void this.uploadFiles(fileInput.files); + }); + dropzone?.addEventListener("dragover", (ev) => { + ev.preventDefault(); + dropzone.classList.add("ga-dragover"); + }); + dropzone?.addEventListener("dragleave", () => dropzone.classList.remove("ga-dragover")); + dropzone?.addEventListener("drop", (ev) => { + ev.preventDefault(); + dropzone.classList.remove("ga-dragover"); + if (ev.dataTransfer?.files.length) void this.uploadFiles(ev.dataTransfer.files); + }); + + root.addEventListener("click", (ev) => { + const target = ev.target as HTMLElement; + const delBtn = target.closest(".ga-item-delete"); + if (delBtn) { + const id = parseInt(delBtn.dataset.itemId || "", 10); + if (id) void this.deleteItem(id); + } + }); + + root.querySelector("#ga-train-form")?.addEventListener("submit", (ev) => { + ev.preventDefault(); + void this.submitTraining(); + }); + } +} + +const GADatasets = { + async mount(cfg: DatasetsConfig) { + installClientErrorReporter({ apiBase: cfg.apiBase, page: `datasets-${cfg.mode}` }); + if (cfg.mode === "library") await new LibraryPage().mount(cfg); + else await new DetailPage().mount(cfg); + }, +}; + +declare global { + interface Window { + GADatasets?: typeof GADatasets; + } +} + +window.GADatasets = GADatasets; +export default GADatasets; diff --git a/workers/api/client/lib/trainableBaseModels.ts b/workers/api/client/lib/trainableBaseModels.ts new file mode 100644 index 0000000..1f60153 --- /dev/null +++ b/workers/api/client/lib/trainableBaseModels.ts @@ -0,0 +1,14 @@ +// Client-side mirror of TRAINABLE_BASE_MODELS in src/ai/training.ts. +// Duplicated rather than imported because client/ bundles separately +// from src/ (different esbuild entry points, no shared runtime) — this +// is presentation-only (label text for the base-model picker); the +// SERVER remains the source of truth and re-validates every value on +// POST /v1/datasets/:slug/train regardless of what this list offers. +// Keep in sync by hand when a new base model is verified end-to-end. +export interface TrainableBase { + label: string; +} + +export const TRAINABLE_BASE_MODELS: Record = { + "flux-dev": { label: "FLUX.1 [dev]" }, +}; diff --git a/workers/api/client/models.ts b/workers/api/client/models.ts new file mode 100644 index 0000000..fe60858 --- /dev/null +++ b/workers/api/client/models.ts @@ -0,0 +1,417 @@ +/** + * /models/ — public catalogue + "my models" + publish flow. + * /models/detail/?slug=X — one model: provenance, versions, publish a + * new version (owner-only), and the render form (everyone, gated by + * visibility/price). + * + * Two Jekyll pages share this module (query-string routed like + * /p/?id=N and /t/?p=N&id=T) — `mount()` reads `cfg.mode` to pick + * which one it's rendering into. + */ +import { installClientErrorReporter } from "./lib/clientErrors"; + +interface ModelsConfig { + apiBase: string; + rootEl: HTMLElement; + mode: "catalogue" | "detail"; +} + +interface Owner { + handle: string; + display_name: string | null; + avatar_url: string | null; +} + +interface ModelSummary { + id: number; + slug: string; + title: string; + description: string | null; + kind: string; + provider: string; + visibility: string; + status: string; + created_at: number; + updated_at: number; + latest_version: number | null; + latest_price_tokens: number | null; + run_count: number; + owner?: Owner; +} + +interface ModelVersion { + id: number; + version: number; + provider_model_id: string; + system_prompt?: string; + params_schema: unknown; + price_tokens: number; + training_method: string | null; + base_model: string | null; + dataset_note: string | null; + weights_ref?: string; + created_at: number; +} + +interface RenderJob { + id: number; + model_version_id: number; + project_id: number | null; + seed: string; + params: Record | null; + status: string; + price_tokens: number; + output_kind: string | null; + output_text: string | null; + output_key: string | null; + output_hash: string | null; + error_code: string | null; + created_at: number; + finished_at: number | null; +} + +function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (ch) => { + switch (ch) { + case "&": return "&"; + case "<": return "<"; + case ">": return ">"; + case '"': return """; + default: return "'"; + } + }); +} + +async function fetchJson(url: string, init?: RequestInit): Promise { + const res = await fetch(url, { credentials: "include", ...init }); + if (!res.ok) { + let detail = ""; + try { detail = JSON.stringify(await res.json()); } catch {} + throw new Error(`${res.status}: ${detail || res.statusText}`); + } + return (await res.json()) as T; +} + +const KIND_LABELS: Record = { code: "Code", image: "Image" }; +const PROVIDER_LABELS: Record = { + anthropic: "Claude", + workers_ai: "Workers AI", + fal_custom: "Custom-trained", + mock: "Mock", +}; + +function provenanceTag(v: Pick): string { + if (!v.base_model) return ""; + const method = v.training_method ? ` · ${escapeHtml(v.training_method)}` : ""; + return `${escapeHtml(v.base_model)}${method}`; +} + +function renderModelCard(m: ModelSummary): string { + const owner = m.owner + ? `@${escapeHtml(m.owner.handle)}` + : ""; + const price = + m.latest_price_tokens !== null + ? `${m.latest_price_tokens.toLocaleString()} tokens / run` + : "unpublished"; + return ` + +
      +

      ${escapeHtml(KIND_LABELS[m.kind] || m.kind)} · ${escapeHtml(PROVIDER_LABELS[m.provider] || m.provider)}

      +

      ${escapeHtml(m.title)}

      +

      ${escapeHtml(m.description || "No description yet.")}

      +

      ${escapeHtml(price)} · ${m.run_count} run${m.run_count === 1 ? "" : "s"}

      + ${owner} +
      +
      `; +} + +function renderEmptyModels(): string { + return `

      No models yet.

      `; +} + +// --------------------------------------------------------------------------- +// Catalogue page +// --------------------------------------------------------------------------- + +class CataloguePage { + private cfg!: ModelsConfig; + private isAuthed = false; + + async mount(cfg: ModelsConfig): Promise { + this.cfg = cfg; + try { + await fetchJson(`${cfg.apiBase}/v1/me`); + this.isAuthed = true; + } catch { + this.isAuthed = false; + } + const mineSection = cfg.rootEl.querySelector("#ga-models-mine-section"); + if (mineSection) mineSection.classList.toggle("d-none", !this.isAuthed); + + await this.loadCatalogue(); + if (this.isAuthed) await this.loadMine(); + this.attachEvents(); + } + + private async loadCatalogue(kind?: string): Promise { + const el = this.cfg.rootEl.querySelector("#ga-models-catalogue"); + if (!el) return; + el.innerHTML = `
      Loading…
      `; + try { + const qs = kind ? `?kind=${encodeURIComponent(kind)}` : ""; + const data = await fetchJson<{ models: ModelSummary[] }>(`${this.cfg.apiBase}/v1/models${qs}`); + el.innerHTML = data.models.length ? data.models.map(renderModelCard).join("") : renderEmptyModels(); + } catch (err) { + el.innerHTML = `
      Failed to load: ${escapeHtml(String(err))}
      `; + } + } + + private async loadMine(): Promise { + const el = this.cfg.rootEl.querySelector("#ga-models-mine"); + if (!el) return; + try { + const data = await fetchJson<{ models: ModelSummary[] }>(`${this.cfg.apiBase}/v1/models/mine`); + el.innerHTML = data.models.length ? data.models.map(renderModelCard).join("") : renderEmptyModels(); + } catch (err) { + el.innerHTML = `
      Failed to load: ${escapeHtml(String(err))}
      `; + } + } + + private attachEvents(): void { + this.cfg.rootEl.querySelectorAll("[data-ga-kind-filter]").forEach((btn) => { + btn.addEventListener("click", () => { + this.cfg.rootEl + .querySelectorAll("[data-ga-kind-filter]") + .forEach((b) => b.classList.toggle("active", b === btn)); + const kind = btn.dataset.gaKindFilter || ""; + void this.loadCatalogue(kind || undefined); + }); + }); + + const form = this.cfg.rootEl.querySelector("#ga-new-model-form"); + form?.addEventListener("submit", async (ev) => { + ev.preventDefault(); + const errEl = this.cfg.rootEl.querySelector("#ga-new-model-error"); + errEl?.classList.add("d-none"); + const title = this.cfg.rootEl.querySelector("#ga-nm-title")!.value.trim(); + const kind = this.cfg.rootEl.querySelector("#ga-nm-kind")!.value; + const provider = this.cfg.rootEl.querySelector("#ga-nm-provider")!.value; + const description = this.cfg.rootEl.querySelector("#ga-nm-description")!.value.trim(); + try { + const data = await fetchJson<{ model: ModelSummary }>(`${this.cfg.apiBase}/v1/models`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ title, kind, provider, description: description || undefined, visibility: "private" }), + }); + window.location.href = `/models/detail/?slug=${encodeURIComponent(data.model.slug)}`; + } catch (err) { + if (errEl) { + errEl.textContent = `Couldn't create model: ${String(err)}`; + errEl.classList.remove("d-none"); + } + } + }); + } +} + +// --------------------------------------------------------------------------- +// Detail page +// --------------------------------------------------------------------------- + +class DetailPage { + private cfg!: ModelsConfig; + private slug = ""; + private model: ModelSummary | null = null; + private versions: ModelVersion[] = []; + private isOwner = false; + + async mount(cfg: ModelsConfig): Promise { + this.cfg = cfg; + const params = new URLSearchParams(window.location.search); + this.slug = params.get("slug") || ""; + if (!this.slug) { + cfg.rootEl.innerHTML = `

      Bad URL — model pages look like /models/detail/?slug=your-model.

      `; + return; + } + + let me: { user: { handle: string } } | null = null; + try { + me = await fetchJson(`${cfg.apiBase}/v1/me`); + } catch { + me = null; + } + + try { + const data = await fetchJson<{ model: ModelSummary; versions: ModelVersion[] }>( + `${cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}`, + ); + this.model = data.model; + this.versions = data.versions; + } catch (err) { + cfg.rootEl.innerHTML = `

      Model not found: ${escapeHtml(String(err))}

      `; + return; + } + + this.isOwner = !!me && !!this.model.owner && me.user.handle === this.model.owner.handle; + this.render(); + this.attachEvents(); + } + + private render(): void { + const m = this.model!; + const root = this.cfg.rootEl; + root.querySelector("#ga-model-title")!.textContent = m.title; + root.querySelector("#ga-model-desc")!.textContent = m.description || "No description yet."; + root.querySelector("#ga-model-meta")!.textContent = + `${KIND_LABELS[m.kind] || m.kind} · ${PROVIDER_LABELS[m.provider] || m.provider} · ${m.visibility}`; + + const versionsEl = root.querySelector("#ga-model-versions"); + if (versionsEl) { + versionsEl.innerHTML = this.versions.length + ? this.versions + .map( + (v) => ` +
    • +
      + v${v.version} + ${v.price_tokens.toLocaleString()} tokens +
      +

      ${escapeHtml(v.provider_model_id)}

      + ${provenanceTag(v)} + ${v.dataset_note ? `

      ${escapeHtml(v.dataset_note)}

      ` : ""} +
    • `, + ) + .join("") + : `
    • No published versions yet.
    • `; + } + + const publishSection = root.querySelector("#ga-publish-version-section"); + publishSection?.classList.toggle("d-none", !this.isOwner); + const providerHint = root.querySelector("#ga-pv-provider-hint"); + if (providerHint) { + providerHint.textContent = + m.provider === "fal_custom" + ? "This is a custom-trained model — base model, training method, and weights_ref are required." + : m.provider === "anthropic" + ? "Provider model id, e.g. claude-opus-5." + : "Provider model id from the Workers AI catalogue, e.g. @cf/black-forest-labs/flux-1-schnell."; + } + root.querySelectorAll(".ga-fal-only").forEach((el) => + el.classList.toggle("d-none", m.provider !== "fal_custom"), + ); + root.querySelectorAll(".ga-code-only").forEach((el) => + el.classList.toggle("d-none", m.kind !== "code"), + ); + + const latest = this.versions[0]; + const renderSection = root.querySelector("#ga-render-section"); + if (renderSection) { + renderSection.classList.toggle("d-none", !latest || m.status !== "active"); + const priceEl = root.querySelector("#ga-render-price"); + if (priceEl && latest) priceEl.textContent = `${latest.price_tokens.toLocaleString()} tokens`; + } + } + + private async publishVersion(): Promise { + const root = this.cfg.rootEl; + const errEl = root.querySelector("#ga-pv-error"); + errEl?.classList.add("d-none"); + const providerModelId = root.querySelector("#ga-pv-provider-model-id")!.value.trim(); + const priceTokens = parseInt(root.querySelector("#ga-pv-price")!.value, 10); + const body: Record = { provider_model_id: providerModelId, price_tokens: priceTokens }; + + if (this.model!.provider === "fal_custom") { + body.training_method = root.querySelector("#ga-pv-training-method")!.value; + body.base_model = root.querySelector("#ga-pv-base-model")!.value.trim(); + body.dataset_note = root.querySelector("#ga-pv-dataset-note")!.value.trim(); + body.weights_ref = root.querySelector("#ga-pv-weights-ref")!.value.trim(); + } else if (this.model!.kind === "code") { + body.system_prompt = root.querySelector("#ga-pv-system-prompt")?.value.trim() || undefined; + } + + try { + await fetchJson(`${this.cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}/versions`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + window.location.reload(); + } catch (err) { + if (errEl) { + errEl.textContent = `Couldn't publish: ${String(err)}`; + errEl.classList.remove("d-none"); + } + } + } + + private async render_(button: HTMLButtonElement): Promise { + const root = this.cfg.rootEl; + const prompt = root.querySelector("#ga-render-prompt")!.value.trim(); + const resultEl = root.querySelector("#ga-render-result")!; + const original = button.textContent; + button.disabled = true; + button.textContent = "Rendering…"; + resultEl.innerHTML = ""; + try { + const data = await fetchJson<{ job: RenderJob }>( + `${this.cfg.apiBase}/v1/models/${encodeURIComponent(this.slug)}/render`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ prompt }), + }, + ); + this.renderResult(data.job, resultEl); + } catch (err) { + resultEl.innerHTML = `
      Render failed: ${escapeHtml(String(err))}
      `; + } finally { + button.disabled = false; + button.textContent = original; + } + } + + private renderResult(job: RenderJob, el: HTMLElement): void { + if (job.status === "failed") { + el.innerHTML = `
      Render failed (${escapeHtml(job.error_code || "unknown")}) — tokens refunded.
      `; + return; + } + const seedLine = `

      seed ${escapeHtml(job.seed)}

      `; + if (job.output_kind === "code" && job.output_text) { + el.innerHTML = `${seedLine}
      ${escapeHtml(job.output_text)}
      `; + } else if (job.output_kind === "image" && job.output_key) { + const src = `${this.cfg.apiBase}/v1/captures/${job.output_key}`; + el.innerHTML = `${seedLine}Render result`; + } else { + el.innerHTML = `${seedLine}

      Render succeeded with no returned output.

      `; + } + } + + private attachEvents(): void { + const root = this.cfg.rootEl; + root.querySelector("#ga-publish-version-form")?.addEventListener("submit", (ev) => { + ev.preventDefault(); + void this.publishVersion(); + }); + root.querySelector("#ga-render-btn")?.addEventListener("click", (ev) => { + void this.render_(ev.currentTarget as HTMLButtonElement); + }); + } +} + +const GAModels = { + async mount(cfg: ModelsConfig) { + installClientErrorReporter({ apiBase: cfg.apiBase, page: `models-${cfg.mode}` }); + if (cfg.mode === "catalogue") await new CataloguePage().mount(cfg); + else await new DetailPage().mount(cfg); + }, +}; + +declare global { + interface Window { + GAModels?: typeof GAModels; + } +} + +window.GAModels = GAModels; +export default GAModels; diff --git a/workers/api/client/studio.ts b/workers/api/client/studio.ts index 396787a..19ada88 100644 --- a/workers/api/client/studio.ts +++ b/workers/api/client/studio.ts @@ -153,6 +153,18 @@ function clearLocal(projectId: number) { } catch {} } +function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (ch) => { + switch (ch) { + case "&": return "&"; + case "<": return "<"; + case ">": return ">"; + case '"': return """; + default: return "'"; + } + }); +} + async function fetchJson(url: string, init?: RequestInit): Promise { const res = await fetch(url, { credentials: "include", ...init }); if (!res.ok) { @@ -209,6 +221,11 @@ class StudioController { private autosaveTimer: ReturnType | null = null; private exportRequests = new Map void>(); private project: ProjectMeta | null = null; + private copilotMode: "generate" | "edit" | "explain" | "params" = "generate"; + // Holds a generate/edit suggestion until the artist explicitly + // accepts it — see ai/copilot.ts for why this is accept-the-whole- + // suggestion rather than per-hunk diffing in v1. + private pendingSuggestion: string | null = null; constructor(cfg: StudioConfig) { this.cfg = cfg; @@ -269,6 +286,7 @@ class StudioController { this.mountEditor(initialContent); this.mountPreviewBridge(); this.bindToolbar(); + this.bindCopilot(); this.startAutosave(); this.startWindowGuards(); @@ -413,6 +431,173 @@ class StudioController { }); } + private readonly COPILOT_PRICES: Record = { + generate: 20, + edit: 15, + explain: 5, + params: 5, + }; + private readonly COPILOT_PLACEHOLDERS: Record = { + generate: "Describe the sketch you want…", + edit: "Describe the change — e.g. \"make the background black\"…", + explain: "(uses your current code — no input needed)", + params: "(uses your current code — no input needed)", + }; + + private async refreshCopilotBalance(): Promise { + const el = document.getElementById("ga-copilot-balance"); + if (!el) return; + try { + const acct = await fetchJson<{ balance: number }>(`${this.cfg.apiBase}/v1/tokens/account`); + el.textContent = `${acct.balance.toLocaleString()} tokens`; + } catch { + el.textContent = "—"; + } + } + + private bindCopilot() { + const toggle = document.getElementById("ga-studio-copilot-toggle"); + const grid = document.getElementById("ga-studio-grid"); + toggle?.addEventListener("click", () => { + const opening = !grid?.classList.contains("ga-copilot-open"); + grid?.classList.toggle("ga-copilot-open"); + document.getElementById("ga-studio-copilot")?.classList.toggle("d-none", !opening); + if (opening) void this.refreshCopilotBalance(); + }); + + const priceEl = document.getElementById("ga-copilot-price"); + const inputEl = document.getElementById("ga-copilot-input") as HTMLTextAreaElement | null; + const updateModeUi = () => { + if (priceEl) priceEl.textContent = `${this.COPILOT_PRICES[this.copilotMode]} tokens`; + if (inputEl) { + inputEl.placeholder = this.COPILOT_PLACEHOLDERS[this.copilotMode]; + const needsInput = this.copilotMode === "generate" || this.copilotMode === "edit"; + inputEl.classList.toggle("d-none", !needsInput); + } + }; + updateModeUi(); + + document.querySelectorAll(".ga-copilot-mode").forEach((btn) => { + btn.addEventListener("click", () => { + document.querySelectorAll(".ga-copilot-mode").forEach((b) => b.classList.toggle("active", b === btn)); + this.copilotMode = (btn.dataset.gaMode as typeof this.copilotMode) || "generate"; + updateModeUi(); + }); + }); + + document.getElementById("ga-copilot-run")?.addEventListener("click", () => { + void this.runCopilot(); + }); + } + + private copilotFeedback(msg: string): void { + const el = document.getElementById("ga-copilot-feedback"); + if (el) el.textContent = msg; + } + + private async runCopilot(): Promise { + const runBtn = document.getElementById("ga-copilot-run") as HTMLButtonElement | null; + const resultEl = document.getElementById("ga-copilot-result"); + const inputEl = document.getElementById("ga-copilot-input") as HTMLTextAreaElement | null; + if (!resultEl || !this.view) return; + const mode = this.copilotMode; + const currentCode = this.view.state.doc.toString(); + const prompt = inputEl?.value.trim() || ""; + if ((mode === "generate" || mode === "edit") && !prompt) { + this.copilotFeedback("Describe what you want first."); + return; + } + + if (runBtn) runBtn.disabled = true; + this.copilotFeedback("Thinking…"); + resultEl.innerHTML = ""; + try { + let path: string; + let body: Record; + if (mode === "generate") { + path = "generate"; + body = { prompt }; + } else if (mode === "edit") { + path = "edit"; + body = { current_code: currentCode, instruction: prompt }; + } else if (mode === "explain") { + path = "explain"; + body = { code: currentCode }; + } else { + path = "params"; + body = { code: currentCode }; + } + + const res = await fetch(`${this.cfg.apiBase}/v1/projects/${this.cfg.projectId}/ai/${path}`, { + method: "POST", + credentials: "include", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + if (res.status === 402) { + const err = (await res.json().catch(() => ({}))) as { balance?: number; shortfall?: number }; + this.copilotFeedback( + `Not enough tokens — need ${err.shortfall ?? "more"} more. `, + ); + resultEl.innerHTML = `Buy tokens`; + return; + } + if (!res.ok) { + const err = (await res.json().catch(() => ({}))) as { error?: string }; + this.copilotFeedback(`Failed: ${err.error ?? res.statusText}`); + return; + } + const data = (await res.json()) as { result: unknown; price_tokens: number }; + this.copilotFeedback(`Spent ${data.price_tokens} tokens.`); + void this.refreshCopilotBalance(); + + if (mode === "generate" || mode === "edit") { + this.pendingSuggestion = data.result as string; + resultEl.innerHTML = ` +
      ${escapeHtml(this.pendingSuggestion)}
      +
      + + +
      `; + resultEl.querySelector("#ga-copilot-accept")?.addEventListener("click", () => this.acceptSuggestion()); + resultEl.querySelector("#ga-copilot-reject")?.addEventListener("click", () => { + this.pendingSuggestion = null; + resultEl.innerHTML = ""; + }); + } else if (mode === "explain") { + resultEl.innerHTML = `

      ${escapeHtml(String(data.result))}

      `; + } else { + const params = data.result as Array<{ name: string; kind: string; default: unknown; line_hint: string }>; + resultEl.innerHTML = params.length + ? `
        ${params + .map((p) => `
      • ${escapeHtml(p.name)} (${escapeHtml(p.kind)}, default ${escapeHtml(String(p.default))})
      • `) + .join("")}
      ` + : `

      Nothing tunable found.

      `; + } + } catch (e) { + this.copilotFeedback(`Failed: ${(e as Error).message}`); + } finally { + if (runBtn) runBtn.disabled = false; + } + } + + /** + * Replaces the whole editor buffer with the pending suggestion — + * the accept-the-whole-suggestion simplification documented in + * ai/copilot.ts, not per-hunk application. Marks the buffer dirty so + * the existing Save flow (and its Cmd/Ctrl+S binding) picks it up + * exactly like a manual edit. + */ + private acceptSuggestion(): void { + if (!this.view || this.pendingSuggestion === null) return; + this.view.dispatch({ + changes: { from: 0, to: this.view.state.doc.length, insert: this.pendingSuggestion }, + }); + this.pendingSuggestion = null; + document.getElementById("ga-copilot-result")!.innerHTML = ""; + this.copilotFeedback("Applied to the editor — remember to Save."); + } + private scheduleReload(forcedCode?: string) { if (this.debounceTimer) clearTimeout(this.debounceTimer); this.debounceTimer = setTimeout(() => { diff --git a/workers/api/client/wallet.ts b/workers/api/client/wallet.ts new file mode 100644 index 0000000..de4523b --- /dev/null +++ b/workers/api/client/wallet.ts @@ -0,0 +1,361 @@ +/** + * /wallet/ — token balance, packs, on-chain purchase, ledger history. + * + * No payment processor: buying a pack sends ETH directly to the + * platform's treasury address, then posts the tx hash to + * POST /v1/tokens/purchase/confirm, which verifies the receipt on-chain + * before crediting the account (see tokens/handlers.ts). Mirrors the + * wallet-connect + send-tx + wait-receipt shape already used by + * client/mint.ts. + */ +import { + createPublicClient, + createWalletClient, + custom, + http, + getAddress, + type EIP1193Provider, + type Hex, +} from "viem"; +import { installClientErrorReporter } from "./lib/clientErrors"; + +declare global { + interface Window { + ethereum?: EIP1193Provider; + GAWallet?: typeof GAWallet; + } +} + +interface WalletConfig { + apiBase: string; + rootEl: HTMLElement; + onUnauthenticated?: () => void; +} + +interface AccountResp { + balance: number; + lifetime_purchased: number; + lifetime_spent: number; + lifetime_earned: number; +} + +interface Pack { + id: number; + slug: string; + title: string; + tokens: number; + price_wei: string; +} + +interface PacksResp { + packs: Pack[]; + purchase_configured: boolean; + chain_id: number | null; + treasury_address: string | null; +} + +interface LedgerEntry { + id: number; + delta: number; + kind: string; + balance_after: number; + ref_kind: string | null; + ref_id: number | null; + memo: string | null; + created_at: number; +} + +function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (ch) => { + switch (ch) { + case "&": return "&"; + case "<": return "<"; + case ">": return ">"; + case '"': return """; + default: return "'"; + } + }); +} + +function fmtTokens(n: number): string { + return n.toLocaleString("en-US"); +} + +// price_wei is a decimal string too large for Number — format to a +// human ETH amount without pulling in a bignum-decimal library. +function weiToEth(weiStr: string): string { + const wei = BigInt(weiStr); + const whole = wei / 1_000_000_000_000_000_000n; + const frac = wei % 1_000_000_000_000_000_000n; + const fracStr = frac.toString().padStart(18, "0").slice(0, 6).replace(/0+$/, ""); + return fracStr ? `${whole}.${fracStr}` : `${whole}`; +} + +async function fetchJson(url: string, init?: RequestInit): Promise { + const res = await fetch(url, { credentials: "include", ...init }); + if (!res.ok) { + let detail = ""; + try { detail = JSON.stringify(await res.json()); } catch {} + throw new Error(`${res.status}: ${detail || res.statusText}`); + } + return (await res.json()) as T; +} + +const KIND_LABELS: Record = { + grant: "Grant", + purchase: "Purchase", + debit: "Spend", + refund: "Refund", + earn: "Earned", + adjust: "Adjustment", +}; + +function renderLedgerRow(e: LedgerEntry): string { + const sign = e.delta > 0 ? "+" : ""; + const cls = e.delta > 0 ? "ga-ledger-credit" : "ga-ledger-debit"; + const when = new Date(e.created_at * 1000).toLocaleString(); + return ` + + ${escapeHtml(when)} + ${escapeHtml(KIND_LABELS[e.kind] || e.kind)} + ${escapeHtml(e.memo || "—")} + ${sign}${fmtTokens(e.delta)} + ${fmtTokens(e.balance_after)} + `; +} + +function renderPackCard(p: Pack, purchaseConfigured: boolean): string { + return ` +
      +

      ${escapeHtml(p.title)}

      +

      ${fmtTokens(p.tokens)} tokens

      +

      ${weiToEth(p.price_wei)} ETH

      + +
      `; +} + +class WalletPage { + private cfg!: WalletConfig; + private treasury: Hex | null = null; + private chainId: number | null = null; + private connectedAddress: Hex | null = null; + + async mount(cfg: WalletConfig): Promise { + this.cfg = cfg; + installClientErrorReporter({ apiBase: cfg.apiBase, page: "wallet" }); + + let me: unknown = null; + try { + me = await fetchJson(`${cfg.apiBase}/v1/me`); + } catch { + me = null; + } + if (!me) { + cfg.onUnauthenticated?.(); + return; + } + + await this.loadAccount(); + await this.loadPacks(); + await this.loadLedger(); + this.attachEvents(); + } + + private async loadAccount(): Promise { + const balEl = this.cfg.rootEl.querySelector("#ga-wallet-balance"); + const purchasedEl = this.cfg.rootEl.querySelector("#ga-wallet-purchased"); + const spentEl = this.cfg.rootEl.querySelector("#ga-wallet-spent"); + const earnedEl = this.cfg.rootEl.querySelector("#ga-wallet-earned"); + if (!balEl) return; + try { + const acct = await fetchJson(`${this.cfg.apiBase}/v1/tokens/account`); + balEl.textContent = fmtTokens(acct.balance); + if (purchasedEl) purchasedEl.textContent = fmtTokens(acct.lifetime_purchased); + if (spentEl) spentEl.textContent = fmtTokens(acct.lifetime_spent); + if (earnedEl) earnedEl.textContent = fmtTokens(acct.lifetime_earned); + } catch { + balEl.textContent = "—"; + } + } + + private async loadPacks(): Promise { + const el = this.cfg.rootEl.querySelector("#ga-wallet-packs"); + if (!el) return; + try { + const data = await fetchJson(`${this.cfg.apiBase}/v1/tokens/packs`); + // Validated + checksummed here rather than trusted verbatim from + // the API — getAddress throws on a malformed address, which we'd + // rather surface as "purchasing unavailable" than as a wallet + // error deep inside the buy flow. + try { + this.treasury = data.treasury_address ? getAddress(data.treasury_address) : null; + } catch { + this.treasury = null; + } + this.chainId = data.chain_id; + if (!data.purchase_configured) { + el.insertAdjacentHTML( + "beforebegin", + `

      Purchasing isn't configured yet — packs are shown, but Buy is disabled.

      `, + ); + } + el.innerHTML = data.packs.map((p) => renderPackCard(p, data.purchase_configured)).join(""); + } catch (err) { + el.innerHTML = `
      Failed to load packs: ${escapeHtml(String(err))}
      `; + } + } + + private async loadLedger(before?: number): Promise { + const bodyEl = this.cfg.rootEl.querySelector("#ga-ledger-body"); + const moreBtn = this.cfg.rootEl.querySelector("#ga-ledger-more"); + if (!bodyEl) return; + try { + const qs = before ? `?before=${before}` : ""; + const data = await fetchJson<{ entries: LedgerEntry[]; next_before: number | null }>( + `${this.cfg.apiBase}/v1/tokens/ledger${qs}`, + ); + const rows = data.entries.map(renderLedgerRow).join(""); + bodyEl.insertAdjacentHTML("beforeend", rows); + if (!before && !data.entries.length) { + bodyEl.innerHTML = `No activity yet.`; + } + if (moreBtn) { + if (data.next_before) { + moreBtn.classList.remove("d-none"); + moreBtn.dataset.before = String(data.next_before); + } else { + moreBtn.classList.add("d-none"); + } + } + } catch (err) { + bodyEl.innerHTML = `Failed to load: ${escapeHtml(String(err))}`; + } + } + + private feedback(msg: string): void { + const el = this.cfg.rootEl.querySelector("#ga-wallet-feedback"); + if (el) el.textContent = msg; + } + + private async ensureConnected(): Promise { + if (this.connectedAddress) return true; + if (!window.ethereum) { + this.feedback("No injected wallet found. Install MetaMask or a Base-compatible wallet."); + return false; + } + try { + const accounts = (await window.ethereum.request({ + method: "eth_requestAccounts", + })) as Hex[]; + if (!accounts?.length) return false; + this.connectedAddress = getAddress(accounts[0]); + return true; + } catch (e) { + this.feedback(`Wallet connect failed: ${(e as Error).message}`); + return false; + } + } + + private async buy(packId: number, button: HTMLButtonElement): Promise { + const treasury = this.treasury; + if (!treasury || this.chainId === null) { + this.feedback("Purchasing isn't configured yet."); + return; + } + if (!(await this.ensureConnected())) return; + // A local const (not `this.connectedAddress` directly) so it + // narrows from `Hex | null` for the eth_sendTransaction call below — + // TS can't carry a field narrowing across the ensureConnected() call. + const from = this.connectedAddress; + if (!from) return; + + const original = button.textContent; + button.disabled = true; + try { + // Re-fetch the pack's current price at buy time rather than + // trusting a value cached in the DOM from page load. + button.textContent = "Preparing…"; + const data = await fetchJson(`${this.cfg.apiBase}/v1/tokens/packs`); + const pack = data.packs.find((p) => p.id === packId); + if (!pack) throw new Error("pack no longer available"); + + await this.ensureChain(this.chainId!); + + button.textContent = "Awaiting wallet…"; + const valueHex = ("0x" + BigInt(pack.price_wei).toString(16)) as Hex; + const txHash = (await window.ethereum!.request({ + method: "eth_sendTransaction", + params: [{ from, to: treasury, value: valueHex }], + })) as Hex; + this.feedback(`Transaction sent: ${txHash.slice(0, 10)}…`); + + button.textContent = "Confirming on-chain…"; + const publicClient = createPublicClient({ transport: http() }); + const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash }); + if (receipt.status !== "success") { + this.feedback("Transaction reverted on-chain."); + return; + } + + button.textContent = "Crediting account…"; + await fetchJson(`${this.cfg.apiBase}/v1/tokens/purchase/confirm`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ pack_id: pack.id, tx_hash: txHash }), + }); + this.feedback(`Purchased ${fmtTokens(pack.tokens)} tokens.`); + await this.loadAccount(); + } catch (e) { + this.feedback(`Purchase failed: ${(e as Error).message}`); + } finally { + button.disabled = false; + button.textContent = original; + } + } + + private async ensureChain(chainId: number): Promise { + if (!window.ethereum) return; + const current = (await window.ethereum.request({ method: "eth_chainId" })) as Hex; + const hex = ("0x" + chainId.toString(16)) as Hex; + if (current.toLowerCase() === hex.toLowerCase()) return; + try { + await window.ethereum.request({ + method: "wallet_switchEthereumChain", + params: [{ chainId: hex }], + }); + } catch { + // Wallet may not have the chain added yet; surfaced by the + // subsequent send failing with a clearer wallet-side error. + } + } + + private attachEvents(): void { + this.cfg.rootEl.addEventListener("click", (ev) => { + const target = ev.target as HTMLElement; + const buyBtn = target.closest(".ga-buy-btn"); + if (buyBtn) { + const id = parseInt(buyBtn.dataset.packId || "", 10); + if (id) void this.buy(id, buyBtn); + return; + } + const moreBtn = target.closest("#ga-ledger-more"); + if (moreBtn) { + const before = parseInt(moreBtn.dataset.before || "", 10); + if (before) void this.loadLedger(before); + } + }); + } +} + +const GAWallet = { + async mount(cfg: WalletConfig) { + await new WalletPage().mount(cfg); + }, +}; + +window.GAWallet = GAWallet; +export default GAWallet; diff --git a/workers/api/package.json b/workers/api/package.json index 1cef2be..06d5112 100644 --- a/workers/api/package.json +++ b/workers/api/package.json @@ -24,7 +24,10 @@ "build:feed": "esbuild client/feed.ts --bundle --format=esm --target=es2020 --minify --sourcemap=linked --outfile=../../assets/js/ga-feed.js --define:process.env.NODE_ENV=\\\"production\\\" --tree-shaking=true", "build:token-detail": "esbuild client/token-detail.ts --bundle --format=esm --target=es2020 --minify --sourcemap=linked --outfile=../../assets/js/ga-token-detail.js --define:process.env.NODE_ENV=\\\"production\\\" --tree-shaking=true", "build:galleries": "esbuild client/galleries.ts --bundle --format=esm --target=es2020 --minify --sourcemap=linked --outfile=../../assets/js/ga-galleries.js --define:process.env.NODE_ENV=\\\"production\\\" --tree-shaking=true", - "build:all": "npm run build:client && npm run build:dashboard && npm run build:studio && npm run build:profile && npm run build:project-detail && npm run build:profile-editor && npm run build:mint && npm run build:briefs && npm run build:explore && npm run build:search && npm run build:feed && npm run build:token-detail && npm run build:galleries", + "build:wallet": "esbuild client/wallet.ts --bundle --format=esm --target=es2020 --minify --sourcemap=linked --outfile=../../assets/js/ga-wallet.js --define:process.env.NODE_ENV=\\\"production\\\" --tree-shaking=true", + "build:models": "esbuild client/models.ts --bundle --format=esm --target=es2020 --minify --sourcemap=linked --outfile=../../assets/js/ga-models.js --define:process.env.NODE_ENV=\\\"production\\\" --tree-shaking=true", + "build:datasets": "esbuild client/datasets.ts --bundle --format=esm --target=es2020 --minify --sourcemap=linked --outfile=../../assets/js/ga-datasets.js --define:process.env.NODE_ENV=\\\"production\\\" --tree-shaking=true", + "build:all": "npm run build:client && npm run build:dashboard && npm run build:studio && npm run build:profile && npm run build:project-detail && npm run build:profile-editor && npm run build:mint && npm run build:briefs && npm run build:explore && npm run build:search && npm run build:feed && npm run build:token-detail && npm run build:galleries && npm run build:wallet && npm run build:models && npm run build:datasets", "migrate:local": "wrangler d1 migrations apply DB --local", "migrate:prod": "wrangler d1 migrations apply DB --env production --remote" }, diff --git a/workers/api/scripts/smoke_api.mjs b/workers/api/scripts/smoke_api.mjs index 3ea87a4..4d2d826 100644 --- a/workers/api/scripts/smoke_api.mjs +++ b/workers/api/scripts/smoke_api.mjs @@ -1078,6 +1078,80 @@ cookie = myCookie; } } +// ---- Studio Copilot (Task #22) --------------------------------------- +// Fresh account so its 200-token signup grant covers all four actions +// (20 + 15 + 5 + 5 = 45 tokens) with room to spare. +{ + const coder = privateKeyToAccount(generatePrivateKey()); + await login(coder); + + const proj = await api("POST", "/v1/projects", { title: "Copilot Smoke", engine: "p5" }); + const projId = proj.data?.project?.id ?? proj.data?.id; + + { + const r = await api("POST", `/v1/projects/${projId}/ai/generate`, { prompt: "a field of drifting particles" }); + record( + "POST ai/generate (AI_MOCK)", + r.status === 200 && typeof r.data?.result === "string" && r.data.result.length > 0, + JSON.stringify(r.data).slice(0, 150), + ); + } + { + const r = await api("POST", `/v1/projects/${projId}/ai/edit`, { + current_code: "function setup() { createCanvas(400,400); }", + instruction: "make the background black", + }); + record( + "POST ai/edit (AI_MOCK)", + r.status === 200 && typeof r.data?.result === "string", + JSON.stringify(r.data).slice(0, 150), + ); + } + { + const r = await api("POST", `/v1/projects/${projId}/ai/explain`, { code: "function draw(){background(0);}" }); + record( + "POST ai/explain (AI_MOCK)", + r.status === 200 && typeof r.data?.result === "string", + JSON.stringify(r.data).slice(0, 150), + ); + } + { + const r = await api("POST", `/v1/projects/${projId}/ai/params`, { code: "let particleCount = 200;" }); + record( + "POST ai/params (AI_MOCK) returns an array", + r.status === 200 && Array.isArray(r.data?.result), + JSON.stringify(r.data).slice(0, 150), + ); + } + { + const r = await api("POST", `/v1/projects/${projId}/ai/edit`, { current_code: "x", instruction: "" }); + record( + "ai/edit rejects empty instruction", + r.status === 400 && r.data?.error === "invalid_instruction", + JSON.stringify(r.data), + ); + } + { + const r = await api("GET", "/v1/tokens/account"); + record( + "copilot debits landed (45 tokens across 4 actions)", + r.status === 200 && r.data?.lifetime_spent === 45, + JSON.stringify(r.data), + ); + } + { + // A stranger can't run the copilot against someone else's project. + const stranger = privateKeyToAccount(generatePrivateKey()); + await login(stranger); + const r = await api("POST", `/v1/projects/${projId}/ai/generate`, { prompt: "hi" }); + record( + "ai/generate on a non-owned project → 403", + r.status === 403, + `status=${r.status}`, + ); + } +} + const failed = results.filter((r) => !r.ok); console.log(`\n=== ${results.length - failed.length}/${results.length} passed ===`); if (failed.length) { diff --git a/workers/api/src/ai/copilot.ts b/workers/api/src/ai/copilot.ts new file mode 100644 index 0000000..7a09ea4 --- /dev/null +++ b/workers/api/src/ai/copilot.ts @@ -0,0 +1,154 @@ +import Anthropic from "@anthropic-ai/sdk"; +import type { Env } from "../types"; + +/** + * Studio Copilot — the platform's own built-in code assistant, distinct + * from the render-model marketplace (src/ai/inference.ts / db/render.ts). + * A model registry entry is a creator-published, token-metered product + * someone else can render; the copilot is a fixed platform feature tied + * to a project's own code in the Studio editor. Both call Claude, but + * they're separate surfaces on purpose — publishing a model is a + * creative act with its own provenance and earnings; asking the + * copilot to edit YOUR sketch is not. + * + * Calls debit the same render-token ledger (one currency platform-wide, + * not two parallel ones) — see projects/ai.ts for the debit/refund + * wiring. This module only knows how to call Claude. + * + * SIMPLIFICATION, stated plainly rather than silently under-delivered: + * `editSketch` returns the full revised source, not a per-hunk unified + * diff. A true reviewable-hunks UI (as sketched in the design brief) + * needs a diff-rendering library on the client that isn't in this + * project's dependencies yet; shipping a fabricated "diff" that's + * actually a whole-file replacement dressed up as hunks would be worse + * than being upfront that v1 is accept-or-reject-the-whole-suggestion. + */ + +export class CopilotError extends Error { + constructor( + message: string, + public code: string, + ) { + super(message); + } +} + +function isAiMock(env: Env): boolean { + return env.AI_MOCK === "1"; +} + +const DETERMINISM_RULE = + "Output only self-contained JavaScript for the given engine (p5.js, " + + "three.js, a GLSL shader harness, or plain canvas). No network calls, " + + "no external imports, no Date.now() or Math.random() for anything that " + + "affects the rendered output — use a seeded PRNG if randomness is " + + "needed. Return code only: no prose, no markdown fences."; + +async function complete( + env: Env, + system: string, + userMessage: string, +): Promise { + if (!env.ANTHROPIC_API_KEY) { + throw new CopilotError("ANTHROPIC_API_KEY is not configured", "provider_unconfigured"); + } + const client = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY }); + let message; + try { + message = await client.messages.create({ + model: "claude-opus-5", + max_tokens: 4096, + system, + messages: [{ role: "user", content: userMessage }], + thinking: { type: "adaptive" }, + }); + } catch (e) { + throw new CopilotError( + e instanceof Error ? e.message : "anthropic request failed", + "provider_error", + ); + } + const text = message.content + .filter((b): b is Anthropic.TextBlock => b.type === "text") + .map((b) => b.text) + .join("\n") + .trim(); + if (!text) throw new CopilotError("empty response from model", "provider_error"); + return text; +} + +const MOCK_SKETCH = (engine: string, prompt: string) => + `// mock generate — engine=${engine}\n` + + `// prompt: ${prompt.slice(0, 120)}\n` + + `function setup() { createCanvas(400, 400); }\n` + + `function draw() { background(0); }\n`; + +/** POST /v1/projects/:id/ai/generate — a new sketch from a prompt. */ +export async function generateSketch( + env: Env, + input: { engine: string; prompt: string }, +): Promise { + if (isAiMock(env)) return MOCK_SKETCH(input.engine, input.prompt); + const system = + `You write ${input.engine} generative-art sketches for creative coders. ${DETERMINISM_RULE}`; + return complete(env, system, input.prompt); +} + +/** POST /v1/projects/:id/ai/edit — revise existing code per an instruction. */ +export async function editSketch( + env: Env, + input: { engine: string; currentCode: string; instruction: string }, +): Promise { + if (isAiMock(env)) { + return `${input.currentCode}\n// mock edit: ${input.instruction.slice(0, 80)}\n`; + } + const system = + `You edit ${input.engine} generative-art sketches for creative coders. ` + + `You are given the current source and an instruction; return the FULL ` + + `revised source, not a diff or partial snippet. ${DETERMINISM_RULE}`; + const userMessage = `Current code:\n${input.currentCode}\n\nInstruction: ${input.instruction}`; + return complete(env, system, userMessage); +} + +/** POST /v1/projects/:id/ai/explain — plain-language walkthrough of code. */ +export async function explainSketch(env: Env, code: string): Promise { + if (isAiMock(env)) return "mock explanation: this sketch sets up a canvas and draws a background."; + const system = + "Explain the given generative-art sketch's code in plain language for " + + "an artist who codes but didn't write this particular sketch. Cover " + + "what it draws, what varies per run (seed/randomness), and any " + + "tunable-looking constants. Prose only, no code blocks."; + return complete(env, system, code); +} + +export interface ParamGuess { + name: string; + kind: "number" | "string" | "boolean"; + default: unknown; + line_hint: string; +} + +/** POST /v1/projects/:id/ai/params — guess tunable parameters from code. */ +export async function extractParams(env: Env, code: string): Promise { + if (isAiMock(env)) { + return [{ name: "particleCount", kind: "number", default: 200, line_hint: "mock" }]; + } + const system = + "Find constants in the given sketch code that look like tunable " + + "creative parameters (particle counts, speeds, color choices, sizes — " + + "not canvas dimensions or setup boilerplate). Respond with ONLY a JSON " + + 'array, no prose, each item shaped exactly {"name": string, "kind": ' + + '"number"|"string"|"boolean", "default": , "line_hint": string}. ' + + "Return [] if nothing looks tunable."; + const text = await complete(env, system, code); + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw new CopilotError("model did not return valid JSON", "provider_error"); + } + if (!Array.isArray(parsed)) { + throw new CopilotError("model response was not a JSON array", "provider_error"); + } + return parsed as ParamGuess[]; +} diff --git a/workers/api/src/index.ts b/workers/api/src/index.ts index 71648fc..44f8c7b 100644 --- a/workers/api/src/index.ts +++ b/workers/api/src/index.ts @@ -32,6 +32,12 @@ import { uploadCaptureHandler, getCaptureHandler, } from "./projects/studio"; +import { + aiGenerateHandler, + aiEditHandler, + aiExplainHandler, + aiParamsHandler, +} from "./projects/ai"; import { getUserByHandleHandler, followHandler, @@ -149,6 +155,14 @@ v1.post("/projects/:id{[0-9]+}/commit", requireAuth, commitProjectFileHandler); v1.post("/projects/:id{[0-9]+}/captures", requireAuth, uploadCaptureHandler); v1.get("/captures/:rest{.+}", getCaptureHandler); +// Studio Copilot (owner-only — distinct from the render-model +// marketplace's public /v1/models/:slug/render). Each debits the +// render-token ledger; see projects/ai.ts. +v1.post("/projects/:id{[0-9]+}/ai/generate", requireAuth, aiGenerateHandler); +v1.post("/projects/:id{[0-9]+}/ai/edit", requireAuth, aiEditHandler); +v1.post("/projects/:id{[0-9]+}/ai/explain", requireAuth, aiExplainHandler); +v1.post("/projects/:id{[0-9]+}/ai/params", requireAuth, aiParamsHandler); + // Mint flow (Task #6). `prepare` is public for the `mint` phase // (collectors don't need a SIWE session) and gates owner-only phases // (deploy / lock_cid) inside the handler. confirm-deploy is owner-only; diff --git a/workers/api/src/projects/ai.ts b/workers/api/src/projects/ai.ts new file mode 100644 index 0000000..ccc1472 --- /dev/null +++ b/workers/api/src/projects/ai.ts @@ -0,0 +1,240 @@ +import type { Context } from "hono"; +import type { Env } from "../types"; +import type { AuthVariables } from "../auth/middleware"; +import { getAuthUser } from "../auth/middleware"; +import { getProjectById } from "../db/projects"; +import { checkRateLimit } from "../lib/rateLimit"; +import { applyLedgerEntry } from "../db/tokens"; +import { + generateSketch, + editSketch, + explainSketch, + extractParams, + CopilotError, +} from "../ai/copilot"; + +/** + * Studio Copilot routes. Owner-only — the copilot edits/generates + * code for a project the caller owns, unlike the render-model + * marketplace which is open to any renderer. See ai/copilot.ts for + * why this is a separate surface from the model registry. + * + * Every call debits the render-token ledger before the Anthropic + * request and refunds in full on failure — the same discipline as + * render_jobs, without a persisted job row: these are ephemeral + * editor assists, not published, re-runnable renders someone would + * browse later. + */ + +const PRICE_TOKENS: Record<"generate" | "edit" | "explain" | "params", number> = { + generate: 20, + edit: 15, + explain: 5, + params: 5, +}; + +const PROMPT_MAX = 2000; +const CODE_MAX = 100_000; +const INSTRUCTION_MAX = 1000; + +function badRequest(c: Context, error: string, detail?: unknown) { + return c.json({ error, detail }, 400); +} + +async function loadOwnedProject( + c: Context<{ Bindings: Env; Variables: AuthVariables }>, +) { + const id = parseInt(c.req.param("id") || "", 10); + if (!id || Number.isNaN(id)) return { error: badRequest(c, "invalid_id") }; + const project = await getProjectById(c.env.DB, id); + if (!project) return { error: c.json({ error: "not_found" }, 404) }; + const session = getAuthUser(c); + if (project.owner_id !== session.uid) { + return { error: c.json({ error: "forbidden" }, 403) }; + } + return { project, session }; +} + +/** + * Debit → call Claude → settle. Shared by all four routes so the + * debit/refund discipline can't drift between them. + */ +async function withDebit( + c: Context<{ Bindings: Env; Variables: AuthVariables }>, + action: keyof typeof PRICE_TOKENS, + session: { uid: number }, + run: () => Promise, +): Promise { + const price = PRICE_TOKENS[action]; + const idempotencyKey = `copilot:${action}:${session.uid}:${crypto.randomUUID()}`; + const debit = await applyLedgerEntry(c.env.DB, { + userId: session.uid, + delta: -price, + kind: "debit", + idempotencyKey, + refKind: "copilot", + refId: null, + memo: `copilot: ${action}`, + }); + if (debit.status === "insufficient") { + return c.json( + { error: "insufficient_balance", balance: debit.balance, shortfall: debit.shortfall }, + 402, + ); + } + try { + const result = await run(); + return c.json({ result, price_tokens: price }, 200); + } catch (e) { + try { + await applyLedgerEntry(c.env.DB, { + userId: session.uid, + delta: price, + kind: "refund", + idempotencyKey: `${idempotencyKey}:refund`, + refKind: "copilot", + refId: null, + memo: `copilot refund: ${action}`, + }); + } catch (refundErr) { + console.error("copilot_refund_failed", refundErr); + } + const code = e instanceof CopilotError ? e.code : "copilot_failed"; + return c.json({ error: code }, code === "provider_unconfigured" ? 503 : 502); + } +} + +interface GenerateBody { + prompt?: unknown; +} + +/** POST /v1/projects/:id/ai/generate */ +export async function aiGenerateHandler( + c: Context<{ Bindings: Env; Variables: AuthVariables }>, +) { + const loaded = await loadOwnedProject(c); + if (loaded.error) return loaded.error; + const { project, session } = loaded; + + const rl = await checkRateLimit(c.env.RATE_LIMIT, { + key: `ai:generate:${session!.uid}`, + limit: 30, + windowSeconds: 3600, + }); + if (!rl.ok) return c.json({ error: "rate_limited", reset_at: rl.resetAt }, 429); + + let body: GenerateBody; + try { + body = await c.req.json(); + } catch { + return badRequest(c, "invalid_json"); + } + const prompt = typeof body.prompt === "string" ? body.prompt.trim() : ""; + if (!prompt || prompt.length > PROMPT_MAX) return badRequest(c, "invalid_prompt", { max: PROMPT_MAX }); + + return withDebit(c, "generate", session!, () => + generateSketch(c.env, { engine: project!.engine, prompt }), + ); +} + +interface EditBody { + current_code?: unknown; + instruction?: unknown; +} + +/** POST /v1/projects/:id/ai/edit */ +export async function aiEditHandler( + c: Context<{ Bindings: Env; Variables: AuthVariables }>, +) { + const loaded = await loadOwnedProject(c); + if (loaded.error) return loaded.error; + const { project, session } = loaded; + + const rl = await checkRateLimit(c.env.RATE_LIMIT, { + key: `ai:edit:${session!.uid}`, + limit: 30, + windowSeconds: 3600, + }); + if (!rl.ok) return c.json({ error: "rate_limited", reset_at: rl.resetAt }, 429); + + let body: EditBody; + try { + body = await c.req.json(); + } catch { + return badRequest(c, "invalid_json"); + } + const currentCode = typeof body.current_code === "string" ? body.current_code : ""; + if (!currentCode || currentCode.length > CODE_MAX) return badRequest(c, "invalid_current_code", { max: CODE_MAX }); + const instruction = typeof body.instruction === "string" ? body.instruction.trim() : ""; + if (!instruction || instruction.length > INSTRUCTION_MAX) { + return badRequest(c, "invalid_instruction", { max: INSTRUCTION_MAX }); + } + + return withDebit(c, "edit", session!, () => + editSketch(c.env, { engine: project!.engine, currentCode, instruction }), + ); +} + +interface CodeBody { + code?: unknown; +} + +function readCode(body: CodeBody): string | null { + const code = typeof body.code === "string" ? body.code : ""; + if (!code || code.length > CODE_MAX) return null; + return code; +} + +/** POST /v1/projects/:id/ai/explain */ +export async function aiExplainHandler( + c: Context<{ Bindings: Env; Variables: AuthVariables }>, +) { + const loaded = await loadOwnedProject(c); + if (loaded.error) return loaded.error; + const { session } = loaded; + + const rl = await checkRateLimit(c.env.RATE_LIMIT, { + key: `ai:explain:${session!.uid}`, + limit: 60, + windowSeconds: 3600, + }); + if (!rl.ok) return c.json({ error: "rate_limited", reset_at: rl.resetAt }, 429); + + let body: CodeBody; + try { + body = await c.req.json(); + } catch { + return badRequest(c, "invalid_json"); + } + const code = readCode(body); + if (code === null) return badRequest(c, "invalid_code", { max: CODE_MAX }); + + return withDebit(c, "explain", session!, () => explainSketch(c.env, code)); +} + +/** POST /v1/projects/:id/ai/params */ +export async function aiParamsHandler( + c: Context<{ Bindings: Env; Variables: AuthVariables }>, +) { + const loaded = await loadOwnedProject(c); + if (loaded.error) return loaded.error; + const { session } = loaded; + + const rl = await checkRateLimit(c.env.RATE_LIMIT, { + key: `ai:params:${session!.uid}`, + limit: 60, + windowSeconds: 3600, + }); + if (!rl.ok) return c.json({ error: "rate_limited", reset_at: rl.resetAt }, 429); + + let body: CodeBody; + try { + body = await c.req.json(); + } catch { + return badRequest(c, "invalid_json"); + } + const code = readCode(body); + if (code === null) return badRequest(c, "invalid_code", { max: CODE_MAX }); + + return withDebit(c, "params", session!, () => extractParams(c.env, code)); +} diff --git a/workers/api/src/types.ts b/workers/api/src/types.ts index 448e823..d65abb5 100644 --- a/workers/api/src/types.ts +++ b/workers/api/src/types.ts @@ -104,6 +104,14 @@ export interface Env { // dispatch/poll cron path used in production. Production must NEVER // set TRAINING_MOCK. TRAINING_MOCK?: string; + // --- Studio Copilot ------------------------------------------------------ + // OPT-IN ONLY, same convention as RENDER_MOCK/TRAINING_MOCK. When + // exactly "1", the four /v1/projects/:id/ai/* routes (ai/copilot.ts) + // return deterministic canned output with no network call. Separate + // from RENDER_MOCK because the copilot is a distinct surface from the + // render-model marketplace, even though both call Claude. Production + // must NEVER set AI_MOCK. + AI_MOCK?: string; } export interface ProjectMintState {