var zt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Te=e=>new Promise(function(t){let n=new MessageChannel;n.port1.onmessage=function(r){t(r.data)},navigator.serviceWorker.controller==null&&window.location.reload(),navigator.serviceWorker.controller.postMessage(e,[n.port2])}),It=()=>{Te({type:"SET_DIR_HANDLE",data:null}),clearInterval(Ke),Ke=null},R,Ke,yr=()=>{Ke==null&&(Ke=setInterval(()=>{Te({type:"SET_DIR_HANDLE",data:R})},1e4))},xr=async()=>(R=await globalThis.showDirectoryPicker(),await Te({type:"SET_DIR_HANDLE",data:R}),R),ot=e=>{e.navigator.serviceWorker.ready.then(()=>{e.navigator.serviceWorker.addEventListener("message",t=>{t.data.type=="GET_DIR_HANDLE"&&t.ports[0].postMessage(R)})})},kr=()=>navigator.serviceWorker.register("service_worker.js").then(()=>navigator.serviceWorker.ready).then(()=>ot(globalThis)).then(()=>Te({type:"GET_DIR_HANDLE"})).then(async e=>{if(e==null||await e.queryPermission()!="granted")return null;try{await e.entries().next()}catch{return null}return R=e,R}),st=async(e,t,n=!1,r)=>{typeof t=="string"&&(t=t.split("/"));let[i,...o]=t;if(o.length==0)return n?await e.getDirectoryHandle(i,r):await e.getFileHandle(i,r);{let l=await e.getDirectoryHandle(i);return st(l,o,n,r)}},Mt=async(e,t)=>{let r=await(await st(R,e)).createWritable();await r.write(t),await r.close()},wr=e=>e.name=="node_modules"||e.name.startsWith("."),Sr=async e=>await(await e.getFile()).text(),Rt=async(e,t)=>{if(e.kind=="directory"){let n=[];for await(let[r,i]of e)wr(i)||n.push(i);return{name:e.name,path:t,kind:"directory",children:(await Promise.all(n.map(r=>Rt(r,t==null?r.name:t+"/"+r.name)))).sort((r,i)=>r.name.localeCompare(i.name))}}else{if(e.kind=="file")return{name:e.name,path:t,kind:"file",contents:await Sr(e)};throw new Error("unknown kind")}},Bt=(e,t)=>st(R,e,t,{create:!0}),he=async e=>{let t;return e?t=await xr():t=await kr(),t==null?null:(yr(),Rt(t,null))};window.addEventListener("unload",()=>{globalThis.app_window!=null&&globalThis.app_window.close()});vr(window);function vr(e){e.onerror=(t,n,r,i,o)=>{o instanceof globalThis.app_window.Error||V.set_status(t)},e.addEventListener("unhandledrejection",t=>{let n=t.reason;n instanceof globalThis.app_window.Error||V.set_status(n)})}var br=new URL("./__leporello_files",globalThis.location),lt=e=>{let t=br+"/";return e.html_file==""?t+"__leporello_blank.html":t+e.html_file+"?leporello"},Vt=e=>{ot(e),me=!1,x("reload_app_window_finished")},ie,Wt=e=>{me=!0,ie=document.createElement("iframe"),ie.src=lt(e),ie.setAttribute("hidden",""),document.body.appendChild(ie),globalThis.app_window=ie.contentWindow,Jt(globalThis.app_window)},Ut=e=>{me=!0,x("open_app_window",!0),globalThis.app_window.close(),globalThis.app_window=open(lt(e)),Jt(globalThis.app_window)},Jt=e=>{let t=()=>{let i=e.performance.getEntriesByType("navigation")[0];return i!=null&&i.loadEventEnd>0},n=()=>{t()?(r(),Vt(e)):e.addEventListener("load",()=>{r(),Vt(e)},{once:!0})},r=()=>{e.addEventListener("unload",i=>{setTimeout(()=>{e.closed?e==globalThis.app_window&&(x("open_app_window",!1),globalThis.app_window=ie.contentWindow,at(C())):n()},100)})};n()},me=!1,at=e=>{if(!me){if(me=!0,e==null)throw new Error("illegal state");globalThis.app_window.location=lt(e)}};var s=ts;var Er=e=>e instanceof Error||e instanceof globalThis.app_window.Error,Kr=e=>e?.[Symbol.toStringTag]=="Promise",ct=e=>e.clazz==null||e.clazz=="Object",$e=e=>e==null?null:e.clazz=="Promise"?e.status==null?null:$e(e.status.ok?e.status.value:e.status.error):e.array_entries!=null?Array.from(e.array_entries).map((t,n)=>[n,t]):e.object_entries,Ht=e=>{if(e.string!=null)return e.string;let t=e.array_entries??e.object_entries;return t==null?"":["Array","Set","Map"].includes(e.clazz)?e.clazz+"("+t.length+")":ct(e)?"":e.clazz},W=(e,t=!1)=>{let n=typeof e;if(e===null)return"null";if(e===void 0)return"undefined";if(n=="function")return"fn "+(e.name==""?"anonymous":e.name);if(n=="string")return JSON.stringify(e);if(n!="object")return e.toString();if(e.string!=null)return e.string;if(e.clazz=="Promise")return e.status==null?"Promise":e.status.ok?`Promise`:`Promise`;if(e.array_entries!=null){if(t)return e.clazz+"("+e.array_entries.length+")";{let[i,o,l]=e.clazz=="Array"?["[","]",""]:["{","}",e.clazz+" "];return l+i+e.array_entries.map(a=>W(a,!0)).join(", ")+o}}let r=ct(e)?"":e.clazz+" ";if(t)return ct(e)?e.object_entries.length==0?r+"{}":"{\u2026}":e.clazz;{let i="{"+e.object_entries.map(([o,l])=>{let a=e.clazz=="Map"?W(o,!0):o,d=W(l,!0);return`${a}: ${d}`}).join(", ")+"}";return r+i}},Ce=e=>{let t=typeof e;return e===null?"null":e===void 0?"undefined":t=="function"?"fn "+e.name:t=="string"?JSON.stringify(e):t!="object"?e.toString():Kr(e)?e.status==null?"Promise ":e.status.ok?`Promise `:`Promise `:Er(e)?e.toString():Array.isArray(e)?"[\u2026]":(e.constructor?.name==null||e.constructor?.name=="Object"?"":e.constructor.name+" ")+"{\u2026}"};function u(e,t,...n){let r=document.createElement(e);if(typeof t=="string")r.setAttribute("class",t);else{let i=t;for(let o in i){let l=i[o];["change","click"].includes(o)?r.addEventListener(o,l):o=="checked"?i[o]&&r.setAttribute(o,"checked"):r.setAttribute(o,l)}}return n.forEach(i=>{let o=l=>{if(typeof l>"u")throw new Error("illegal state");l!==null&&l!==!1&&r.appendChild(typeof l=="string"?document.createTextNode(l):l)};Array.isArray(i)?i.forEach(o):o(i)}),r}function Tr(e){let t=e.name==""?"anonymous":e.name,n=e.__location==null?`${t}`:`fn ${t}`,r=document.createElement("div");r.innerHTML=n;let i=r.children[0];return e.__location!=null&&i.addEventListener("click",o=>{o.stopPropagation(),x("goto_location",e.__location)}),i}function $(e){return typeof e=="function"?Tr(e):Ce(e)}function Y(e,t=", "){let n=[];for(let r=0;r{t.offsetTop-e.scrollTop-e.offsetTop<0&&t.scrollIntoView(!0),t.offsetTop-e.scrollTop-e.offsetTop-e.clientHeight+t.clientHeight>0&&t.scrollIntoView(!1)};var G=(e,t)=>{if(t.length!=0){let[n,...r]=t,i=$e(e).find(([o,l])=>o==n)[1];return G(i,r)}else{let n=$e(e),r=n!=null&&n.length>0;return{displayed_entries:n,header:W(e),short_header:r?Ht(e):null,is_exp:r}}},Fe=class{constructor({container:t,event_target:n=t,scroll_to_element:r,on_escape:i=()=>{},on_enter:o=()=>{}}={}){this.container=t,this.scroll_to_element=r,this.on_escape=i,n.addEventListener("keydown",l=>{if(l.key=="F1"){this.on_escape();return}if(l.key=="Enter"){o();return}let a=G(this.value,this.current_path);if(l.key=="ArrowDown"||l.key=="j")if(l.preventDefault(),a.is_exp&&this.is_expanded(this.current_path))this.select_path(this.current_path.concat(a.displayed_entries[0][0]));else{let d=_=>{if(_.length==0)return null;let h=_.slice(0,_.length-1),f=G(this.value,h).displayed_entries,p=f.findIndex(([g,k])=>g==_[_.length-1]),m=f[p+1];return m==null?d(h):[...h,m[0]]},c=d(this.current_path);c!=null&&this.select_path(c)}if(l.key=="ArrowUp"||l.key=="k"){if(l.preventDefault(),this.current_path.length==0){this.on_escape();return}let d=this.current_path.slice(0,this.current_path.length-1),c=G(this.value,d).displayed_entries,_=c.findIndex(([f,p])=>f==this.current_path[this.current_path.length-1]),h=c[_-1];if(h==null)this.select_path(d);else{let f=p=>{let m=G(this.value,p);if(!m.is_exp||!this.is_expanded(p))return p;{let g=m.displayed_entries.map(([k,y])=>k);return f([...p,g[g.length-1]])}};this.select_path(f([...d,h[0]]))}}if(l.key=="ArrowLeft"||l.key=="h"){l.preventDefault();let d=this.is_expanded(this.current_path);if(!a.is_exp||!d)if(this.current_path.length!=0){let c=this.current_path.slice(0,this.current_path.length-1);this.select_path(c)}else this.on_escape();else this.toggle_expanded()}if((l.key=="ArrowRight"||l.key=="l")&&(l.preventDefault(),a.is_exp))if(!this.is_expanded(this.current_path))this.toggle_expanded();else{let c=G(this.value,this.current_path).displayed_entries;this.select_path([...this.current_path,c[0][0]])}})}get_node_data(t,n=this.node_data){if(t.length==0)return n;{let[r,...i]=t;return this.get_node_data(i,n.children[r])}}is_expanded(t){return this.get_node_data(t).is_expanded}on_click(t){this.select_path(t),this.toggle_expanded()}render(t,n,r){this.value=n,this.node_data=r;let i=[];this.container.appendChild(this.render_value_explorer_node(i,this.node_data)),this.select_path(i)}select_path(t){if(this.current_path!=null&&this.set_active(this.current_path,!1),this.current_path=t,this.set_active(this.current_path,!0),document.contains(this.container)){let n=this.get_node_data(t).el.getElementsByClassName("value_explorer_header")[0];this.scroll_to_element==null?oe(this.container.parentNode,n):this.scroll_to_element(n)}}set_active(t,n){let r=this.get_node_data(t).el.getElementsByClassName("value_explorer_header")[0];n?r.classList.add("active"):r.classList.remove("active")}set_expanded(t){if(typeof t=="boolean")return this.set_expanded(()=>t);let n=this.get_node_data(this.current_path);n.is_expanded=t(n.is_expanded);let r=n.el,i=this.render_value_explorer_node(this.current_path,n);r.parentNode.replaceChild(i,r)}toggle_expanded(){this.set_expanded(t=>!t),this.set_active(this.current_path,!0)}render_value_explorer_node(t,n){let r=t.length==0,i=t.at(-1),{displayed_entries:o,header:l,short_header:a,is_exp:d}=G(this.value,t),c=d&&n.is_expanded;n.children??={};let _=u("div","value_explorer_node",u("span",{class:"value_explorer_header",click:this.on_click.bind(this,t)},u("span","expand_icon",d?c?"\u25BC":"\u25B6":"\xA0"),r?null:u("span","value_explorer_key",typeof i=="string"?i:W(i),": "),r||!d||!c?l:i=="*arguments*"?"":a),d&&c?o.map(([h,f])=>(n.children[h]??={},this.render_value_explorer_node([...t,h],n.children[h]))):[]);return n.el=_,_}};var Cr=(e,{on_change:t,on_change_selection:n,is_change_selection_supressed:r,on_change_immediate:i})=>{let l,a=()=>{l={}};a();let d=()=>{l.change_args!=null?t(...l.change_args):l.change_selection_args!=null&&n(...l.change_selection_args),a()};e.on("change",(...c)=>{l.immediate_change_fired||(l.immediate_change_fired=!0,i()),l.tid!=null&&clearTimeout(l.tid),l.change_args=c,l.tid=setTimeout(()=>{l.tid=null,d()},1e3)}),e.on("changeSelection",(...c)=>{r()||l.tid==null&&(l.change_selection_args=c,l.is_flush_set||(l.is_flush_set=!0,Promise.resolve().then(()=>{l.tid==null&&d()})))})};function $r(e,t){let n=e.renderer;n.$loop.changes?n.once("afterRender",t):t()}var De=class{constructor(t,n){this.ui=t,this.editor_container=n,this.make_resizable(),this.markers={},this.sessions={},this.ace_editor=globalThis.ace.edit(this.editor_container),this.ace_editor.setOptions({behavioursEnabled:!1,scrollPastEnd:100,enableLiveAutocompletion:!1,enableBasicAutocompletion:!0}),Cr(this.ace_editor,{on_change:()=>{try{x("input",this.ace_editor.getValue(),this.get_cursor_position())}catch(r){console.error(r),this.ui.set_status(r.message)}},on_change_immediate:()=>{this.unembed_value_explorer(),this.clear_parse_result()},on_change_selection:()=>{try{this.is_change_selection_supressed||x("move_cursor",this.get_cursor_position())}catch(r){console.error(r),this.ui.set_status(r.message)}},is_change_selection_supressed:()=>this.is_change_selection_supressed}),this.focus(),this.init_keyboard()}focus(){this.ace_editor.focus()}clear_parse_result(){this.for_each_session((t,n)=>{this.remove_markers_of_type(t,"error-code"),n.clearAnnotations()})}supress_change_selection(t){try{this.is_change_selection_supressed=!0,t()}finally{this.is_change_selection_supressed=!1}}ensure_session(t,n){let r=this.sessions[t];return r==null&&(r=globalThis.ace.createEditSession(n),this.sessions[t]=r,r.setUseWorker(!1),r.setOptions({mode:"ace/mode/typescript",tabSize:2,useSoftTabs:!0})),r}get_session(t){return this.sessions[t]}switch_session(t){this.supress_change_selection(()=>{this.ace_editor.setSession(this.get_session(t))})}has_value_explorer(){return this.value_explorer!=null}unembed_value_explorer(){if(!this.has_value_explorer())return null;let t=this.ace_editor.getSession(),n=this.value_explorer.el.getBoundingClientRect().bottom;if(t.widgetManager.removeLineWidget(this.value_explorer),this.value_explorer.is_dom_el){let r=t.selection.getCursor().row-this.value_explorer.row;if(r>0){let i=this.ace_editor.renderer.lineHeight,o=n-this.editor_container.getBoundingClientRect().bottom;o>0&&t.setScrollTop(t.getScrollTop()-o-i*r)}}this.value_explorer=null}update_value_explorer_margin(){if(this.value_explorer!=null){let t=this.ace_editor.getSession(),n=0;for(let r=this.value_explorer.row;r<=this.ace_editor.renderer.getLastVisibleRow();r++)n=Math.max(n,t.getLine(r).length);this.value_explorer.content.style.marginLeft=n+1+"ch"}}embed_value_explorer(t,{index:n,length:r,result:{ok:i,value:o,error:l,is_calltree_node_explorer:a}}){this.unembed_value_explorer();let d=this.ace_editor.getSession(),c,_=u("div",{class:"embed_value_explorer_container"},u("div",{class:"embed_value_explorer_wrapper"},c=u("div",{class:"embed_value_explorer_content",tabindex:0}))),h,f=()=>{h!=null&&d.setScrollTop(h),this.value_explorer.return_to==null?this.focus():this.value_explorer.return_to.focus()},p=()=>{x("step_into")};_.addEventListener("keydown",y=>{y.key=="Escape"&&f()});let m=t.selection_state?.node;(m?.kind==s.SyntaxKind.CallExpression||m?.kind==s.SyntaxKind.NewExpression)&&c.append(u("a",{href:"javascript: void(0)",class:"embed_value_explorer_control",click:p},"Step into call (Enter)"));let g;if(i)if(o?.dom_node!=null)if(g=!0,o.is_svg){let y=document.createElementNS("http://www.w3.org/2000/svg","svg");y.appendChild(o.dom_node),c.appendChild(y)}else c.appendChild(o.dom_node);else{g=!1;let y=new Fe({container:c,event_target:_,on_escape:f,on_enter:p,scroll_to_element:w=>{h==null&&(h=d.getScrollTop());let v=w.getBoundingClientRect().bottom-this.editor_container.getBoundingClientRect().bottom;v>0&&d.setScrollTop(d.getScrollTop()+v);let K=this.editor_container.getBoundingClientRect().top-w.getBoundingClientRect().top;K>0&&d.setScrollTop(d.getScrollTop()-K)}});a?y.render(t,{object_entries:Object.entries(o)},{is_expanded:!0,children:{"*arguments*":{is_expanded:!0}}}):y.render(t,o,{is_expanded:!0})}else g=!1,c.appendChild(u("span","eval_error",l==null?""+l:l.toString()));let k=this.value_explorer={selected_node:m,row:g?d.doc.indexToPosition(n+r).row:d.doc.indexToPosition(n).row,fixedWidth:!0,el:_,content:c,is_dom_el:g};if(!d.widgetManager){let y=zt("ace/line_widgets").LineWidgets;d.widgetManager=new y(d),d.widgetManager.attach(this.ace_editor)}if(g)_.classList.add("is_dom_el"),d.widgetManager.addLineWidget(k);else{_.classList.add("is_not_dom_el");let y=this.ace_editor.renderer.lineHeight;c.style.transform=`translate(0px, -${y}px)`,_.style.display="none",d.widgetManager.addLineWidget(k),$r(this.ace_editor,()=>{this.update_value_explorer_margin(),_.style.display=""})}}focus_value_explorer(t){this.value_explorer!=null&&(this.value_explorer.return_to=t,this.value_explorer.content.focus({preventScroll:!0}))}set_keyboard_handler(t){t!=null&&(localStorage.keyboard=t),this.ace_editor.setKeyboardHandler(t=="vim"?"ace/keyboard/vim":null)}init_keyboard(){this.set_keyboard_handler(localStorage.keyboard),this.ace_editor.keyBinding.addKeyboardHandler((n,r,i,o,l)=>{if(i=="return"){let a=this.value_explorer?.selected_node;if(a?.kind==s.SyntaxKind.CallExpression||a?.kind==s.SyntaxKind.NewExpression)return x("step_into"),{command:"null"}}});let t=zt("ace/keyboard/vim").CodeMirror.Vim;this.ace_editor.commands.removeCommand("openCommandPallete"),this.ace_editor.commands.removeCommand("toggleFoldWidget"),this.ace_editor.commands.removeCommand("goToNextError"),this.ace_editor.commands.bindKey("F5","goto_definition"),t._mapCommand({keys:"gd",type:"action",action:"aceCommand",actionArgs:{name:"goto_definition"}}),this.ace_editor.commands.addCommand({name:"goto_definition",exec:n=>{this.goto_definition()}}),this.ace_editor.commands.bindKey("F1","focus_value_explorer"),this.ace_editor.commands.addCommand({name:"focus_value_explorer",exec:n=>{this.focus_value_explorer()}}),this.ace_editor.commands.bindKey("F11","step_into"),this.ace_editor.commands.addCommand({name:"step_into",exec:n=>{x("step_into")}}),this.ace_editor.commands.bindKey("Shift-F11","step_out"),this.ace_editor.commands.addCommand({name:"step_out",exec:n=>{x("calltree.arrow_left")}}),this.ace_editor.commands.addCommand({name:"expand_selection",exec:()=>{x("eval_selection",this.get_cursor_position(),!0)}}),this.ace_editor.commands.addCommand({name:"collapse_selection",exec:()=>{x("eval_selection",this.get_cursor_position(),!1)}}),this.ace_editor.commands.bindKey("ctrl-j","expand_selection"),this.ace_editor.commands.bindKey("ctrl-down","expand_selection"),this.ace_editor.commands.bindKey("ctrl-k","collapse_selection"),this.ace_editor.commands.bindKey("ctrl-up","collapse_selection"),this.ace_editor.commands.addCommand({name:"edit",exec:(n,r)=>{let i=r.args==null?"":r.args[0];x("change_current_module",i)}}),t.defineEx("edit","e",function(n,r){n.ace.execCommand("edit",r)}),this.ace_editor.commands.addCommand({name:"buffer",exec:(n,r)=>{let i=r.args==null?"":r.args[0],o=i==""?"":Object.keys(C().files).find(l=>l.includes(i));o!=null&&x("change_current_module",o)}}),t.defineEx("buffer","b",function(n,r){n.ace.execCommand("buffer",r)}),t.map("jj","","insert")}add_marker(t,n,r,i){let o=this.get_session(t),l=o.doc.indexToPosition(r),a=o.doc.indexToPosition(i),d=o.addMarker(new globalThis.ace.Range(l.row,l.column,a.row,a.column),n);this.markers[t]==null&&(this.markers[t]=[]),this.markers[t].push({className:n,from:r,to:i,markerId:d})}remove_markers_of_type(t,n){this.markers[t]==null&&(this.markers[t]=[]);let r=this.markers[t].filter(o=>o.className==n),i=this.get_session(t);for(let o of r)i.removeMarker(o.markerId);this.markers[t]=this.markers[t].filter(o=>o.className!=n)}get_cursor_position(t){let n=t==null?this.ace_editor.getSession():this.get_session(t);if(n==null)throw new Error("illegal state");return n.doc.positionToIndex(n.selection.getCursor())}set_cursor_position(t){if(t==null)throw new Error("illegal state");this.supress_change_selection(()=>{let n=this.ace_editor.session.doc.indexToPosition(t);this.ace_editor.moveCursorToPosition(n),this.ace_editor.clearSelection();let r=this.ace_editor.renderer.getFirstVisibleRow(),i=this.ace_editor.renderer.getLastVisibleRow();(n.rowi)&&this.ace_editor.scrollToLine(n.row)})}goto_definition(){let t=this.get_cursor_position();x("goto_definition",t)}for_each_session(t){for(let n in this.sessions)t(n,this.sessions[n])}make_resizable(){let t=()=>{this.editor_container.style.height=localStorage.editor_height+"vh"},n=new Date().getTime();window.addEventListener("resize",()=>{n=new Date().getTime()}),localStorage.editor_height!=null&&t();let r=!0;new ResizeObserver(i=>{if(r){r=!1;return}if(new Date().getTime()-n<100)return;this.ace_editor.resize();let o=this.editor_container.offsetHeight/window.innerHeight*100;localStorage.editor_height=o,setTimeout(t,0)}).observe(this.editor_container)}};var Co=new Function("arr","pred",` for(let i = arr.length - 1; i >= 0; i--) { if(pred(arr[i])) { return arr[i] } } `);var qt=(e,t)=>Object.fromEntries(Object.entries(e).map(([n,r])=>[n,t(n,r)]));var Xt=new Function("fn","acc","arr",` let idx = 0; const len = arr.length; const result = []; let tuple = [acc]; while (idx < len) { tuple = fn(tuple[0], arr[idx], idx); result[idx] = tuple[1]; idx += 1; } return [tuple[0], result]; `),Yt=(e,t)=>e.reduce((n,r,i)=>n??t(r,i),null);var Gt=e=>[...new Set(e)];var Qt=`function fib(n) { if(n == 0 || n == 1) { return n } else { return fib(n - 1) + fib(n - 2) } } fib(6) `,Zt=(e,t)=>{localStorage["examples_"+e]=t},Fr=e=>localStorage["examples_"+e],ge=[{path:"github_api",entrypoint:"github_api/index.js"},{path:"fibonacci",entrypoint:"fibonacci/index.js"},{path:"todos-preact",entrypoint:"todos-preact/index.js",with_app_window:!0},{path:"ethers",entrypoint:"ethers/block_by_timestamp.js"},{path:"plot",entrypoint:"plot/index.js"},{path:"fractal_tree",entrypoint:"fractal_tree/fractal_tree.js",with_app_window:!0},{path:"animated_fractal_tree",entrypoint:"animated_fractal_tree/animated_fractal_tree.js",with_app_window:!0},{path:"canvas_animation_bubbles",entrypoint:"canvas_animation_bubbles/bubbles.js",with_app_window:!0}].map(e=>({...e,entrypoint:e.entrypoint??e.path})),Dr=ge.map(e=>(e.files??[]).concat([e.entrypoint])).flat().map(e=>e.split("/")),en=e=>{let t=Dr.filter(i=>e.every((o,l)=>o==i[l])),n=t.filter(i=>i.length==e.length+1),r=[...new Set(t.filter(i=>i.length!=e.length+1).map(i=>i[e.length]))];return Promise.all(n.map(async i=>{let o=i[e.length],l=i.slice(0,e.length+1).join("/");return{name:o,path:l,kind:"file",contents:Fr(l)??await fetch(globalThis.location.origin+"/docs/examples/"+l).then(a=>a.text())}}).concat(r.map(async i=>{let o=[...e,i];return{name:i,path:o.join("/"),kind:"directory",children:await en(o)}})))},dt=en([]).then(e=>({kind:"directory",name:"examples",path:null,children:e}));var Lr=e=>e.endsWith(".htm")||e.endsWith(".html"),Ar=e=>e==""||e.endsWith(".js")||e.endsWith(".ts")||e.endsWith(".mjs")||e.endsWith(".jsx")||e.endsWith(".tsx"),Le=class{constructor(t){this.ui=t,this.el=u("dialog","panel files_container"),this.render(C()),this.el.addEventListener("click",n=>{let r=this.el.getBoundingClientRect();r.top<=n.clientY&&n.clientY<=r.bottom&&r.left<=n.clientX&&n.clientX<=r.right||this.el.close()})}change_entrypoint(t,n){x("change_entrypoint",t,n),this.ui.editor.focus()}change_html_file(t){let n=t.target.value;x("change_html_file",n)}render(t){this.file_to_el=new Map;let n=t.has_file_system_access?u("div","file_actions",u("a",{class:"file_action",href:"javascript: void(0)",click:this.create_file.bind(this,!1)},"New file"),u("a",{class:"file_action",href:"javascript: void(0)",click:this.create_file.bind(this,!0)},"New dir"),u("a",{class:"file_action",href:"javascript: void(0)",click:nn},"Revoke access"),u("a",{href:"https://github.com/leporello-js/leporello-js#selecting-entrypoint-module",target:"__blank",class:"select_entrypoint_title",title:"Select entrypoint"},"Entry point")):u("div","file_actions",u("div","file_action allow_file_access",u("a",{href:"javascript: void(0)",click:tn},"Allow access to local project folder"),u("span","subtitle","Your files stay on your device - nothing is sent to a server"))),r=[this.render_file({name:"*scratch*",path:""},t),this.render_file(t.project_dir,t)],i=this.el.querySelector(".files");i==null?(this.el.innerHTML="",this.el.appendChild(n),this.el.appendChild(u("div","files",r))):(this.el.replaceChild(n,this.el.children[0]),i.replaceChildren(...r))}render_current_module(t){this.current_file=t,this.active_el.querySelector(".file_title").classList.remove("active"),this.active_el=this.file_to_el.get(t),this.active_el.querySelector(".file_title").classList.add("active")}render_select_entrypoint(t,n){return!n.has_file_system_access||t.kind=="directory"?null:Ar(t.path)?u("span","select_entrypoint",u("input",{type:"radio",name:"js_entrypoint",value:t.path,checked:n.entrypoint==t.path,change:r=>this.change_entrypoint(r.target.value),click:r=>r.stopPropagation()})):Lr(t.path)?u("span","select_entrypoint",u("input",{type:"radio",name:"html_file",value:t.path,checked:n.html_file==t.path,change:r=>this.change_html_file(r),click:r=>r.stopPropagation()})):null}render_file(t,n){let r=u("div","file",u("div",{class:"file_title"+(t.path==n.current_module?" active":""),click:i=>this.on_click(i,t)},u("span","icon",t.kind=="directory"?"\u{1F4C1}":"\xA0"),t.name,this.render_select_entrypoint(t,n)),t.children==null?null:t.children.map(i=>this.render_file(i,n)));return this.file_to_el.set(t.path,r),t.path==n.current_module&&(this.active_el=r,this.current_file=t.path),r}async create_file(t){let n=prompt(`Enter ${t?"directory":"file"} name`);if(n==null)return;let r=C().project_dir,i,o;if(this.current_file=="")i=r;else{let a=(d,c)=>d.path==this.current_file?[d,c]:d.children==null?null:Yt(d.children,_=>a(_,d));if([o,i]=a(r),o.kind=="directory")i=o;else if(i==null)throw new Error("illegal state")}let l=i==r?n:i.path+"/"+n;await Bt(l,t),he(!1).then(a=>{t?x("load_dir",a,!0):x("create_file",a,l)})}on_click(t,n){if(t.stopPropagation(),C().has_file_system_access)n.kind!="directory"&&x("change_current_module",n.path);else if(n.path!=null)if(n.path=="")this.change_entrypoint("");else{let r=l=>l.path==n.path||l.children!=null&&l.children.find(r),i=C().project_dir.children.find(l=>r(l)!=null),o=ge.find(l=>l.path==i.path);this.change_entrypoint(o.entrypoint,n.kind=="directory"?void 0:n.path),o.with_app_window&&!localStorage.onboarding_open_app_window&&this.ui.toggle_open_app_window_tooltip(!0)}this.render_current_module(n.path)}};import{ts_libs_promise as Pr}from"./ts_libs.js";var B=new Set;for(let e in s.Diagnostics)(e.startsWith("Duplicate")||e.includes("super")||e.includes("Super")||e.includes("used_before")||e.includes("redeclare"))&&B.add(s.Diagnostics[e].code);B.add(1108);B.add(1308);B.add(1103);B.add(1163);B.add(1104);B.add(1105);B.add(2588);(function(){let t=s.factory.createIdentifier("test").__proto__,n=s.factory.createBlock([]).__proto__,r=s.factory.createToken(s.SyntaxKind.FalseKeyword).__proto__;for(let i of[t,n,r])Object.defineProperty(i,"index",{get:function(){return this.getStart()},configurable:!1,enumerable:!1}),Object.defineProperty(i,"length",{get:function(){return this.getWidth()},configurable:!1,enumerable:!1}),Object.defineProperty(i,"kind_name",{get:function(){return s.SyntaxKind[this.kind]},configurable:!1,enumerable:!1})})();var ye=s.ScriptTarget.Latest,jr=s.createSourceFile("leporello.d.ts",` declare var leporello: { storage: Map } `,ye),Ae={target:ye,module:s.ModuleKind.ES2022,lib:["lib.esnext.d.ts","lib.dom.d.ts","leporello.d.ts"],noEmitOnError:!0,verbatimModuleSyntax:!0,jsx:s.JsxEmit.React,noResolve:!0,skipLibCheck:!0,allowJs:!0,checkJs:!0,noEmit:!0},Pe=e=>s.createSourceFile("temp.ts",e,ye,!1,s.ScriptKind.JSX),_t;Pr.then(e=>{_t=Object.fromEntries(Object.entries(e).map(([t,n])=>{let r=s.createSourceFile(t,n,ye,void 0,s.ScriptKind.TSX);return[t,r]}))});var rn=e=>e==""?".ts":e,je=e=>e==".ts"?"":e,ut=(e,t)=>{let n={resolveLibrary(i,o,l,a){return{path:a}},readFile(i){throw new Error("not implemented")},useCaseSensitiveFileNames(){return!1},getDefaultLibFileName(){return"lib.d.ts"},getCurrentDirectory(){return"currentDirectoryToken"},getCanonicalFileName(i){return i},resolveModuleNames(i){return i.map(o=>({resolvedFileName:o,extension:".js"}))},getSourceFile(i){if(i=="leporello.d.ts")return jr;if(_t[i]!=null)return _t[i];if(je(i)==e)return t;throw new Error("illegal state")}};return s.createProgram([e],Ae,n)};function Or(e){let t=[];function n(r){r.kind==s.SyntaxKind.ImportDeclaration&&(r.moduleSpecifier.text.startsWith(".")||r.moduleSpecifier.text.startsWith("/"))&&t.push({node:r,messageText:"Local imports are not supported yet. Please use a full URL starting with https:// or specify an npm package name"}),r.kind==s.SyntaxKind.VariableDeclarationList&&!(r.flags&(s.NodeFlags.Let|s.NodeFlags.Const))&&t.push({node:r,messageText:'"var" declarations are not supported. Use "let" declarations instead'}),(s.isFunctionDeclaration(r)||s.isFunctionExpression(r)||s.isMethodDeclaration(r))&&r.asteriskToken!==void 0&&t.push({node:r,messageText:"Generator functions are not implemented"}),(r.kind==s.SyntaxKind.CallExpression||r.kind==s.SyntaxKind.NewExpression)&&r.questionDotToken!=null&&t.push({node:r,messageText:"Optional chaining with function calls is not implemented"});let i=s.SyntaxKind[r.kind];r.kind==s.SyntaxKind.ForOfStatement&&r.awaitModifier!=null&&t.push({node:r,messageText:"for-await loops are not supported."}),(r.kind==s.SyntaxKind.TryStatement||r.kind==s.SyntaxKind.ClassDeclaration||r.kind==s.SyntaxKind.LabeledStatement||r.kind==s.SyntaxKind.ClassExpression||r.kind==s.SyntaxKind.SwitchStatement||r.kind==s.SyntaxKind.NamespaceImport||r.kind==s.SyntaxKind.MethodDeclaration||r.kind==s.SyntaxKind.GetAccessor||r.kind==s.SyntaxKind.SetAccessor||r.kind==s.SyntaxKind.TaggedTemplateExpression)&&t.push({node:r,messageText:`${i} is not implemented`});function o(l){return l.kind==s.SyntaxKind.PropertyAccessExpression||l.kind==s.SyntaxKind.ElementAccessExpression||l.kind==s.SyntaxKind.CallExpression}o(r)&&r.questionDotToken!=null&&r.parent!=null&&o(r.parent)&&r.parent.questionDotToken==null&&t.push({node:r,messageText:"Only the last element of access chain can be optional"}),s.forEachChild(r,n)}return n(e),t.map(({node:r,messageText:i})=>({file:e,start:r.getStart(),length:r.getWidth(),messageText:i,category:s.DiagnosticCategory.Error}))}var Nr=(e,t,n)=>{let r=s.createSourceFile(e,t,{languageVersion:ye,setExternalModuleIndicator:c=>{c.externalModuleIndicator=!0}},!0,n?s.ScriptKind.TSX:s.ScriptKind.JSX),i=ut(e,r),o;if(n)o=s.getPreEmitDiagnostics(i);else{let c=i.getSemanticDiagnostics().filter(_=>B.has(_.code));o=[...i.getSyntacticDiagnostics(),...c]}let l=s.sortAndDeduplicateDiagnostics([...o,...Or(r)]),a=l.length==0,d;if(n){let c=function(_,h){_.parent=h,s.forEachChild(_,f=>c(f,_))};d=s.transform(r,[s.transformTypeScript],Ae).transformed[0],c(d),delete d.original,s.forEachChildRecursively(d,_=>{delete _.original})}else d=r;return{ok:a,node:d,program:i,problems:l.map(c=>{let _=s.flattenDiagnosticMessageText(c.messageText,` `);if(c.length==null)throw new Error("illegal state");return{message:_,index:c.start,length:c.length,module:je(c.file.fileName)}})}},on=(e,t,n)=>{let r=t(e),i=e==""?n:e.endsWith(".ts"),o=Nr(e,r,i);return{ok:o.ok,program:o.program,sorted:[e],modules:o.ok?{[e]:o.node}:null,problems:o.problems}};var Oe=s.SyntaxKind,S=e=>s.isFunctionLike(e),pt=e=>(e.parent?.kind==s.SyntaxKind.ForOfStatement||e.parent?.kind==s.SyntaxKind.ForInStatement)&&e.parent.expression==e||e.parent?.kind==s.SyntaxKind.ForStatement&&e.parent.initializer==e,ze=e=>{if(pt(e))return s.forEachAncestor(e.parent.parent,t=>{if(S(t)||E(t)||t.kind==s.SyntaxKind.SourceFile)return t})},se=e=>e.kind==s.SyntaxKind.JsxElement||e.kind==s.SyntaxKind.JsxSelfClosingElement||e.kind==s.SyntaxKind.JsxFragment,E=e=>e.kind==s.SyntaxKind.ForStatement||e.kind==s.SyntaxKind.ForOfStatement||e.kind==s.SyntaxKind.ForInStatement||e.kind==s.SyntaxKind.DoStatement||e.kind==s.SyntaxKind.WhileStatement,Ie=e=>{if(e.kind!=s.SyntaxKind.ForStatement)return null;let t=e.initializer;return t.kind==s.SyntaxKind.VariableDeclarationList&&t.declarations[0].name.kind==s.SyntaxKind.Identifier?t.declarations[0].name:t.kind==s.SyntaxKind.BinaryExpression&&t.operatorToken.kind==s.SyntaxKind.EqualsToken&&t.left.kind==s.SyntaxKind.Identifier?t.left:null},Ne=class{constructor(t,n,r){this.index=t,this.length=n,this.original=r}},Q=e=>e instanceof Ne,L=e=>{if(Q(e))return[];if(S(e)){let n=e.getChildren(),r=n.find(a=>a.kind==s.SyntaxKind.OpenParenToken),i,o;return r!=null?(i=r.getStart(),o=n.find(a=>a.kind==s.SyntaxKind.CloseParenToken).getEnd()-i):(i=n[0].index,o=n[0].length),[new Ne(i,o,e.parameters),e.body]}if(se(e)){let n=[];return s.forEachChildRecursively(e,r=>{if(r.kind==s.SyntaxKind.JsxExpression||r.kind==s.SyntaxKind.JsxSpreadAttribute)return n.push(r),"skip"}),n}if(e.kind==s.SyntaxKind.ImportDeclaration)return[];let t=[];return s.forEachChild(e,n=>{(!s.isToken(n)||s.isLiteralExpression(n)||s.isIdentifier(n)||n.kind==s.SyntaxKind.NullKeyword||n.kind==s.SyntaxKind.ThisKeyword||n.kind==s.SyntaxKind.TrueKeyword||n.kind==s.SyntaxKind.FalseKeyword)&&t.push(n)}),t},xe=e=>!!s.forEachChildRecursively(e,t=>{if(t.kind==s.SyntaxKind.AwaitExpression)return!0;if(S(t))return"skip"}),sn=e=>e.modifiers?.some(t=>t.kind===s.SyntaxKind.AsyncKeyword)??!1,zr=e=>(s.isPrefixUnaryExpression(e)||s.isPostfixUnaryExpression(e))&&(e.operator===s.SyntaxKind.PlusPlusToken||e.operator===s.SyntaxKind.MinusMinusToken),ke=(e,t)=>t.kind==Oe.VariableDeclaration&&t.name==e||s.isAssignmentExpression(t)&&t.left==e||t.kind==Oe.BindingElement&&t.name==e||t.kind==s.SyntaxKind.ForOfStatement&&t.initializer==e||t.kind==s.SyntaxKind.ForInStatement&&t.initializer==e||t.kind==Oe.Parameter||e.kind==Oe.BindingElement||t!=null&&zr(t)&&t.operand==e,Ir=s.createPrinter(),ft=e=>{let t;e.kind==s.SyntaxKind.VariableDeclarationList||e.kind==s.SyntaxKind.VariableStatement?t=e:S(e)?t=s.factory.createVariableDeclarationList([s.factory.createVariableDeclaration(s.factory.createArrayBindingPattern(e.parameters),void 0,void 0,s.factory.createNull())]):t=s.factory.createVariableDeclarationList([s.factory.createVariableDeclaration(e,void 0,void 0,s.factory.createNull())]);let n=Ir.printNode(s.EmitHint.Unspecified,t),r=Pe(n),i="collect.ts",o=ut(i,r);return o.getTypeChecker(),[...o.getSourceFile(i).locals.keys()]};var ht=e=>Object.entries(e).map(([t,n])=>n.statements.filter(r=>r.kind==s.SyntaxKind.ImportDeclaration).map(r=>({node:r,module_name:t,url:r.moduleSpecifier.text}))).flat(),A=(e,t)=>Z(e,t)?s.forEachChild(e,r=>A(r,t))??e:null,Z=(e,t)=>e.index<=t&&e.index+e.length>t,ln=(e,t)=>t.index<=e.index&&t.index+t.length>=e.index+e.length,mt=(e,t)=>{let n=[];return s.forEachAncestor(e,r=>{if(r==t)return r;r!=e&&n.push(r)}),n},le=(e,t)=>[e,...mt(e,t)],P=(e,t)=>t(e)?e:e.children==null?null:e.children.reduce((n,r)=>n??P(r,t),null),gt=(e,t,n=null)=>{if(e==t)return n;if(e.children==null)return null;for(let r of e.children){let i=gt(r,t,e);if(i!=null)return i}return null},Me=(e,t)=>s.forEachChildRecursively(e,n=>{if(t(n))return n}),yt=(e,t)=>s.forEachChildRecursively(e,n=>{if(t.get(n)?.is_error_origin)return n;if(S(n))return"skip"});var Mr=e=>{let t=[];function n(r){if(S(r)){t.push(r);return}for(let i of L(r))n(i,r)}return n(e),t},an=(e,t)=>{let n=(c,_)=>{let h=c.kind==null?c.result:t.get(c),f=_.kind==null?_.result:t.get(_);return h==null?f==null:f!=null&&h.ok==f.ok&&!!h.is_error_origin==!!f.is_error_origin},r=c=>{let _=t.get(c);return{index:c.index,length:c.length,result:_==null||S(c)?null:_.ok?{ok:!0}:{ok:!1,is_error_origin:!!_.is_error_origin}}},i=c=>s.isBinaryExpression(c)&&(c.operatorToken.kind==s.SyntaxKind.AmpersandAmpersandToken||c.operatorToken.kind==s.SyntaxKind.BarBarToken||c.operatorToken.kind==s.SyntaxKind.QuestionQuestionToken)||c.kind==s.SyntaxKind.ConditionalExpression,o=(c,_)=>{let h=L(c).map(y=>l(y)).reduce((y,[w,...v])=>{if(y.length==0)return[w,...v];{let K=y[y.length-1];if(n(K,w))return[...y.slice(0,y.length-1),{index:K.index,length:w.index-K.index+w.length,result:w.result==null?null:{ok:w.result.ok}},...v];if(!i(c)&&K.result==null&&w.result?.ok){let re=K.index+K.length;return[...y,{...w,index:re,length:w.index-re+w.length},...v]}else return!i(c)&&K.result?.ok&&w.result==null?[...y.slice(0,y.length-1),{...K,length:w.index-K.index},w,...v]:[...y,w,...v]}},[]),f=t.get(c);if((f==null||f?.ok)&&h.reduce((y,w)=>y&&n(h[0],w),!0)){if(n(c,h[0]))return _&&S(c)?[{...r(c),result:{ok:t.get(c).ok}}]:[r(c)];{let y=r(c),w=h.at(-1).index+h.at(-1).length;return[{...y,length:h[0].index-y.index},...h,{...y,index:w,length:c.index+c.length-w}]}}if(h.length==0)throw new Error("illegal state");let p=h[0],m=n(p,c)&&t.get(c)?.ok?[{...p,index:c.index,length:p.length+p.index-c.index},...h.slice(1)]:h,g=m[m.length-1];return n(g,c)&&t.get(c)?.ok?[...m.slice(0,m.length-1),{...g,index:g.index,length:c.index+c.length-g.index}]:m},l=(c,_=!1)=>{if(S(c)&&!_)return[{...r(c),result:null}];if((c.kind==s.SyntaxKind.WhileStatement||c.kind==s.SyntaxKind.DoStatement)&&!_){let p;c.kind==s.SyntaxKind.WhileStatement?p=c.expression.index:p=c.statement.index;let m=t.get(c);return[{index:c.index,length:p-c.index,result:m==null?null:m.ok?{ok:!0}:{ok:!1,is_error_origin:!!m.is_error_origin}},{index:p,length:c.index+c.length-p,result:null}]}if((c.kind==s.SyntaxKind.ForOfStatement||c.kind==s.SyntaxKind.ForInStatement)&&!_){let p=t.get(c);return[{index:c.index,length:c.initializer.index-c.index,result:p==null?null:p.ok?{ok:!0}:{ok:!1,is_error_origin:!!p.is_error_origin}},{index:c.initializer.index,length:c.initializer.length,result:null},...l(c.expression),{index:c.statement.index,length:c.statement.length,result:null}]}if(c.kind==s.SyntaxKind.ForStatement&&!_){let p=t.get(c);return[{index:c.index,length:c.initializer.index-c.index,result:p==null?null:p.ok?{ok:!0}:{ok:!1,is_error_origin:!!p.is_error_origin}},...l(c.initializer),{index:c.condition.index,length:c.condition.length,result:null},{index:c.incrementor.index,length:c.incrementor.length,result:null}]}if(Q(c)||L(c).length==0)return[r(c)];if(t.get(c)?.is_error_origin){let p=r(c),m=Mr(c);return m.length==0?[p]:m.map((g,k)=>{let y;if(k==0)y=c.index;else{let w=m[k-1];y=w.index+w.length}return{index:y,length:g.index-y,result:p.result}}).concat([{index:m.at(-1).index+m.at(-1).length,length:c.index+c.length-(m.at(-1).index+m.at(-1).length),result:p.result}])}let h=o(c,_),f=t.get(c);return f!=null&&!f.ok?h.map(p=>p.result==null?{...p,result:{ok:!1,is_error_origin:!1}}:p):h},a=l(e,!0);a=a.filter(c=>c.result!=null&&(c.result.ok||c.result.is_error_origin));let{ok:d}=a.reduce(({ok:c,prev:_},h)=>c?_==null?{ok:c,prev:h}:_.index+_.length>h.index?{ok:!1}:{ok:!0,prev:h}:{ok:c},{ok:!0,prev:null});if(!d)throw new Error("illegal state");return a},cn=(e,t)=>Object.values(e.colored_frames?.[t]??{}).map(n=>e.frame_coloring.get(n)).flat();var O=class{constructor(t){this.str=t}},xt=class{constructor(){this.map=new Map}set(t,n,r){this.map.has(t)||this.map.set(t,new Map),this.map.get(t).set(n,r)}get(t,n){return this.map.get(t)?.get(n)}},dn=new xt,_n=(e,...t)=>{let n=t.filter(l=>!(l instanceof O)).map(l=>{switch(typeof l){case"string":return s.factory.createStringLiteral(l);case"number":return s.factory.createNumericLiteral(l);case"undefined":return s.factory.createIdentifier("undefined");case"boolean":return(l?s.factory.createTrue:s.factory.createFalse)();default:return l}}),r=t.filter(l=>l instanceof O),i=[e,r.map(l=>l.str).join()],o=dn.get(...i);if(o==null){let l="";for(let a=0;a{let _=s.visitNode(c,d);if(a!=n.length)throw console.error({replacement_idx:a,"replacements.length":n.length,replacements:t}),new Error("illegal state");return _}}]).transformed[0]},T=(...e)=>_n(...e).statements,I=(...e)=>_n(...e).statements[0].expression;var un=e=>e.frames.get(e.active_calltree_node.id),Re=(e,t)=>({id:"calltree",children:[e,{id:"deferred_calls",children:t}]}),M=e=>e.calltree.children[1].children,D=e=>e.calltree.children[0];var Rr=["pointerId","buttons","altKey","ctrlKey","shiftKey","metaKey","pageX","pageY","deltaX","deltaY","key","which","timeStamp"],Br=new Set(["blur","focus","click","dblclick","wheel","input","change","contextmenu","pointerdown","pointerup","pointermove","pointerover","pointerenter","pointerleave","pointercancel","mousedown","mouseup","mousemove","mouseover","mouseenter","mouseleave","mousecancel","keydown","keyup","keypress","load","DOMContentLoaded"]),Vr=["bubbles","composed","cancelable"],pn=e=>{let t=e.window,n=t.EventTarget.prototype.addEventListener,r=new Set;t.EventTarget.prototype.addEventListener=function(o,...l){return!r.has(o)&&Br.has(o)&&n.call(t.window,o,a=>{if(!e.io_trace_is_recording||["change","input"].includes(o)&&["checkbox","radio"].includes(a.target.type))return;let d=a.constructor.name,c=Object.fromEntries(Rr.map(f=>[f,a[f]])),_=Object.fromEntries(Vr.map(f=>[f,a[f]])),h=Ur(t.window,a.target);e.io_trace.push({type:"event",constructorName:d,event_type:o,props:c,dispatch_props:_,selectors:h,value:a.target.value})},!0),r.add(o),n.call(this,o,...l)}},fn=(e,t)=>{let n=e.window[t.constructorName],r=Object.defineProperties(new n(t.event_type,t.dispatch_props),Object.fromEntries(Object.entries(t.props).map(([o,l])=>[o,{value:l}]))),i=Jr(e.window.window,t.selectors);["input","change"].includes(t.event_type)&&(i.value=t.value),i.dispatchEvent(r)},kt=e=>{e.window.document.dispatchEvent(new Event("DOMContentLoaded")),e.window.window.dispatchEvent(new Event("DOMContentLoaded")),e.window.window.dispatchEvent(new Event("load"))};function Wr(e){let t=[];for(;e;){t.unshift(e.tagName.toLowerCase());let n=e.parentNode;if(n){let r=[...n.children];if(r.length>1){let i=r.indexOf(e)+1;i&&(t[0]+=`:nth-child(${i})`)}}if(e.hasAttribute("part")){let r=`[part=${e.getAttribute("part")}]`;t[0]+=r}if(n instanceof Element)e=n;else break}return t.join(" > ")}function Ur(e,t){if(t==e)return["window"];let n=[],r;for(;(r=t.getRootNode())&&(n.unshift(Wr(t)),!(r===e.document||r===t));)t=r.host;return n}function Jr(e,t){let n=e.document,r,i;for(let o of t){if(o==="window")return e;if(i=n?.querySelector(o),!i)return r;if(r=i,n=i?.shadowRoot,!n)break}return r}var ae=(e,t,n=!1,r=!1)=>{let i=e;for(let d=0;d{throw e.io_trace_is_replay_aborted=!0,e.io_trace_resolve_replay_finished(),new e.window.Error("io replay aborted")},yn=e=>{if(e.io_trace_is_replay_aborted)throw new e.window.Error("io replay was aborted")},hn=(e,t)=>{for(let n=e.io_trace_index;n{e.io_trace_resolver_is_set||(e.io_trace_resolver_is_set=!0,setTimeout(()=>{if(e.io_trace_is_replay_aborted)return;if(e.io_trace_resolver_is_set=!1,e.io_trace_index>=e.io_trace.length)throw new Error("illegal state");let t=e.io_trace[e.io_trace_index];if(e.io_trace_index++,t.type=="call")hn(e,"resolution").index{let o=function(...l){let a=new.target!=null,d=e.__cxt;if(yn(d),d.io_trace_is_recording){let c,_,h;try{let f=d.io_trace.length;if(n=="setTimeout"){l=l.slice();let p=l[0];typeof p=="function"&&(l[0]=Object.defineProperty(function(){d.io_trace_is_replay_aborted||(d.io_trace.push({type:"resolution",index:f}),p())},"name",{value:p.name}))}return _=a?new t(...l):t.apply(this,l),c=!0,_?.[Symbol.toStringTag]=="Promise"?(_=Promise.prototype.then.call(_,p=>{if(!d.io_trace_is_replay_aborted)return d.io_trace.push({type:"resolution",index:f}),_.status={ok:!0,value:p},i?p:e.structuredClone(p)},p=>{if(!d.io_trace_is_replay_aborted)throw d.io_trace.push({type:"resolution",index:f}),_.status={ok:!1,error:p},e.structuredClone(p)}),_):i?_:e.structuredClone(_)}catch(f){throw h=f,c=!1,e.structuredClone(f)}finally{d.io_trace.push({type:"call",name:n,ok:c,value:_,error:h,args:l,has_new_target:a,use_context:r,skip_clone:i,context:r?this:void 0})}}else{let c=d.io_trace[d.io_trace_index];if(d.io_trace_index++,c==null||c.type!="call"||c.has_new_target!=a||c.use_context&&c.context!=this||c.name!=n||n=="setTimeout"&&l[1]!=c.args[1]||n!="setTimeout"&&JSON.stringify(c.args)!=JSON.stringify(l))gn(d);else if(c.ok){if(c.value?.[Symbol.toStringTag]=="Promise")return new d.window.Promise((_,h)=>{d.io_trace_resolvers.set(d.io_trace_index-1,{resolve:_,reject:h})});if(n=="setTimeout"){let _=l[0];return d.io_trace_resolvers.set(d.io_trace_index-1,{resolve:_}),c.value}else return i?c.value:e.structuredClone(c.value)}else throw e.structuredClone(c.error)}};return Object.defineProperty(o,"name",{value:t.name}),o},Hr=e=>{let t=e.Date,n=t.prototype,r=xn(e,t,"Date",!1);e.Date=function(...o){return o.length==0?new.target!=null?new r(...o):r(...o):new.target!=null?new t(...o):t(...o)},e.Date.prototype=n,e.Date.parse=Date.parse,e.Date.now=Date.now,e.Date.UTC=Date.UTC,ae(e,["Date","now"])},mn=(e,t)=>{let n=e[t];e[t]=function(...r){let i=new.target!=null,o=e.__cxt;return yn(o),o.io_trace_is_recording||gn(o),i?new n(...r):n.apply(this,r)},Object.defineProperty(e[t],"name",{value:t})},kn=e=>{if(ae(e,["Math","random"]),ae(e,["setTimeout"],void 0,!0),ae(e,["clearTimeout"]),mn(e,"setInterval"),mn(e,"clearInterval"),Hr(e),ae(e,["fetch"],void 0,!0),e.Response!=null){let t=["arrayBuffer","blob","formData","json","text"];for(let n of t)ae(e,["Response","prototype",n],!0)}};var wn=globalThis?.CanvasRenderingContext2D?.prototype?.reset;function qr(e){wn!=null?wn.call(e):e.canvas.width=e.canvas.width+0}function Xr(e){for(let t of e.contexts)qr(t)}function vn(e){let t=e?.CanvasRenderingContext2D?.prototype;if(t==null)return;let n=Object.getOwnPropertyDescriptors(t);Object.entries(n).forEach(([r,i])=>{if(i.value!=null){if(typeof i.value!="function")return;let o=i.value;t[r]={[r](){let l=e.__cxt,a=++l.version_counter;try{return o.apply(this,arguments)}finally{l.canvas_ops.contexts.add(this),l.canvas_ops.ops.push({canvas_context:this,method:o,version_number:a,args:arguments})}}}[r]}if(i.set!=null){let o=i.set;Object.defineProperty(t,r,{set(l){let a=e.__cxt,d=++a.version_counter;try{o.call(this,l)}finally{a.canvas_ops.contexts.add(this),a.canvas_ops.ops.push({canvas_context:this,version_number:d,set_op:o,prop_value:l})}}})}})}function Sn(e){if(e.method!=null)e.method.apply(e.canvas_context,e.args);else if(e.set_op!=null)e.set_op.call(e.canvas_context,e.prop_value);else throw new Error("illegal op")}function Be(e,t){if(e.calltree==null)return;let n=e.rt_cxt;if(n.canvas_ops.ops!=null)if(Xr(n.canvas_ops),t)for(let r of n.canvas_ops.ops)Sn(r);else{let r=e.current_calltree_node.last_version_number;for(let i of n.canvas_ops.ops){if(i.version_number>r)break;Sn(i)}}}var ce;try{(function e(){return e()})()}catch(e){ce=e}var Yr=500,de=e=>e?.[Symbol.toStringTag]=="Promise",Gr=e=>(...t)=>{let n=e(...t),r=i=>i.done?i.value:de(i.value)?Promise.prototype.then.call(i.value,o=>r(n.next(o)),o=>r(n.throw(o))):r(n.next(i.value));return r(n.next())},F=(e,t)=>{let n=new Map;return r(t);function r(o){if(o==null||typeof o!="object")return o;let l=n.get(o);if(l!=null)return l;let a={};return n.set(o,a),l=i(o),Object.assign(a,l),l}function i(o){if(Array.isArray(o))return{clazz:"Array",array_entries:o.map(r)};if(e.Element!=null&&o instanceof e.Element&&!o.isConnected)return{clazz:o.constructor?.name,is_svg:e.SVGElement!=null&&o instanceof e.SVGElement,object_entries:[],dom_node:o.cloneNode(!0)};if(o instanceof e.Map)return{clazz:"Map",object_entries:[...o.entries()].map(([l,a])=>[r(l),r(a)])};if(o instanceof e.Set)return{clazz:"Set",array_entries:[...o.values()].map(r)};if(de(o)){let l;return o.status!=null&&(l={ok:o.status.ok,value:r(o.status.value),error:r(o.status.error)}),{clazz:"Promise",status:l}}return o instanceof e.Date?{clazz:"Date",string:o.toJSON()}:o instanceof e.Error?{clazz:o.constructor?.name,string:o.toString()}:o==e?{clazz:"Window",object_entries:[]}:{clazz:o.constructor?.name,object_entries:Object.entries(o).map(([l,a])=>[l,r(a)])}}},Qr=()=>{let e;return[new Promise(n=>e=n),e]},bn=Gr(function*(e,t,n){let[r,i]=Qr(),o=n.length==0;if(t=o?{...t,io_trace_is_recording:o,logs:[]}:{...t,io_trace_is_recording:o,logs:[],io_trace_is_replay_aborted:!1,io_trace_resolver_is_set:!1,io_trace_resolvers:new Map,io_trace_index:0,io_trace_resolve_replay_finished:i},t.window.__cxt!=null)throw new Error("illegal state");t.window.__cxt=t,oi(t.window),ei(t),kn(t.window),Zr(t),pn(t),vn(t.window);let l=!o&&!n.every(h=>h.type=="call");l&&wt(t);let a=!1,d;for(let h=0;hkt(t),0)),l&&(yield Promise.race([r,m]),t.io_trace_is_replay_aborted))break;yield m,d.ok=!0}catch(m){d.ok=!1,d.error=m}if(d.children=t.children,t.children=null,d.last_version_number=t.version_counter,!d.ok)break}if(t.children!=null&&!t.io_trace_is_replay_aborted)throw new Error("illegal state");let c=t.children=[];o&&!a&&kt(t),l&&(yield r),t.io_trace_is_recording=!0,t.is_recording_deferred_calls=!0;let _=t.logs;return t.logs=[],t.children=null,{modules:t.modules,calltree:d,deferred_calls:c.length==0?null:c,logs:_,rt_cxt:t}}),Zr=e=>{e.window.leporello={storage:e.storage}},ei=e=>{let t=e.window.Promise.prototype.then;e.window.Promise.prototype.then=function(r,i){e.children==null&&(e.children=[]);let o=e.children,l=(a,d)=>typeof a!="function"?a:c=>{this.status==null&&(this.status=d?{ok:d,value:c}:{ok:d,error:c});let _=e.children;e.children=o;try{return a(c)}finally{e.children=_}};return t.call(this,l(r,!0),l(i,!1))}},U=e=>{for(let t=0;t{e.children==null&&(e.children=[]);let r={children_copy:e.children,promise:t};return de(t)?r.promise=t.then(i=>{r.status={ok:!0,value:i}},i=>{r.status={ok:!1,error:i}}):r.status={ok:!0,value:t},r},ni=(e,t)=>{if(e.children=t.children_copy,t.status.ok)return t.status.value;throw t.status.error},ri=(e,t,n,r,i)=>{function o(...l){if(e.stack.length>Yr)throw new ce.constructor(ce.message);let a=e.children;e.children=null,e.stack.push(!1);let d=++e.call_counter,c=e.version_counter,_,h=e.breakpoint.current_calltree_node_id==d;h&&(_={args:F(e.window,l),context_before:F(e.window,this)},U(e));let f,p,m,g=e.is_toplevel_call;e.is_toplevel_call=!1;try{return new.target==null?p=t.apply(this,l):p=new t(...l),f=!0,de(p)&&U(e),h&&(_.ok=f,_.context_after=F(e.window,this),_.value=F(e.window,p)),p}catch(k){throw f=!1,m=k,h&&(_.context_after=F(e.window,this),_.error=F(e.window,m)),U(e),m}finally{let k={id:d,version_number:c,last_version_number:e.version_counter,ok:f,context:this,value:p,error:m,fn:o,args:r==null?l:l.slice(0,r),snapshot:_};if(e.stack.pop()?k.children=e.children:k.has_more_children=e.children!=null&&e.children.length!=0,e.children=a,e.children==null&&(e.children=[]),e.children.push(k),e.is_toplevel_call=g,e.is_recording_deferred_calls&&e.is_toplevel_call){if(e.children.length!=1)throw new Error("illegal state");let w=e.children[0];e.children=null;let v=e.logs;e.logs=[],e.on_deferred_call(w,e.execution_id,v)}}}return Object.defineProperty(o,"name",{value:n}),o.__location=i,o.is_hosted=!0,t.prototype=o.prototype,o},ii=["log","error","info","debug","warn","trace"],oi=e=>{let t=e.console,n=e.__cxt;for(let r of ii){let i=t[r];t[r]={[r](...o){let l=++n.call_counter,a=n.breakpoint.current_calltree_node_id==l,d={id:l,version_number:n.version_counter,last_version_number:n.version_counter,ok:!0,value:void 0,fn:i,args:o,context:t,is_new:!1,snapshot:a?{args:F(n.window,o)}:null};n.children==null&&(n.children=[]),n.children.push(d),n.logs.push(n.call_counter),U(n)}}[r],t[r].is_hosted=!0}},si=(e,t,n,r,i,o=!1,l)=>{if(typeof t!="function")throw new e.window.TypeError(i+" is not a "+(o?"constructor":"function"));if(t.is_hosted)try{return o?new t(...r):t.apply(n,r)}finally{e.children!=null&&(e.children.at(-1).callsite_location=l)}let a=e.children;e.children=null,e.stack.push(!1);let d=++e.call_counter,c=e.version_counter,_,h=e.breakpoint.current_calltree_node_id==d;h&&(_={args:F(e.window,r),context_before:F(e.window,n)},U(e));let f,p,m;try{return o?p=new t(...r):p=t.apply(n,r),f=!0,de(p)&&U(e),h&&(_.ok=f,_.context_after=F(e.window,n),_.value=F(e.window,p)),p}catch(g){throw f=!1,m=g,h&&(_.context_after=F(e.window,n),_.error=F(e.window,m)),U(e),m}finally{let g={id:d,version_number:c,last_version_number:e.version_counter,ok:f,value:p,error:m,fn:t,args:r,context:n,is_new:o,snapshot:_,callsite_location:l};e.stack.pop()?g.children=e.children:(g.has_more_children=e.children!=null&&e.children.length!=0,g.children_count=e.children?.length??0),e.children=a,e.children==null&&(e.children=[]),e.children.push(g)}},li=(e,t,n)=>{if(!e.is_entrypoint)return;let r=e.snapshots,i=r.get(t);if(!(i==null||n==e.breakpoint.selected_call_id))return null;i==null&&(i=new Map,r.set(t,i));let l=i.get(n);return l==null?(l={call_id:n,ok:!1},U(e),i.set(n,l),l):null},ai=(e,t,n)=>(t!=null&&(t.ok=!0,t.value=F(e.window,n)),n),ci=(e,t,n,r)=>{if(!e.is_entrypoint)return;let o=e.snapshots.get(t);if(o==null)return r;let l=o.get(n);return l!=null&&!l.ok&&(l.ok=!0,l.value=F(e.window,r)),r},di=Symbol("loop_break"),_i=Symbol("loop_continue"),ui={trace:ri,trace_call:si,await_start:ti,await_finish:ni,before_take_node_snapshot:li,take_node_snapshot_fast:ai,take_node_snapshot:ci,Symbol_loop_break:di,Symbol_loop_continue:_i};var We=e=>e.should_collect_footprints&&e.breakpoint.function_node==e.current_function,Kt=e=>(S(e)?sn(e):xe(e))?T`let __await_state;`:[],Ue=(e,t)=>[...T`const __call_id = __cxt.call_counter;`,...Kt(e),...We(t)?T` const __footprints = new Map(); __cxt.footprints.set(__call_id, __footprints); `:[]],pi=e=>{let t=e.parent;return t!=null&&(s.isPropertyAssignment(t)&&s.isIdentifier(t.name)||s.isVariableDeclaration(t)&&s.isIdentifier(t.name))?t.name.text:""},En=(e,t,n)=>{let r=e.breakpoint.function_node,i=`${e.module}_${r.index}_${r.length}`,o=s.factory.createObjectLiteralExpression(ft(n).map(l=>s.factory.createShorthandPropertyAssignment(s.factory.createIdentifier(l))));return vt(t,o,i)},fi=(e,t,n)=>{e.kind==s.SyntaxKind.FunctionDeclaration&&(e=s.factory.createFunctionExpression(e.modifiers,e.asteriskToken,e.name,e.typeParameters,e.parameters,e.type,e.body));let r=Ue(n,t),i=s.factory.createVariableStatement(void 0,s.factory.createVariableDeclarationList([s.factory.createVariableDeclaration(s.factory.createArrayBindingPattern(e.parameters),void 0,void 0,s.factory.createIdentifier("__arguments"))]));if(t.breakpoint.function_node==n){if(i=En(t,i,e),We(t)){let f=L(n)[0],p=`${f.index}_${f.length}`;i=[...i,T`__footprints.set(${p}, true);\n`[0]]}}else i=[i];let l=[s.factory.createParameterDeclaration(void 0,s.factory.createToken(s.SyntaxKind.DotDotDotToken),s.factory.createIdentifier("__arguments"),void 0,void 0,void 0)],a=s.factory.createBlock([...r,...i,...e.body.kind==s.SyntaxKind.Block?e.body.statements:[s.factory.createReturnStatement(e.body)]]),d;if(e.kind==s.SyntaxKind.FunctionExpression)d=s.factory.updateFunctionExpression(e,e.modifiers,void 0,void 0,void 0,l,void 0,a);else if(e.kind==s.SyntaxKind.ArrowFunction)d=s.factory.updateArrowFunction(e,e.modifiers,void 0,l,void 0,void 0,a);else throw console.error("bad node kind for function",e.kind),new Error("illegal state");let c=e.parameters.every(f=>f.dotDotDotToken==null)?e.parameters.length:void 0,_=I`({index: ${n.index}, length: ${n.length}, module: ${t.module}})`,h=n.name!=null?n.name.escapedText:pi(n);return I`__rt.trace(__cxt, ${d}, ${h}, ${c}, ${_})`},hi=(e,t)=>e.getText(t.toplevel).replaceAll(new RegExp("\\(.*\\)","g"),"(...)"),mi=(e,t)=>s.factory.createStringLiteral(JSON.stringify({index:e.index,length:e.length,module:t.module})),gi=(e,t,n)=>{let r=s.factory.createArrayLiteralExpression(e.arguments),i=n.kind==s.SyntaxKind.NewExpression,o=s.factory.createStringLiteral(hi(n.expression,t)),l=mi(n,t);function a(d){return We(t)&&(d=Cn(d,n.expression)),n.expression==t.breakpoint.selected_node&&(d=Kn(d,t,n.expression)),d}if(n.expression.kind==s.SyntaxKind.PropertyAccessExpression||n.expression.kind==s.SyntaxKind.ElementAccessExpression){let d;switch(n.expression.kind){case s.SyntaxKind.PropertyAccessExpression:d=s.factory.createPropertyAccessChain(s.factory.createIdentifier("__obj"),e.expression.questionDotToken,e.expression.name);break;case s.SyntaxKind.ElementAccessExpression:d=s.factory.createElementAccessChain(s.factory.createIdentifier("__obj"),e.expression.questionDotToken,e.expression.argumentExpression);break;default:throw new Error("illegal state")}return d=a(I`( __obj = ${e.expression.expression}, __fn = ${d} )`),I`( ${d}, __rt.trace_call(__cxt, __fn, __obj, ${r}, ${o}, ${i}, ${l}) )`}else{let d=e.expression;return d=a(d),I` __rt.trace_call(__cxt, ${d}, null, ${r}, ${o}, ${i}, ${l}) `}},St=(e,t)=>I` __rt.take_node_snapshot_fast( __cxt, __rt.before_take_node_snapshot(__cxt, ${t}, __call_id), ${e} ) `,vt=(e,t,n)=>T` __rt.before_take_node_snapshot(__cxt, ${n}, __call_id); ${e} __rt.take_node_snapshot(__cxt, ${n}, __call_id, ${t}); `;function yi(e){let t=e.declarationList,n=t.declarations;return n.length==1?[e]:n.map(r=>s.factory.updateVariableStatement(e,void 0,s.factory.updateVariableDeclarationList(t,[r])))}var Kn=(e,t,n)=>{let r=`${t.module}_${n.index}_${n.length}`;if(s.isExpression(n))return St(e,r);if(n.kind==s.SyntaxKind.ExpressionStatement)throw new Error("illegal state");if(n.kind==s.SyntaxKind.VariableStatement||n.kind==s.SyntaxKind.VariableDeclarationList){let i,o=n.kind==s.SyntaxKind.VariableDeclarationList?n:n.declarationList,l=ft(n);if(o.declarations.length==1&&o.declarations[0].name.kind==s.SyntaxKind.Identifier){if(l.length!=1)throw new Error("illegal state");i=s.factory.createIdentifier(l[0])}else i=s.factory.createObjectLiteralExpression(l.map(a=>s.factory.createShorthandPropertyAssignment(s.factory.createIdentifier(a))));return vt(e,i,r)}if(n.kind==s.SyntaxKind.ThrowStatement)return T` __rt.before_take_node_snapshot(__cxt, ${r}, __call_id); ${e}; `;if(n.kind==s.SyntaxKind.ReturnStatement||n.kind==s.SyntaxKind.BreakStatement||n.kind==s.SyntaxKind.ContinueStatement)return[s.factory.createExpressionStatement(St(s.factory.createIdentifier("undefined"),r)),...Array.isArray(e)?e:[e]];if(n.kind==s.SyntaxKind.ImportDeclaration){let i=I`__cxt.modules[${n.moduleSpecifier.text}]`;return vt(e,i,r)}return e},Tn=e=>(e.parent.kind==s.SyntaxKind.CallExpression||e.parent.kind==s.SyntaxKind.NewExpression)&&e==e.parent.expression,Cn=(e,t)=>{let n=`${t.index}_${t.length}`;return I` ( __footprints.set(${n}, false), __tmp = ${e}, __footprints.set(${n}, true), __tmp ) `},bt=new Set;for(let e in s.SyntaxKind){let t=s.SyntaxKind[e];typeof t=="string"&&t.startsWith("Jsx")&&bt.add(parseInt(e))}var $n=e=>!(e.kind==s.SyntaxKind.VariableDeclarationList&&!(e.parent.kind==s.SyntaxKind.ForStatement&&e.parent.initializer==e)||e.kind==s.SyntaxKind.SourceFile||e.kind==s.SyntaxKind.PropertyAssignment||e.kind==s.SyntaxKind.ShorthandPropertyAssignment||e.kind==s.SyntaxKind.ParenthesizedExpression||e.kind==s.SyntaxKind.VariableDeclaration||e.kind==s.SyntaxKind.ExpressionStatement||e.kind==s.SyntaxKind.SpreadElement||e.kind==s.SyntaxKind.SpreadAssignment||e.kind==s.SyntaxKind.BindingElement||e.kind==s.SyntaxKind.ComputedPropertyName||e.kind==s.SyntaxKind.Parameter||e.kind==s.SyntaxKind.NamedImports||e.kind==s.SyntaxKind.ImportSpecifier||e.kind==s.SyntaxKind.ImportClause||e.kind==s.SyntaxKind.TemplateHead||e.kind==s.SyntaxKind.TemplateMiddle||e.kind==s.SyntaxKind.TemplateTail||e.kind==s.SyntaxKind.TemplateSpan||e.kind==s.SyntaxKind.PartiallyEmittedExpression||e.kind==s.SyntaxKind.AsyncKeyword||e.kind==s.SyntaxKind.OmittedExpression||bt.has(e.kind)&&!se(e)||bt.has(e.parent?.kind)&&e.parent?.kind!=s.SyntaxKind.JsxExpression&&e.parent?.kind!=s.SyntaxKind.JsxSpreadAttribute||ke(e,e.parent)||e.parent.kind==s.SyntaxKind.BindingElement&&e.parent.propertyName==e||(e.parent.kind==s.SyntaxKind.PropertyAccessExpression||e.parent.kind==s.SyntaxKind.PropertyAssignment||e.parent.kind==s.SyntaxKind.ShorthandPropertyAssignment)&&e.parent.name==e),xi=(e,t,n)=>{if(!We(t)||!$n(n)||Tn(n))return e;if(n.kind==s.SyntaxKind.Block)if(n.statements.length==0){let r=`${n.index}_${n.length}`;return T`{__footprints.set(${r}, true);}`}else return e;if(s.isExpression(n))return Cn(e,n);{(n.kind==s.SyntaxKind.VariableStatement||n.kind==s.SyntaxKind.VariableDeclarationList)&&(e=yi(e).flatMap(i=>{let o=s.getOriginalNode(i.declarationList.declarations[0]),l=`${o.index}_${o.length}`;return T` __footprints.set(${l}, false); ${i}; __footprints.set(${l}, true); `}));let r=`${n.index}_${n.length}`;return T` __footprints.set(${r}, false); ${e}; __footprints.set(${r}, true); `}},ki=s.createPrinter({newLine:s.NewLineKind.LineFeed,removeComments:!0});function wi(e,t,n){let r={...e,current_function:n},i=xe(n),o=Ue(n,r),l=n.index,a;if(r.breakpoint.function_node==n){let y=`${r.module}_${n.index}_${n.length}`;a=St(s.factory.createNull(),y)}else a=null;let d=s.factory.createUniqueName("loop_result"),c=s.factory.createUniqueName("loop_body"),_=s.factory.createUniqueName("loop_counter"),h=s.factory.createUniqueName("loop_iter_name"),f=s.factory.createUniqueName("loop_location"),p;t.kind==s.SyntaxKind.WhileStatement?p=T` if(${t.expression}) { ${t.statement}; return __rt.Symbol_loop_continue } else { return __rt.Symbol_loop_break } `:p=T` ${t.statement}; if(${t.expression}) { return __rt.Symbol_loop_continue } else { return __rt.Symbol_loop_break } `;let m=new O(i?"async":""),g=new O(i?"await":""),k=Ie(n);return T` const ${f} = {index: ${l}, length: ${n.length}, module: ${r.module}} const ${d} = ${g} __rt.trace_call( __cxt, Object.defineProperty( ${m} () => { ${Kt(n)}; const ${c} = __rt.trace( __cxt, ${m} () => { ${o}; ${a}; ${p} }, null, null, ${f}, ) ${c}.__type = 'loop_iteration' let ${_} = 0 while(true) { if(${_}++ > 1000) { throw new RangeError('Potential infinite loop: exceeded 1000 iterations.') } const ${h} = ${g} ${c}(${k}); if(${h} == __rt.Symbol_loop_continue) { // do nothing, continue loop } else { // return either value returned by return statement, or Symbol_loop_break return ${h} } } }, '__location', {value: ${f}}, ), null, null, null, false, ) if(${d} != __rt.Symbol_loop_break) { return ${d} } `}function Fn(e,t){if(t=s.visitEachChild(t,n=>Fn(e,n)),t.kind==s.SyntaxKind.WhileStatement||t.kind==s.SyntaxKind.DoStatement)return wi(e,t,s.getOriginalNode(t));if(t.kind==s.SyntaxKind.ForOfStatement||t.kind==s.SyntaxKind.ForInStatement){let n=s.getOriginalNode(t),r={...e,current_function:n},i=xe(n),o=Ue(n,r),l=n.index,a=s.factory.createUniqueName("loop_result"),d=s.factory.createUniqueName("loop_body"),c=s.factory.createUniqueName("loop_iter_name"),_=s.factory.createUniqueName("loop_location"),h=s.factory.createUniqueName("loop_initializer"),f;if(n.initializer.kind==s.SyntaxKind.VariableDeclarationList){if(n.initializer.declarations.length!=1)throw new Error("illegal state");let y=t.initializer.declarations[0];f=s.factory.createVariableStatement(void 0,s.factory.updateVariableDeclarationList(t.initializer,[s.factory.updateVariableDeclaration(y,y.name,void 0,void 0,h)]))}else f=s.factory.createExpressionStatement(s.factory.createBinaryExpression(t.initializer,s.factory.createToken(s.SyntaxKind.EqualsToken),h));let p;r.breakpoint.function_node==n?p=En(r,f,n.initializer):p=f;let m=new O(i?"async":""),g=new O(i?"await":""),k=new O(n.kind==s.SyntaxKind.ForOfStatement?"of":"in");return T` const ${_} = {index: ${l}, length: ${n.length}, module: ${r.module}} const ${a} = ${g} __rt.trace_call( __cxt, Object.defineProperty( ${m} () => { ${Kt(n)}; const ${d} = __rt.trace( __cxt, ${m} (${h}) => { ${o}; ${p}; ${t.statement}; return __rt.Symbol_loop_continue }, null, null, ${_}, ) ${d}.__type = 'loop_iteration' for(const ${h} ${k} ${t.expression}) { const ${c} = ${g} ${d}(${h}); if(${c} == __rt.Symbol_loop_continue) { // do nothing, continue loop } else { // return either value returned by return statement, or Symbol_loop_break return ${c} } } return __rt.Symbol_loop_break }, '__location', {value: ${_}}, ), null, null, null, false, ) if(${a} != __rt.Symbol_loop_break) { return ${a} } `}return t.kind==s.SyntaxKind.BreakStatement?T`return __rt.Symbol_loop_break;`[0]:t.kind==s.SyntaxKind.ContinueStatement?T`return __rt.Symbol_loop_continue;`[0]:t}var _e=e=>function(t){return n=>s.visitNode(n,e)},Si=(e,t)=>{let n=t.breakpoint;return s.transform(e,[_e(function r(i){let o=s.visitEachChild(i,r);if(i.kind==s.SyntaxKind.Block||i.kind==s.SyntaxKind.SourceFile){let l=[],a=[];o.statements.forEach(c=>{s.isFunctionDeclaration(c)?l.push(c):a.push(c)}),o=(i.kind==s.SyntaxKind.Block?s.factory.updateBlock:s.factory.updateSourceFile)(o,[...l,...a])}return o}),_e(function r(i){if(i=s.visitEachChild(i,r),i.kind==s.SyntaxKind.ForStatement){let o=s.factory.createBlock([i.statement,i.incrementor]),l=s.factory.createWhileStatement(i.condition,o);o.parent=l;let a=i.initializer;if(a?.kind==s.SyntaxKind.VariableDeclarationList){let c=s.factory.createVariableDeclarationList(i.initializer.declarations,i.initializer.flags);c.original=void 0,c.parent=i.initializer.parent,a=s.factory.createVariableStatement(void 0,c),a.original=i.initializer}let d=s.factory.createBlock([a,l]);return l.original=i.original,d.parent=s.getOriginalNode(i).parent,d}return i}),_e(function r(i,o=t,l=0){let a=s.getOriginalNode(i),d=o,c=o;(S(a)||E(a))&&(d={...o,current_function:a});let _=ze(a);_!=null&&(c=d={...o,current_function:_});let h=s.visitEachChild(i,f=>r(f,d,l+1));if(i.kind==s.SyntaxKind.ExportAssignment||i.kind==s.SyntaxKind.ExportDeclaration)return[];if(i.modifiers!=null&&i.modifiers.some(f=>f.kind==s.SyntaxKind.ExportKeyword)){let f=s.getEffectiveModifierFlags(i)&~s.ModifierFlags.Export;h=s.factory.replaceModifiers(h,f)}if(i.kind==s.SyntaxKind.ImportDeclaration){let f=[];i?.importClause?.namedBindings!=null&&(f=i.importClause.namedBindings.elements.map(m=>{let g=(m.propertyName??m.name).escapedText;return{name:m.name.escapedText,prop:g}})),i?.importClause?.name!=null&&f.push({prop:"default",name:i.importClause.name.escapedText});let p=s.factory.createObjectBindingPattern(f.map(({name:m,prop:g})=>s.factory.createBindingElement(void 0,g,m,void 0)));h=T` const ${p} = __cxt.modules[${i.moduleSpecifier.text}]; `}if((i.kind==s.SyntaxKind.CallExpression||i.kind==s.SyntaxKind.NewExpression)&&i.expression.kind!=s.SyntaxKind.ImportKeyword&&(h=gi(h,o,a)),S(i)&&(h=fi(h,d,a),i.kind==s.SyntaxKind.FunctionDeclaration)){if(i.name==null)throw new Error("Illegal state");h=s.factory.createVariableStatement(void 0,s.factory.createVariableDeclarationList([s.factory.createVariableDeclaration(i.name,void 0,void 0,h)],s.NodeFlags.Let))}return h=xi(h,c,a),a==n.selected_node&&(Tn(a)||(h=Kn(h,o,a))),h}),_e(r=>Fn(t,r)),_e(function r(i){let o=s.visitEachChild(i,r);return i.kind==s.SyntaxKind.AwaitExpression&&(o=I` (__await_state = __rt.await_start(__cxt, ${o.expression}), await __await_state.promise, __rt.await_finish(__cxt, __await_state)) `),o}),_e(function r(i){return i.kind==s.SyntaxKind.DebuggerStatement?null:s.visitEachChild(i,r)})]).transformed[0]},Dn=(e,t,n,r,i,o,l,a,d)=>{let c=globalThis.app_window.Function,_=globalThis.app_window.eval("(async function(){})").constructor,h=e.sorted.map(g=>{let k=e.modules[g],y={module:g,toplevel:k,breakpoint:d,current_function:k,should_collect_footprints:a};k=Si(k,y);let w=T`"use strict";let __obj, __fn, __tmp;`;k=s.factory.updateSourceFile(k,[...w,...Ue(k,y),...k.statements]);let v=s.transformNodes(e.program.getTypeChecker().getEmitResolver(),void 0,s.factory,Ae,[k],[s.transformJsx],!1).transformed;if(v.length!=1)throw new Error("illegal state");k=v[0];let K=ki.printFile(k),re=xe(k)?_:c,Ot;try{Ot=new re("__cxt","__rt",K)}catch(Nt){throw new Error(Nt.message,{cause:Nt})}return{module:g,fn:Ot}}),f={modules:t==null?{}:qt(t,(g,{module:k})=>k),call_counter:0,version_counter:0,children:null,stack:new Array,is_recording_deferred_calls:!1,on_deferred_call:(g,k,y)=>n(Ve(e.modules,g),k,y),execution_id:r,is_toplevel_call:!0,window:globalThis.app_window,storage:o,canvas_ops:{ops:[],contexts:new Set},snapshots:l,footprints:new Map,breakpoint:d,io_trace:i},p=bn(h,f,i),m=g=>{let k=Ve(e.modules,Re(g.calltree,g.deferred_calls));return{...g,breakpoint:d,calltree:k}};return p?.[Symbol.toStringTag]=="Promise"?Promise.resolve(p).then(m):m(p)},vi=(e,t)=>{let n=s.forEachChildRecursively(e,r=>{if(!ln(r,e))return"skip";if(r.index==t.index&&r.length==t.length&&(S(r)||E(r)))return r});if(n==null)throw new Error("illegal state");return n},Ve=(e,t)=>t.toplevel?{...t,code:e[t.module],children:t.children&&t.children.map(n=>Ve(e,n))}:{...t,code:t.fn==null||t.fn.__location==null?null:vi(e[t.fn.__location.module],t.fn.__location),children:t.children&&t.children.map(n=>Ve(e,n))},Tt=(e,t,n)=>e.kind==s.SyntaxKind.AwaitExpression&&!n&&!t.toplevel&&t.value.status==null,Et=class extends Map{get(t){return t=Q(t)?t.original:t,super.get(t)}},Ct=(e,t,n,r,i)=>{i??=new Et;let o=bi(e,t,n,r,i);return i.set(e,o.result),i},bi=(e,t,n,r,i)=>{let o=f=>Ct(f,t,n,e,i),l=f=>n.get(f.index+"_"+f.length),a=l(e);if(e.kind==s.SyntaxKind.VariableDeclarationList&&e.parent.kind==s.SyntaxKind.VariableStatement&&(a=l(e.parent)),r?.kind==s.SyntaxKind.PropertyAccessExpression&&r.name==e&&(l(r.expression)?a=!0:a=void 0),(r?.kind==s.SyntaxKind.PropertyAssignment||r?.kind==s.SyntaxKind.ShorthandPropertyAssignment)&&r.name==e&&l(r.parent)!=null&&(a=!0),Tt(e,t,a)&&(a=void 0),S(e)){if(r!=null)return{result:a==null?void 0:{ok:a}};{let[f,p]=L(e);return l(f)?(i.set(f.original,{ok:!0}),o(p)):i.set(f.original,{ok:!1,is_error_origin:!0}),{result:{ok:i.get(p)?.ok}}}}if(E(e)&&r!=null)return(e.kind==s.SyntaxKind.ForOfStatement||e.kind==s.SyntaxKind.ForInStatement)&&o(e.expression),e.kind==s.SyntaxKind.ForStatement&&o(e.initializer),a==null?{result:void 0}:{result:{ok:a,is_error_origin:!a}};if($n(e)&&!(e.kind==s.SyntaxKind.Block||e.kind==s.SyntaxKind.SourceFile)&&r!=null&&a==null)return{result:void 0};if(r!=null&&ke(e,r))if(e.kind==s.SyntaxKind.PropertyAccessExpression||e.kind==s.SyntaxKind.ElementAccessExpression){let f=L(e);return f.map(m=>o(m)),{result:{ok:f.every(m=>i.get(m)?.ok)}}}else a=!0;if(e.kind==s.SyntaxKind.VariableDeclaration){let[f,p]=[e.name,e.initializer];return p!=null&&o(p),(p==null||i.get(p)?.ok)&&o(f),{result:{ok:a,is_error_origin:a?void 0:i.get(p)?.ok}}}let d=L(e);d&&d.map(f=>o(f));let c=d==null||d.every(f=>i.get(f)?.ok),_=!a&&c;if((e.kind==s.SyntaxKind.Block||e.kind==s.SyntaxKind.SourceFile)&&(d.length!=0&&(a=d.reduce((f,p)=>f&&i.get(p)?.ok,!0)),_=!1),e.kind==s.SyntaxKind.PartiallyEmittedExpression||e.kind==s.SyntaxKind.ExpressionStatement||e.kind==s.SyntaxKind.ParenthesizedExpression||e.kind==s.SyntaxKind.JsxExpression){if(d.length!=1)throw new Error("illegal state");let f=i.get(e.expression);return{result:f==null?null:{...f,is_error_origin:!1}}}if(e.kind==s.SyntaxKind.IfStatement&&(a=l(e.expression),d.some(f=>i.get(f)?.ok===!1)&&(a=!1)),E(e)&&r==null){if(e.kind==s.SyntaxKind.ForOfStatement||e.kind==s.SyntaxKind.ForInStatement){let f=e.statement;o(f);let p=i.get(f)!=null;i.set(e.initializer,{ok:p,is_error_origin:!p})}return{result:void 0}}return[s.SyntaxKind.ReturnStatement,s.SyntaxKind.BreakStatement,s.SyntaxKind.ContinueStatement].includes(e.kind)&&(a!=null&&(a=c),_=!1),e.kind==s.SyntaxKind.PropertyAssignment||e.kind==s.SyntaxKind.ShorthandPropertyAssignment||e.kind==s.SyntaxKind.SpreadElement||e.kind==s.SyntaxKind.SpreadAssignment||e.kind==s.SyntaxKind.JsxSpreadAttribute?{result:{ok:c}}:{result:a===void 0?void 0:{ok:a,is_error_origin:a?void 0:_}}};function Ln(e){return new Map([...e.entries()].map(([t,n])=>[t,structuredClone(n)]))}var we=class extends Map{set(t,n){if(structuredClone(n),typeof t!="string")throw new Error("key must be a string");super.set(t,n)}};var ue=class extends Map{get_by_module_and_node(t,n){if(n.index==null||n.length==null)throw new Error("illegal state");return this.get(`${t}_${n.index}_${n.length}`)}set_by_module_and_node(t,n,r){if(n.index==null||n.length==null)throw new Error("illegal state");return this.set(`${t}_${n.index}_${n.length}`,r)}};var An=e=>e.kind==s.SyntaxKind.ExpressionStatement?e.expression:e.kind==s.SyntaxKind.NotEmittedStatement||e.kind==s.SyntaxKind.EmptyStatement?null:e.kind==s.SyntaxKind.ReturnStatement?e.expression==null?e:e.expression:e.kind=="export"?An(e.children[0]):e,Je=(e,t)=>{let n=S(e);if(n){let d=L(e)[0];if(Z(d,t))return e.parameters.length>0?d:null}let r=A(e,t),i=r==null||(r.kind==s.SyntaxKind.Block||r.kind==s.SyntaxKind.SourceFile)&&t>r.index?A(e,t-1):r;if(i==null||i.kind==s.SyntaxKind.Block||e==i||e.name==i)return null;let o=le(i,e);for(let d of o){if(S(d))break;if(d.kind==s.SyntaxKind.JsxExpression||d.kind==s.SyntaxKind.JsxSpreadAttribute)return d.expression;if(pt(d))return d}if(n&&e.body.kind!=s.SyntaxKind.Block)return e.body;if(o.find(d=>d!=e&&d!=i&&S(d))!=null)return null;if(E(e)&&o.includes(e.expression))return e.expression;if(e.kind==s.SyntaxKind.ForStatement&&o.includes(e.incrementor))return e.incrementor;if(e.kind==s.SyntaxKind.ForStatement&&o.includes(e.condition))return e.condition;let a=s.forEachAncestor(i,d=>{if(d.parent.kind==s.SyntaxKind.IfStatement&&d.parent.expression==d||s.isStatement(d))return d});return An(a)};var b={reload_app_window:"reload_app_window",reload_app_window_finished:"reload_app_window_finished",load_external_imports:"load_external_imports",eval_modules:"eval_modules",eval_modules_finished:"eval_modules_finished"},Nn=(e,t)=>{let n=new Set(e),r=new Map,i=(o,l)=>{if(o.children!=null)for(let a of o.children)i(a,o.code!=null&&E(o.code)?l:o);n.has(o.id)&&r.set(o.id,{id:o.id,version_number:o.version_number,toplevel:l.toplevel,module:l.toplevel?l.module:l.fn?.__location?.module,parent_name:l.fn?.name,args:o.args,log_fn_name:o.fn.name})};return i(t,null),e.map(o=>r.get(o))},Ei=e=>e.run_state?.status!=b.reload_app_window?J({...e,run_state:{status:b.reload_app_window_finished}},!1):e.run_state.on_reload_app_window_finished(e),$t=(e,t,n,r)=>({function_node:n,module:t,selected_node:r,selected_call_id:Zn(e,t,n)}),Ft=e=>{let t=ee(e),n=be(e,e.current_module,t),r=Je(n,t);return $t(e,e.current_module,n,r)},J=(e,t)=>{if(e={...e,calltree:null,modules:null,execution_id:e.execution_id+1,rt_cxt:null,logs:null,current_calltree_node:null,active_calltree_node:null,calltree_node_is_expanded:null,collected_footprints_functions:new Set,frames:new Map,colored_frames:null,frame_coloring:new Map,selected_calltree_node_by_loc:null,selection_state:null,value_explorer:null,snapshots:new ue,footprints:null},t){let n=i=>e.files[i],r=on(e.entrypoint,n,e.use_ts);e={...e,parse_result:r}}return e.parse_result.ok?e.run_state?.status==b.reload_app_window_finished?Pn(e):{...e,run_state:{status:b.reload_app_window,on_reload_app_window_finished:Pn,reload_counter:e.run_state?.reload_counter}}:e},Pn=e=>(e={...e,run_state:{breakpoint:Ft(e),on_eval_modules_finished:Mn}},He(e)),He=e=>{let t=Gt(ht(e.parse_result.modules).map(n=>n.url));return t.length!=0?{...e,run_state:{...e.run_state,status:b.load_external_imports,external_imports:t}}:zn(e,e)},zn=(e,t,n)=>{if(e.run_state!=t.run_state)return e;if(n!=null){let l=new Set(Object.entries(n).filter(([a,d])=>!d.ok).map(([a,d])=>a));if(l.size!=0){let a=ht(e.parse_result.modules).filter(({url:d})=>l.has(d)).map(({node:d,module_name:c,url:_})=>({index:d.index,message:n[_].error.message,module:c}));return{...e,parse_result:{...e.parse_result,ok:!1,problems:a}}}}let r=new ue([...e.snapshots.entries()].map(([l,a])=>[l,a==null?a:new Map(a)])),i=e.run_state.on_eval_modules_finished!=Mn;!i&&e.is_open_app_window&&(e={...e,io_trace:[]});let o=Dn(e.parse_result,n,e.on_deferred_call,e.execution_id,e.io_trace,Ln(i?e.prev_storage:e.storage),r,!e.collected_footprints_functions.has(e.run_state.breakpoint.function_node),e.run_state.breakpoint);return o.then!=null?{...e,run_state:{...e.run_state,status:b.eval_modules,promise:o}}:In(e,e.execution_id,o)},In=(e,t,n)=>{if(e.execution_id!=t)return e;if(e.calltree!=null){if(n.rt_cxt.io_trace_is_replay_aborted)throw new Error("illegal state");if(n.rt_cxt.io_trace_index!=null&&n.rt_cxt.io_trace_index!=n.rt_cxt.io_trace.length)throw new Error("illegal state: trace was replayed partially");e={...e,calltree:er(e.calltree,n.calltree)}}let r=n.rt_cxt.snapshots,i=n.breakpoint,o=i.function_node.kind==s.SyntaxKind.SourceFile?[i.selected_node]:[i.selected_node,i.function_node];for(let a of o){let d=[i.module,a];a!=null&&r.get_by_module_and_node(...d)===void 0&&r.set_by_module_and_node(...d,null)}if(i.selected_node!=null&&i.selected_call_id!=null){let a=r.get_by_module_and_node(i.module,i.selected_node);a!=null&&a.get(i.selected_call_id)===void 0&&a.set(i.selected_call_id,null)}let l={...e,snapshots:r,footprints:new Map([...e.footprints??[],...n.rt_cxt.footprints]),rt_cxt:n.rt_cxt,run_state:{status:b.eval_modules_finished}};if(e.run_state.breakpoint.function_node==null)throw new Error("illegal state");return e.collected_footprints_functions.add(e.run_state.breakpoint.function_node),e.run_state.on_eval_modules_finished(l,n,e.run_state.breakpoint)},Mn=(e,t)=>{if(t.rt_cxt.io_trace_is_replay_aborted)return Xn(e);if(e={...e,calltree:t.calltree,rt_cxt:t.rt_cxt,logs:{logs:Nn(t.logs,t.calltree),log_position:null},modules:t.modules,prev_storage:e.storage,storage:t.rt_cxt.storage},e=qn(e),e.active_calltree_node==null){let{node:n,state:r}=Ye(e);e=fe(r,null,n)}else e=tr(X(e,e.active_calltree_node));if(e.run_state.status==b.reload_app_window)return e;if(e.run_state.status!=b.eval_modules_finished)throw new Error("illegal state");return e},Ki=(e,t,n)=>{let r={...e.files,[e.current_module]:t},i={...e,files:r},o=Xe(i,n),l={type:"write",args:[o.current_module,o.files[o.current_module]]};return{state:J(o,!0),effects:[l]}},Dt=(e,t)=>{if(!e.parse_result.ok)return{state:e,effects:{type:"set_status",args:["invalid syntax"]}};if(e.calltree==null)return{state:e,effects:{type:"set_status",args:["code is executing"]}};let n=be(e,e.current_module,t);if(n==null||n.kind==s.SyntaxKind.SourceFile&&n!=Se(e)||S(n)&&e.snapshots.get_by_module_and_node(e.current_module,n)===null)return{state:e,effects:{type:"set_status",args:["code was not reached during program execution"]}}},Ti=(e,t)=>{let n=e.parse_result.modules[e.current_module],r=A(n,t);if(r==null)return null;let i=le(r,n).find(o=>o.kind==s.SyntaxKind.CallExpression||o.kind==s.SyntaxKind.NewExpression||S(o));return i==null||S(i)?null:i},Ci=e=>{let t=ee(e),n=Dt(e,t);if(n!=null)return n;let r=Ti(e,t);if(r==null)return{state:e,effects:{type:"set_status",args:["no function call to step into"]}};if(e.run_state.status!=b.eval_modules_finished)return{state:e,effects:{type:"set_status",args:["code is not executed yet"]}};let i=(e.active_calltree_node.children??[]).find(o=>{let l=JSON.parse(o.callsite_location);return l.index==r.index&&l.length==r.length});return i==null?{state:e,effects:{type:"set_status",args:["call was not reached during program execution"]}}:pe(i)?{state:e,effects:{type:"set_status",args:["Cannot step into: function is either builtin or from external lib"]}}:ve(e,!0,i)},Rn=(e,t)=>s.isExpression(e)&&e.kind!=s.SyntaxKind.SpreadAssignment&&e.kind!=s.SyntaxKind.SpreadElement&&t?.kind!=s.SyntaxKind.ShorthandPropertyAssignment&&t?.kind!=s.SyntaxKind.ImportDeclaration&&t?.kind!=s.SyntaxKind.ImportClause&&t?.kind!=s.SyntaxKind.ImportSpecifier&&t?.kind!=s.SyntaxKind.NamespaceImport&&(t==null||!ke(e,t))&&!(t!=null&&t.kind==s.SyntaxKind.PropertyAccessExpression&&t.name==e)&&!(t!=null&&t.kind==s.SyntaxKind.PropertyAssignment&&e==t.name)&&t?.kind!=s.SyntaxKind.JsxAttribute&&!(t!=null&&(t.kind==s.SyntaxKind.JsxOpeningElement||t.kind==s.SyntaxKind.JsxClosingElement)&&e.kind==s.SyntaxKind.Identifier&&s.isIntrinsicJsxName(e.escapedText))&&!(t!=null&&se(t)&&se(e)),jn=e=>e.find((t,n)=>{let r=e[n+1];return Rn(t,r)}),$i=(e,t,n,r)=>{if(A(t,r)==null)return{ok:!1,message:"out of scope"};if(e!=null&&e.index==r){let o;if(e.initial_is_expand==n)e.node==t?o=e.node:(o=jn(mt(e.node,t)),(o==null||!s.isExpression(o))&&(o=e.node));else{let a=A(e.node,r);if(a!=e.node){let d=le(a,e.node);o=d.findLast((c,_)=>{let h=d[_+1];return c!=e.node&&Rn(c,h)}),o==null&&(o=e.node)}else o=e.node}return{ok:!0,initial_is_expand:e.initial_is_expand,node:o,index:r}}else{let o=A(t,r),l=jn(le(o,t));return l==null||!s.isExpression(l)?{ok:!1,message:"can only evaluate expression, not statement"}:{ok:!0,index:r,node:l,initial_is_expand:n}}},Fi=(e,t,n)=>{let r=Dt(e,t);if(r!=null)return r;let i=be(e,e.current_module,t);if(i==null)throw new Error("not implemented");let o=$i(e.selection_state,i,n,t),l={...e,selection_state:o,value_explorer:null};if(!o.ok)return{state:l,effects:{type:"set_status",args:[o.message]}};let a=$t(e,e.current_module,i,o.node);return Vn(l,a,!0)},Bn=(e,t,n,r)=>{let i=e.snapshots.get_by_module_and_node(t,n);if(i===null)return{has_snapshot:!0,node_snapshot:null};if(i===void 0)return{has_snapshot:!1};let o=i.get(r);return{has_snapshot:o!==void 0,node_snapshot:o}},On=(e,t,n,r=void 0)=>{let i=e.snapshots.get_by_module_and_node(t,n);if(i===null)return{has_snapshot:!0,node_snapshot:null};if(i===void 0)return{has_snapshot:!1};if(r!=null){let a=i.get(r);if(a!=null)return{has_snapshot:!0,node_snapshot:a};if(a===void 0)return{has_snapshot:!1}}let[o,l]=[...i.entries()].sort((a,d)=>a[0]-d[0]).find(([a,d])=>d!=null);if(o==null)throw new Error("illegal state");return{has_snapshot:!0,node_snapshot:l}},Vn=(e,t,n=!1)=>(e=Jn(e,t,n),e.run_state.status==b.reload_app_window?{...e,run_state:{...e.run_state,on_eval_modules_finished:Di}}:e.value_explorer!=null?e:{state:e,effects:{type:"set_status",args:["expression was not reached during program execution"]}}),Di=e=>{let t=e.selection_state;if(t==null||e.value_explorer!=null)return e;let n=be(e,e.current_module,t.node.index),r=$t(e,e.current_module,n,t.node);return Vn(e,r,!1)},Li=(e,t)=>e.files[t]==null?{state:e,effects:{type:"set_status",args:["File not found"]}}:{...e,current_module:t,selection_state:null,value_explorer:null},Ai=(e,t,n=t)=>J({...e,entrypoint:t,current_module:n},!0),Pi=(e,t)=>J({...e,html_file:t},!0),ji=(e,t)=>J({...e,use_ts:t},!0),Wn=(e,t)=>({state:Un(H(e,t),t.index),effects:{type:"set_focus"}}),Oi=(e,t)=>{let n=e.parse_result.program.getSourceFile(rn(e.current_module)),r=A(n,t);if(r==null||r.kind!=s.SyntaxKind.Identifier)return{state:e,effects:{type:"set_status",args:["not an identifier"]}};{let i=e.parse_result.program.getTypeChecker().getSymbolAtLocation(r);if(i==null)return{state:e};let o=i.getDeclarations()[0];if(o==null)return{state:e};let l=je(o.getSourceFile().fileName);if(l.endsWith(".d.ts"))return{state:e,effects:{type:"set_status",args:["built-in variable"]}};let a={module:l,index:o.index};return Wn(e,a)}},Ni=(e,t)=>({state:H(e,t),effects:{type:"set_focus"}}),Un=(e,t)=>(e=Xe(e,t),e={...e,selection_state:null,value_explorer:null},Dt(e,t)!=null?e:Hn(e,Ft(e),!0)),Lt=(e,t,n,r)=>{let i=r.call_id;if(i==null)throw new Error("illegal state");let o=P(e.calltree,a=>a.id==i);if(Tt(n,o,r.ok)||[s.SyntaxKind.BreakStatement,s.SyntaxKind.ContinueStatement].includes(n.kind))return null;let l;return r.ok?l=void 0:l=q(o).error,{index:n.index,length:n.length,result:{ok:r.ok,value:r.value,error:l}}},Jn=(e,t,n=!1)=>{if(t.selected_call_id==null){let l=P(e.calltree,a=>q(a)?.ok==!1&&a.code==t.function_node&&(!E(a.code)||a.fn.__type=="loop_iteration"));l!=null&&(t={...t,selected_call_id:l.id})}let r=t.selected_node,{has_snapshot:i,node_snapshot:o}=r==null?{has_snapshot:!0,node_snapshot:null}:On(e,t.module,Q(t.selected_node)?t.function_node:t.selected_node,t.selected_call_id);if(i){let l=!1,a,d;if(o==null)if(a=null,t.function_node==Se(e))d=D(e).id,l=e.footprints.get(d)==null;else{let{has_snapshot:c,node_snapshot:_}=On(e,t.module,t.function_node,t.selected_call_id);l=!c,d=_?.call_id}else o!=null&&(d=o.call_id,a=Lt(e,t.function_node,r,o));if(!l)return nr({...e,value_explorer:a},t.function_node,d)}if(!n)throw new Error("illegal state");return{...e,run_state:{status:b.reload_app_window,reload_counter:(e.run_state.reload_counter??0)+1,on_reload_app_window_finished:He,breakpoint:t}}},Hn=(e,t,n)=>t.function_node.kind==s.SyntaxKind.SourceFile&&t.function_node!=Se(e)?e:(e=Jn(e,t,n),e.run_state.status==b.reload_app_window?{...e,run_state:{...e.run_state,on_eval_modules_finished:qn}}:e),qn=e=>e.selection_state!=null||e.value_explorer!=null?e:Hn(e,Ft(e),!0),zi=(e,t,n,r)=>e.execution_id!=n||(e={...e,snapshots:new ue,footprints:new Map,collected_footprints_functions:new Set,calltree:Re(D(e),[...M(e)??[],t]),logs:{...e.logs,logs:e.logs.logs.concat(Nn(r,t))}},t.ok)?e:Ye(e,t).state,Xn=e=>J({...e,io_trace:[],run_state:{...e.run_state,reload_counter:(e.run_state.reload_counter??0)+1}},!1),Yn=(e,t)=>{let n=i=>i.kind=="file"?[i]:i.children.map(n).flat(),r=Object.fromEntries(n(t).map(i=>[i.path,i.contents]));return{...e,project_dir:t,files:{...r,"":e.files[""]}}},Gn=(e,t)=>{let n=l=>e.files[t[l]]==null?"":t[l],r=n("entrypoint"),i=n("current_module"),o=n("html_file");return{...e,entrypoint:r,current_module:i,html_file:o}},Qn=(e,t,n,r)=>{let i=Yn(e,t);return J({...r==null?i:Gn(i,r),has_file_system_access:n},!0)},Ii=(e,t,n)=>({...Qn(e,t,!0),current_module:n}),Mi=(e,t)=>({...e,storage:new we,is_open_app_window:t}),Ri=(e,t,n=0)=>{let r=e.project_dir==null?e:Yn(e,e.project_dir),i=Gn(r,t);return J({...i,execution_id:0,storage:new we,io_trace:[],is_open_app_window:!1,cursor_position_by_file:{[i.current_module]:n}},!0)},qe={get_initial_state:Ri,input:Ki,open_app_window:Mi,load_dir:Qn,create_file:Ii,step_into:Ci,change_current_module:Li,change_entrypoint:Ai,change_html_file:Pi,change_use_ts:ji,goto_location:Wn,goto_definition:Oi,goto_problem:Ni,move_cursor:Un,eval_selection:Fi,reload_app_window_finished:Ei,external_imports_loaded:zn,eval_modules_finished:In,on_deferred_call:zi,clear_io_trace:Xn};var ee=e=>e.cursor_position_by_file[e.current_module]??0,Xe=(e,t)=>({...e,cursor_position_by_file:{...e.cursor_position_by_file,[e.current_module]:t}});var H=(e,t)=>Xe({...e,current_module:t.module},t.index),Bi=e=>e.error?.constructor==ce.constructor&&e.error?.message==ce.message,te=e=>!e.ok||e.value?.[Symbol.toStringTag]=="Promise"&&e.value.status!=null&&!e.value.status.ok,q=e=>e.value?.[Symbol.toStringTag]=="Promise"?e.value.status:e,N=e=>e.toplevel?{module:e.module}:e.fn.__location,Vi=e=>D(e).module,Se=e=>e.parse_result.modules[Vi(e)],pe=e=>!e.toplevel&&!e.fn.is_hosted,Wi=(e,t)=>e?.[t.module]?.[t.index??-1],ir=(e,t,n)=>({...e,[t.module]:{...e?.[t.module],[t.index??-1]:n}}),Zn=(e,t,n)=>e.selected_calltree_node_by_loc?.[t]?.[e.parse_result.modules[t]==n?-1:n.index],Ui=(e,t,n)=>({...e,selected_calltree_node_by_loc:ir(e.selected_calltree_node_by_loc,t,n)}),fe=(e,t,n=e.current_calltree_node)=>({...e,active_calltree_node:t,current_calltree_node:n}),At=(e,t,n=t)=>{let r=N(t);if(Wi(e.colored_frames,r)!=t.id){e={...e,colored_frames:ir(e.colored_frames,r,t.id)};let o=e.frames.get(t.id);if(o==null){let l=e.footprints.get(t.id);if(l==null)throw new Error("illegal state");if(t.code!=null&&E(t.code)&&t.fn?.__type!="loop_iteration")throw new Error("illegal state");o=Ct(t.code,t,l);let a=an(t.code,o);e.frames.set(t.id,o),e.frame_coloring.set(t.id,a)}}return fe(e,t,n)},er=(e,t)=>Ge(e,t)[1],Ge=(e,t)=>{if(e.id!=t.id)throw new Error("illegal state: merge_calltree");if(e.callsite_location==null&&t.callsite_location!=null)return[!0,Ge({...e,callsite_location:t.callsite_location},t)[1]];if(e.snapshot==null&&t.snapshot!=null)return[!0,Ge({...e,snapshot:t.snapshot},t)[1]];if(e.has_more_children){if(t.has_more_children)return[!1,e];if(e.id!=t.id)throw new Error("illegal state");return[!0,t]}if(e.children==null)return[!1,e];if(t.has_more_children)return[!1,e];if(e.children.length!=(t.children?.length??0))throw new Error("illegal state");let[n,r]=Xt((i,o,l)=>{let[a,d]=Ge(o,t.children[l]);return[i||a,d]},!1,e.children);return n?[!0,{...e,children:r}]:[!1,e]},or=(e,t)=>{let n=e.callsite_location;if(n==null)return null;n=JSON.parse(n);let r=Me(t.code,i=>i.index==n.index&&i.length==n.length&&(i.kind==s.SyntaxKind.CallExpression||i.kind==s.SyntaxKind.NewExpression||E(i)));if(r==null)throw new Error("illegal state");return r},rr=(e,t,n)=>{let{has_snapshot:r,node_snapshot:i}=Bn(e,N(e.current_calltree_node).module,t,n);if(r){let o;return i==null?o=null:o=Lt(e,e.current_calltree_node.code,t,i),{should_replay:!1,value_explorer:o}}else return{should_replay:!0}},z=(e,t,n=o=>o,r=!1,i=!1)=>{function o(p){if(i)throw new Error("illegal state");let m=c.code;return{...e,value_explorer:null,run_state:{status:b.reload_app_window,on_reload_app_window_finished:He,on_eval_modules_finished:l,breakpoint:{module:c?.fn?.__location?.module,function_node:m,selected_call_id:c.id,current_calltree_node_id:t.id,selected_node:p}}}}function l(p,m,g){if(g.current_calltree_node_id!=p.current_calltree_node.id)return p;let k=P(p.calltree,y=>y.id==t.id);return z(p,k,n,r,!0)}let[a]=Ee(e.calltree,t);if(!t.toplevel&&!t.fn.is_hosted&&!a.toplevel&&!a.fn.is_hosted)return n({...fe(e,null,t),value_explorer:null,selection_state:null});let d;t.toplevel||t.fn.__type=="loop_iteration"?d=!0:t.code!=null&&E(t.code)?d=!1:a.id=="deferred_calls"?d=!0:pe(t)?d=!1:pe(a)?d=!0:d=e.calltree_node_is_expanded[t.id];let c=d?t:a;e=fe(e,c,t);let _,h,f;if(t.toplevel){if(e.footprints.get(D(e).id)==null)return o();h=null,f=null,_=N(c)}else if(t.fn.__type=="loop_iteration"){let p=N(t).module,m=ee(e),g=!1;if(e.current_module==p&&Z(t.code,m)&&m!=t.code.index)_={module:p,index:m};else{let v=t.code,K=v.kind;if(K==s.SyntaxKind.WhileStatement||K==s.SyntaxKind.DoStatement||K==s.SyntaxKind.ForStatement){let re=v.statement.kind==s.SyntaxKind.Block?v.statement.statements.length==0?K==s.SyntaxKind.ForStatement?v.initializer:v.expression:v.statement.statements[0]:v.statement;_={module:p,index:re.index}}else _={module:p,index:v.initializer.index},g=!0}let k=e.selection_state?.node,y=k!=null&&!(k==t.code.expression&&(t.code.kind==s.SyntaxKind.ForOfStatement||t.code.kind==s.SyntaxKind.ForInStatement))&&k!=t.code.initializer&&Z(t.code,k.index),w;if((t.code.kind==s.SyntaxKind.ForOfStatement||t.code.kind==s.SyntaxKind.ForInStatement)&&(k==t.code.initializer||g)?(f={node:t.code.initializer},w=t.code):y?(f=e.selection_state,w=e.selection_state.node):(w=Je(t.code,_.index),f=null),w==null)h=null,f=null;else{let v;if({value_explorer:h,should_replay:v}=rr(e,w,t.id),v)return o(w)}}else if(t.code!=null&&E(t.code)){let p=t.code.kind;if(p==s.SyntaxKind.WhileStatement||p==s.SyntaxKind.DoStatement)h=null,f=null;else{let m;p==s.SyntaxKind.ForStatement?m=t.code.initializer:m=t.code.expression,f={node:m};let g;if({value_explorer:h,should_replay:g}=rr(e,m,gt(e.calltree,t).id),g)return o(m)}if(_={module:N(t).module,index:t.code.index},t.has_more_children)return o()}else{if(t.snapshot==null)return o();let p;if(d){_=N(t),f=null;let g=e.snapshots.get_by_module_and_node(c.fn.__location.module,c.code)?.get(c.id);if(g==null)return o();g.ok?p=g.value:p=t.snapshot.args}else{let g=or(t,c);if(g==null)return o();_={module:N(c).module,index:g.index},p=t.snapshot.args,f={node:g}}if(p==null)throw new Error("illegal state");let m=t.ok?{"*arguments*":p,"*return*":t.snapshot.value}:{"*arguments*":p,"*throws*":t.snapshot.error};t.context!=null&&(m={...m,"*this before call*":t.snapshot.context_before,"*this after call*":t.snapshot.context_after}),h={index:_.index,result:{ok:!0,is_calltree_node_explorer:!0,value:m}}}return e=r?e:t.toplevel?{...e,current_module:_.module}:H(e,_),e.footprints.get(c.id)==null?o():n({...At(Ui(e,N(c),e.active_calltree_node.id),c,t),value_explorer:h,selection_state:f})},Ji=e=>z(e,e.current_calltree_node,void 0,!0),Ee=(e,t)=>{let n=i=>i.id==t.id?[]:i.children==null?null:i.children.reduce((o,l)=>{if(o!=null)return o;let a=n(l);return a==null?null:[...a,i]},null),r=n(e);if(r==null)throw new Error("illegal state");return r},ne=e=>pe(e)||E(e.code)?e.children!=null&&e.children.length!=0||e.has_more_children:e.toplevel?e.children!=null&&e.children.length!=0:!0,Hi=e=>{let t=e.current_calltree_node,n;if(ne(t)&&e.calltree_node_is_expanded[t.id]&&t.children!=null)n=t.children[0];else{let r=(i,o)=>{if(i.id=="calltree")return null;let[l,...a]=o,d=l.children.findIndex(_=>_==i),c=l.children[d+1];return c??r(l,a)};n=r(t,Ee(e.calltree,t))}return n?.id=="deferred_calls"&&(n.children==null?n=null:n=n.children[0]),n==null?e:z(e,n)},qi=e=>{let t=e.current_calltree_node;if(t.toplevel)return e;let[n]=Ee(e.calltree,t),r=n.children.findIndex(a=>a==t),i=n.children[r-1],o=a=>!ne(a)||!e.calltree_node_is_expanded[a.id]||a.children==null?a:o(a.children[a.children.length-1]),l;return i==null?l=n.id=="deferred_calls"?o(D(e)):n:l=o(i),z(e,l)},Xi=e=>{let t=e.current_calltree_node,n=e.calltree_node_is_expanded[t.id];if(!ne(t)||!n){let[r]=Ee(e.calltree,t);return r.id=="calltree"||r.id=="deferred_calls"?e:z(e,r)}else return ve(e)},Yi=e=>{let t=e.current_calltree_node;return ne(t)?e.calltree_node_is_expanded[t.id]?t.children!=null?z(e,t.children[0]):e:ve(e):e},ve=(e,t,n=e.current_calltree_node)=>{let r=n.id,i=e.calltree_node_is_expanded[r],o=t??!i,l={...e,calltree_node_is_expanded:{...e.calltree_node_is_expanded,[r]:o}};return z(l,n)},Gi=(e,t)=>{let n=P(e.calltree,r=>r.id==t);return z(e,n)},Qi=(e,t)=>{let n=P(e.calltree,r=>r.id==t);return ne(n)?ve(e,void 0,n):z(e,n)},X=(e,t)=>e.calltree_node_is_expanded?.[t.id]?e:{...e,calltree_node_is_expanded:{...e.calltree_node_is_expanded,...Object.fromEntries(Ee(e.calltree,t).map(n=>[n.id,!0])),[t.id]:!0}},Ye=(e,t)=>{if(t??=D(e),t.ok||Bi(t))return{state:X(e,t),node:t};{let n=P(t,r=>!q(r).ok&&(r.children==null||r.children.find(i=>!q(i).ok)==null));return{state:X(e,n),node:n}}},tr=e=>Ye(e).state,be=(e,t,n)=>{let r=e.parse_result.modules[t];if(r==null)return null;if(Z(r,n)){let i=A(r,n),o=s.forEachAncestor(i,l=>{let a=ze(l);if(a!=null)return a;if(S(l)||E(l))return l});return o??r}else return r},nr=(e,t,n)=>{if(t==Se(e)){let i=D(e);return At(X(e,i),i)}if(t.kind==s.SyntaxKind.SourceFile)return e;if(n==null)return fe(e,null);let r=P(e.calltree,i=>i.id==n);if(r==null)throw new Error("illegal state");return At(X(e,r),r)},Zi=e=>{if(e.current_calltree_node.toplevel)return{state:e};if(e.current_calltree_node.code!=null&&E(e.current_calltree_node.code))return{state:e};let t=N(e.active_calltree_node),n;if(e.current_calltree_node==e.active_calltree_node){let r=e.frames.get(e.active_calltree_node.id),i=e.active_calltree_node.code;if(e.active_calltree_node.ok)if(i.body.kind==s.SyntaxKind.Block){let o=Me(i,l=>l.kind==s.SyntaxKind.ReturnStatement&&r.get(l)?.ok);if(o==null)return{state:H(e,{module:t.module,index:i.body.index}),effects:{type:"set_focus"}};n=o.expression}else n=i.body;else n=yt(i,r)}else{let r=e.current_calltree_node.callsite_location;r=JSON.parse(r),n=Me(e.active_calltree_node.code,i=>i.index==r.index&&i.length==r.length)}return{state:{...H(e,{module:t.module,index:n.index}),selection_state:{node:n},value_explorer:{index:n.index,length:n.length,result:e.current_calltree_node.snapshot}},effects:{type:"set_focus"}}},sr=(e,t=!0)=>{if(e.current_calltree_node.toplevel)return{state:e};if(e.current_calltree_node.code!=null&&E(e.current_calltree_node.code))return{state:e};let n=N(e.active_calltree_node),r,i;if(e.current_calltree_node==e.active_calltree_node){if(e.active_calltree_node.toplevel)return{state:e};let o=e.active_calltree_node.code;r=L(o)[0];let l=e.snapshots.get_by_module_and_node(e.active_calltree_node.fn.__location.module,o)?.get(e.active_calltree_node.id);if(l==null)return{state:e};i=l.ok?l:{ok:!1,error:e.active_calltree_node.error}}else{let o=or(e.current_calltree_node,e.active_calltree_node);if(o==null)return{state:e};i={ok:!0,value:e.current_calltree_node.snapshot.args},r=[...o.arguments];let l=o.getChildren();r.index=l.find(a=>a.kind==s.SyntaxKind.OpenParenToken).pos,r.length=l.find(a=>a.kind==s.SyntaxKind.CloseParenToken).pos-r.index+1}return{state:{...H(e,{module:n.module,index:r.index}),selection_state:{node:r},value_explorer:{index:r.index,length:r.length,result:i}},effects:t?{type:"set_focus"}:null}},eo=e=>{let t=[e.current_calltree_node,e.active_calltree_node,D(e)].find(r=>te(r));if(t==null)return{state:e,effects:[{type:"set_status",args:["no error found"]}]};let n=P(t,r=>te(r)&&(r.children==null||r.children.every(i=>!te(i)||pe(i)&&i.children==null)));if(n==null)throw new Error("illegal state: error origin not found");return z(X(e,n),n,r=>{let i=un(r),o=yt(r.active_calltree_node.code,i);return{state:H(r,{module:N(n).module,index:o.index}),effects:{type:"set_focus"}}})},to=(e,t)=>{if(e.logs.logs.length==0)return{state:e};let n=Math.max(Math.min(e.logs.log_position==null?0:e.logs.log_position+t,e.logs.logs.length-1),0);return lr(e,n)},lr=(e,t)=>{e={...e,logs:{...e.logs,log_position:t}};let n=P(e.calltree,r=>r.id==e.logs.logs[t].id);return z(X(e,n),n,r=>{if(r.active_calltree_node==null)return r;let i=sr(r,!1);if(i.effects!=null)throw new Error("illegal state");return i.state})};qe.calltree={arrow_down:Hi,arrow_up:qi,arrow_left:Xi,arrow_right:Yi,select_node:Gi,select_and_toggle_expanded:Qi,select_return_value:Zi,select_arguments:sr,select_error:eo,navigate_logs_position:lr,navigate_logs_increment:to,show_value_explorer:Ji};var Qe=class{constructor(t,n){this.ui=t,this.container=n,this.container.addEventListener("keydown",r=>{r.key=="r"&&(r.ctrlKey||r.metaKey)||r.preventDefault(),r.key=="Escape"&&this.ui.editor.focus(),r.key=="F1"&&this.ui.editor.focus_value_explorer(this.container),r.key=="F2"&&this.ui.editor.focus(),r.key=="a"&&x("calltree.select_arguments"),r.key=="e"&&x("calltree.select_error"),(r.key=="r"||r.key=="Enter")&&x("calltree.select_return_value"),(r.key=="ArrowDown"||r.key=="j")&&x("calltree.arrow_down"),(r.key=="ArrowUp"||r.key=="k")&&x("calltree.arrow_up"),(r.key=="ArrowLeft"||r.key=="h")&&x("calltree.arrow_left"),(r.key=="ArrowRight"||r.key=="l")&&x("calltree.arrow_right")})}on_click_node(t,n){t.target.classList.contains("expand_icon")?x("calltree.select_and_toggle_expanded",n):x("calltree.select_node",n)}clear_calltree(){this.container.innerHTML="",this.node_to_el=new Map,this.state=null}render_loop(t){let{ok:n,error:r}=q(t),i;t.code.kind==s.SyntaxKind.WhileStatement&&(i="while"),t.code.kind==s.SyntaxKind.DoStatement&&(i="do while"),(t.code.kind==s.SyntaxKind.ForInStatement||t.code.kind==s.SyntaxKind.ForOfStatement||t.code.kind==s.SyntaxKind.ForStatement)&&(i="for");let o=t.has_more_children?t.children_count:t.children.length;return u("span","call_header "+(n?"":"error"),i+" loop("+o+")",n?null:[": ",$(r)])}render_loop_iteration(t,n){let{ok:r,error:i}=q(t),o=n.children.indexOf(t),l=null;(t.code.kind==s.SyntaxKind.ForOfStatement||t.code.kind==s.SyntaxKind.ForInStatement)&&(l=t.code.initializer.getText()+" = "+$(t.args[0]));let a=Ie(t.code);return a!=null&&(l=a.getText()+" = "+$(t.args[0])),u("span","call_header "+(r?"":"error"),u("span","loop_step","step "+o,(l!=null||!r)&&":"),l,r?"":u("span","call_header error",l!=null&&":\xA0",$(i)))}render_node(t,n){let r=this.state.calltree_node_is_expanded[t.id],i=u("div","callnode",u("div",{class:"call_el",click:o=>this.on_click_node(o,t.id)},ne(t)?r&&t.has_more_children?u("div","spinner"):u("span","expand_icon",r?"\u25BC":"\u25B6"):u("span","expand_icon_placeholder","\xA0"),t.toplevel?u("span",t.ok?"":"call_header error",u("i","","toplevel: "+(t.module==""?"*scratch*":t.module)),t.ok?"":u("span","",":\xA0",$(t.error))):t.fn.__type=="loop_iteration"?this.render_loop_iteration(t,n):t.code!=null&&E(t.code)?this.render_loop(t):u("span","call_header "+(te(t)?"error":"")+(t.fn.is_hosted?"":" native"),t.is_new?"new ":"",t.context==null?"":u("span","",typeof t.context=="object"?t.context.constructor?.name||"":$(t.context),"."),t.fn.name==""?"anonymous":t.fn.name,"(",...Y(t.args.map(o=>$(o))),")",": ",t.ok?$(t.value):$(t.error))),t.children==null||!r?null:t.children.map(o=>this.render_node(o,t)));return this.node_to_el.set(t.id,i),i.is_expanded=r,i}render_active(t,n){let r=this.node_to_el.get(t.id).getElementsByClassName("call_el")[0];n?r.classList.add("active"):r.classList.remove("active")}render_select_node(t,n){if(t!=null&&this.render_active(t.current_calltree_node,!1),this.state=n,this.render_active(this.state.current_calltree_node,!0),t?.current_calltree_node!=n.current_calltree_node){let r=this.container.scrollLeft;oe(this.container,this.node_to_el.get(this.state.current_calltree_node.id).getElementsByClassName("call_el")[0]),this.container.scrollLeft=r}}render_expand_node(t,n){this.state=n,this.do_render_expand_node(t.calltree_node_is_expanded,n.calltree_node_is_expanded,D(t),D(n));let r=M(t),i=M(n);if(r!=null){for(let o=0;othis.render_node(n))))))}};var Ze=class{constructor(t,n){this.el=n,this.ui=t,this.el.addEventListener("keydown",r=>{r.key=="Escape"&&this.ui.editor.focus(),r.key=="Enter"&&this.ui.editor.focus(),r.key=="F1"&&this.ui.editor.focus_value_explorer(this.el),r.key=="F3"&&this.ui.editor.focus(),(r.key=="ArrowDown"||r.key=="j")&&(r.preventDefault(),x("calltree.navigate_logs_increment",1)),(r.key=="ArrowUp"||r.key=="k")&&(r.preventDefault(),x("calltree.navigate_logs_increment",-1))})}rerender_logs(t,n){this.el.innerHTML="",this.render_logs(t,null,n)}render_logs(t,n,r){for(let i=n==null?0:n.logs.length;ix("calltree.navigate_logs_position",i)},u("a",{href:"javascript: void(0)"},l+": "+(o.toplevel?"toplevel":"fn "+(o.parent_name==""?"anonymous":o.parent_name))+":")," ",...Y(o.args.map(d=>$(d)))))}if(n?.log_position!=r.log_position&&(n?.logs==r.logs&&n?.log_position!=null&&this.el.children[n.log_position].classList.remove("active"),r.log_position!=null)){let i=this.el.children[r.log_position];i.classList.add("active"),oe(this.el,i)}}};var et=class{constructor(t,n){this.el=n,this.ui=t,this.el.addEventListener("keydown",r=>{r.key=="Escape"&&this.ui.editor.focus(),r.key=="F4"&&this.ui.editor.focus()})}clear(){this.el.innerHTML="",this.is_rendered=!1,this.io_trace_length=0}render_io_trace(t,n){if(n&&(this.is_rendered=!1),this.is_rendered)return;this.is_rendered=!0,this.el.innerHTML="",this.io_trace_length=t.io_trace.length;let r=t.io_trace,i=t.rt_cxt.io_trace_index??r.length;for(let o=0;o ")));else if(l.type=="call")this.el.appendChild(u("div","call_header "+(te(l)?"error ":"")+(a?"":"native "),l.name,"(",...Y(l.args.map(d=>$(d))),"): ",l.ok?$(l.value):$(l.error)));else throw new Error("unknown item type")}}};var no="leporello-js",ar=`https://firebasestorage.googleapis.com/v0/b/${no}.appspot.com/o/`;async function ro(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}async function io(e){let t=(await ro(e)).slice(0,40),n=new Blob([e],{type:"text/plain"}),r=new FormData;r.append("file",n);let i=await fetch(ar+t,{method:"POST",body:r});if(!i.ok){let l=(await i.json())?.error?.message;throw new Error("Failed to upload: "+l)}return t}async function oo(e){let t=await fetch(ar+e+"?alt=media");if(!t.ok){let r=(await t.json())?.error?.message;throw new Error("Failed to fetch: "+r)}return t.text()}async function cr(){let t=new URLSearchParams(window.location.search).get("share_id");if(t==null)return null;let n=localStorage["share_"+t];if(n!=null)return n;try{return await oo(t)}catch(r){return alert(r.message),null}}async function dr(e){let t=await io(e),n=new URL(window.location);n.searchParams.set("share_id",t),history.replaceState(null,null,n.href)}var tt=class{constructor(){this.el=u("dialog","share_dialog",this.upload_begin=u("p","",u("p","","This button will upload your scratch file to the cloud for sharing with others."),u("ul","",u("li","","Please ensure that no personal data or confidential information is included."),u("li","","Avoid including copyrighted materials.")),u("span",{style:"color: red"},"Caution: Once shared, files cannot be deleted."),this.upload_buttons=u("p",{style:"text-align: center"},u("button",{class:"upload_button",click:()=>this.upload()},"Upload"),this.cancel_button=u("button",{style:"margin-left: 1em",click:()=>this.cancel()},"Cancel"))),this.uploading=u("span",{style:"display: none"},"Uploading..."),this.upload_finish=u("p",{style:"display: none"},u("p","",u("p",{style:` text-align: center; margin-bottom: 1em; font-size: 1.2em `},"Upload successful"),this.url_share=u("input",{type:"text",readonly:!0,style:"min-width: 30em"}),this.copy_button=u("button",{click:()=>this.copy(),style:"margin-left: 1em"},"Copy URL")),this.close_button=u("button",{style:"display: block; margin: auto",click:()=>this.cancel()},"Close")))}async upload(){this.uploading.style.display="",this.upload_begin.style.display="none";try{await dr(C().files[""]),this.url_share.value=window.location.toString(),this.upload_finish.style.display=""}catch(t){alert(t.message),this.upload_begin.style.display=""}finally{this.uploading.style.display="none"}}copy(){this.url_share.select(),document.execCommand("copy")}cancel(){this.upload_finish.style.display="none",this.upload_begin.style.display="",this.el.close()}};var nt=class{constructor(t,n){this.open_app_window=this.open_app_window.bind(this),this.files=new Le(this),this.tabs={},this.debugger={},t.appendChild(this.root=u("div","root",this.editor_container=u("div","editor_container"),u("div","bottom",this.debugger_container=u("div","debugger",this.debugger_loaded=u("div","debugger_wrapper",u("div","tabs",this.tabs.calltree=u("div","tab",u("a",{click:()=>this.set_active_tab("calltree"),href:"javascript: void(0)"},"Call tree (F2)")),this.tabs.logs=u("div","tab",u("a",{click:()=>this.set_active_tab("logs"),href:"javascript: void(0)"},"Logs (F3)")),this.tabs.io_trace=u("div","tab",u("a",{click:()=>this.set_active_tab("io_trace"),href:"javascript: void(0)"},"IO trace (F4)"))),this.debugger.calltree=u("div",{class:"tab_content",tabindex:0}),this.debugger.logs=u("div",{class:"tab_content logs",tabindex:0}),this.debugger.io_trace=u("div",{class:"tab_content io_trace",tabindex:0})),this.debugger_loading=u("div","debugger_wrapper",this.debugger_loading_message=u("div"))),this.problems_container=u("div",{class:"problems_container",tabindex:0},this.problems=u("div"))),this.files.el,this.statusbar=u("div","statusbar",this.loading_spinner=u("div","spinner"),this.status=u("div","status"),this.current_module=u("div","current_module"),u("a",{class:"statusbar_action first",href:"javascript: void(0)",click:()=>this.clear_io_trace()},"Clear IO trace (F6)"),u("a",{class:"statusbar_action open_app_window_button",href:"javascript: void(0)",click:this.open_app_window},"(Re)open app window (F7)",this.open_app_window_tooltip=u("div",{class:"open_app_window_tooltip"},"Click here to open app window")),u("div","options",u("label",{for:"standard"},u("input",{id:"standard",type:"radio",name:"keyboard",checked:localStorage.keyboard=="standard"||localStorage.keyboard==null,change:()=>{this.editor.set_keyboard_handler("standard")}}),"Standard"),u("label",{for:"vim"},u("input",{id:"vim",type:"radio",name:"keyboard",checked:localStorage.keyboard=="vim",change:()=>{this.editor.set_keyboard_handler("vim")}}),"VIM")),u("div","options",u("label",{for:"js"},u("input",{id:"js",type:"radio",name:"use_ts",checked:!n.use_ts,change:()=>{x("change_use_ts",!1)}}),"JavaScript"),u("label",{for:"ts"},u("input",{id:"ts",type:"radio",name:"use_ts",checked:n.use_ts,change:()=>{x("change_use_ts",!0)}}),"TypeScript")),u("a",{class:"show_help",href:"javascript: void(0)",click:()=>this.help_dialog.showModal()},"Help"),u("a",{class:"github",href:"https://leporello.tech",target:"__blank"},"Website"),u("button",{class:"statusbar_button",click:()=>this.share_dialog.showModal()},"Share"),u("button",{class:"statusbar_button",click:()=>this.files.el.showModal()},"Files"),this.help_dialog=this.render_help(),this.share_dialog=new tt().el))),window.addEventListener("keydown",()=>this.clear_status(),!0),window.addEventListener("click",()=>this.clear_status(),!0),window.addEventListener("keydown",r=>{r.key=="F2"&&this.set_active_tab("calltree"),r.key=="F3"&&this.set_active_tab("logs"),r.key=="F4"&&this.set_active_tab("io_trace"),r.key=="F6"&&this.clear_io_trace(),r.key=="F7"&&this.open_app_window()}),this.editor=new De(this,this.editor_container),this.calltree=new Qe(this,this.debugger.calltree),this.logs=new Ze(this,this.debugger.logs),this.io_trace=new et(this,this.debugger.io_trace),this.render_current_module(n.current_module),this.set_active_tab("calltree",!0),t.addEventListener("focusin",r=>{let i;this.editor_container.contains(document.activeElement)?this.editor.has_value_explorer()?i=!this.debugger_container.contains(this.editor.value_explorer.return_to):i=!0:i=!1,this.prev_is_focus_in_editor!=i&&(this.prev_is_focus_in_editor=i,Be(C(),i))})}set_active_tab(t,n=!1){this.active_tab=t,Object.values(this.tabs).forEach(r=>r.classList.remove("active")),this.tabs[t].classList.add("active"),Object.values(this.debugger).forEach(r=>r.style.display="none"),this.debugger[t].style.display="block",t=="io_trace"&&this.io_trace.render_io_trace(C(),!1),n||this.debugger[t].focus(),t=="calltree"&&!n&&x("calltree.show_value_explorer")}clear_io_trace(){x("clear_io_trace")}open_app_window(){this.toggle_open_app_window_tooltip(!1),localStorage.onboarding_open_app_window=!0,Ut(C())}render_debugger_loading(t){this.debugger_container.style="",this.problems_container.style="display: none",this.debugger_loaded.style="display: none",this.debugger_loading.style="",this.debugger_loading_message.innerText=t.run_state.status==b.load_external_imports?"Loading external modules...":"Executing code..."}render_debugger(t){this.debugger_container.style="",this.problems_container.style="display: none",this.debugger_loading.style="display: none",this.debugger_loaded.style="",this.calltree.render_calltree(t),this.logs.render_logs(t,null,t.logs)}render_io_trace(t){this.active_tab=="io_trace"?this.io_trace.render_io_trace(t,!0):this.io_trace.clear()}render_problems(t){this.debugger_container.style="display: none",this.problems_container.style="",this.problems.innerHTML="",t.forEach(n=>{let i=this.editor.get_session(n.module).doc.indexToPosition(n.index),o=n.module==""?"*scratch*":n.module;this.problems.appendChild(u("div","problem",u("a",{href:"javascript:void(0)",click:()=>x("goto_problem",n)},`${o}:${i.row+1}:${i.column} - ${n.message}`)))})}set_status(t){this.current_module.style="display: none",this.status.style="",this.status.innerText=t}clear_status(){this.render_current_module(C().current_module)}render_current_module(t){this.status.style="display: none",this.current_module.innerText=t==""?"*scratch*":t,this.current_module.style=""}render_help(){let t=[["Focus value explorer","F1"],["Navigate value explorer","\u2190 \u2192 \u2191 \u2193 or hjkl"],["Leave value explorer","F1 or Esc"],["Focus call tree view","F2"],["Navigate call tree view","\u2190 \u2192 \u2191 \u2193 or hjkl"],["Leave call tree view","F2 or Esc"],["Focus console logs","F3"],["Navigate console logs","\u2191 \u2193 or jk"],["Leave console logs","F3 or Esc"],["Focus IO trace","F4"],["Leave IO trace","F4 or Esc"],["Jump to definition","F5","gd"],["Expand selection to eval expression","Ctrl-\u2193 or Ctrl-j"],["Collapse selection","Ctrl-\u2191 or Ctrl-k"],["Step into call","F11"],["Step out of call","Shift-F11"],["When in call tree view, jump to return statement","Enter"],["When in call tree view, jump to function arguments","a"],["When in call tree view, jump to error origin","e"],["Clear IO trace","F6"],["(Re)open run window (F7)","F7"]];return u("dialog","help_dialog",u("table","help",u("thead","",u("th","","Action"),u("th","key","Standard"),u("th","key","VIM")),u("tbody","",t.map(([n,r,i])=>u("tr","",u("td","",n),u("td",i==null?{class:"key spanned",colspan:2}:{class:"key"},r),i==null?null:u("td","key",i))))),u("form",{method:"dialog"},u("button",null,"Close")))}toggle_open_app_window_tooltip(t){this.open_app_window_tooltip.classList.toggle("on",t)}};var so=e=>new globalThis.app_window.Function("url",` return import(url) `)(e),lo=async e=>{let t=e.run_state.external_imports,n=await Promise.allSettled(t.map(i=>so(/^\w+:\/\//.test(i)?i:"https://esm.sh/"+i))),r=Object.fromEntries(n.map((i,o)=>[t[o],{ok:i.status=="fulfilled",error:i.reason,module:i.value}]));x("external_imports_loaded",e,r)},rt=(e,t,n=t.current_module)=>{e.editor.ensure_session(n,t.files[n])},ur=(e,t)=>{e.editor.remove_markers_of_type(t,"evaluated_ok"),e.editor.remove_markers_of_type(t,"evaluated_error")},Pt=e=>{e.editor.for_each_session((t,n)=>ur(e,t))},_r=(e,t)=>{let n=t.current_module;ur(e,n),cn(t,n).forEach(r=>{e.editor.add_marker(n,r.result.ok?"evaluated_ok":"evaluated_error",r.index,r.index+r.length)})},pr=(e,t)=>{e.editor.clear_parse_result(),t.parse_result!=null&&(t.parse_result.ok?Object.keys(t.parse_result.modules).forEach(n=>{rt(e,t,n)}):(e.editor.for_each_session((n,r)=>{r.setAnnotations(t.parse_result.problems.filter(i=>i.module==n).map(i=>{let o=r.doc.indexToPosition(i.index);return{row:o.row,column:o.column,text:i.message,type:"error"}}))}),t.parse_result.problems.forEach(n=>{rt(e,t,n.module),e.editor.add_marker(n.module,"error-code",n.index,n.index+n.length)}),e.render_problems(t.parse_result.problems)))},fr=(e,t,n)=>{rt(e,t),e.editor.switch_session(t.current_module),pr(e,t),n!=null&&n.with_app_window&&!localStorage.onboarding_open_app_window&&e.toggle_open_app_window_tooltip(!0)},hr=(e,t,n,r)=>{if(e!=t){if(e.project_dir!=t.project_dir&&n.files.render(t),e.current_module!=t.current_module&&n.files.render_current_module(t.current_module),e.current_module!=t.current_module&&(localStorage.current_module=t.current_module,n.render_current_module(t.current_module)),e.entrypoint!=t.entrypoint&&(localStorage.entrypoint=t.entrypoint),e.html_file!=t.html_file&&(localStorage.html_file=t.html_file),e.use_ts!=t.use_ts&&(localStorage.use_ts=t.use_ts),e.current_module!=t.current_module&&(rt(n,t),n.editor.unembed_value_explorer(),n.editor.switch_session(t.current_module)),ee(t)!=n.editor.get_cursor_position()&&r!="on_deferred_call"&&n.editor.set_cursor_position(ee(t)),(e.run_state?.status!=t.run_state.status||t.run_state.status==b.reload_app_window&&e.run_state.reload_counter!=t.run_state.reload_counter)&&(t.run_state.status==b.reload_app_window&&at(t),t.run_state.status==b.load_external_imports&&lo(t),t.run_state.status==b.eval_modules&&t.run_state.promise.then(i=>{x("eval_modules_finished",t.execution_id,i)}),n.loading_spinner.style.visibility=t.run_state.status==b.eval_modules_finished||t.run_state.status==b.reload_app_window_finished?"hidden":"initial"),e.parse_result!=t.parse_result&&pr(n,t),t.parse_result?.ok?e.calltree==null||e.execution_id!=t.execution_id?t.calltree==null?(n.calltree.clear_calltree(),Pt(n),n.render_debugger_loading(t)):(n.render_debugger(t),Pt(n),_r(n,t),n.logs.rerender_logs(t,t.logs),(e.io_trace!=t.io_trace||e.rt_cxt?.io_trace_index!=t.rt_cxt.io_trace_index)&&n.render_io_trace(t)):(M(e)==null&&M(t)!=null&&n.calltree.render_deferred_calls(t),t.io_trace.length!=n.io_trace.io_trace_length&&n.render_io_trace(t),(e.calltree!=t.calltree||e.calltree_node_is_expanded!=t.calltree_node_is_expanded)&&n.calltree.render_expand_node(e,t),t.current_calltree_node!=e.current_calltree_node&&n.calltree.render_select_node(e,t),e.colored_frames!=t.colored_frames&&_r(n,t),n.logs.render_logs(t,e.logs,t.logs),(e.run_state.status!=t.run_state.status&&t.run_state.status=="eval_modules_finished"||(e.current_calltree_node!=t.current_calltree_node||e.calltree_node_is_expanded!=t.calltree_node_is_expanded)&&t.run_state.status=="eval_modules_finished")&&Be(t,n.is_focus_in_editor)):(n.calltree.clear_calltree(),Pt(n)),e.selection_state!=t.selection_state){n.editor.remove_markers_of_type(t.current_module,"selection");let i=t.selection_state?.node;i!=null&&n.editor.add_marker(t.current_module,"selection",i.index,i.index+i.length)}e.value_explorer!=t.value_explorer&&(t.value_explorer==null?n.editor.unembed_value_explorer():n.editor.embed_value_explorer(t,t.value_explorer))}},mr={set_focus:(e,t,n)=>{n.editor.focus()},set_status:(e,[t],n)=>{n.set_status(t)},save_to_localstorage(e,[t,n]){localStorage[t]=n},write:(e,[t,n],r,i)=>{if(t==""){let o=new URL(window.location).searchParams.get("share_id");if(o==null)localStorage.code=n;else{let l="share_"+o;localStorage.code==i.files[""]&&(localStorage.code=n),localStorage[l]=n}}else e.has_file_system_access?Mt(t,n):Zt(t,n)}};import{ts_libs_promise as ao}from"./ts_libs.js";var it=()=>({current_module:localStorage.current_module??"",entrypoint:localStorage.entrypoint??"",html_file:localStorage.html_file??""}),tn=()=>{if(globalThis.showDirectoryPicker==null)throw new Error("Your browser is not supporting File System Access API");he(!0).then(e=>{x("load_dir",e,!0,it())})},nn=async()=>{It(),x("load_dir",await dt,!1,it())},jt,V,j,gr=async(e,t)=>{jt=t;let n={"":localStorage.code||Qt},r,i,o=await he(!1),l;if(o==null){let d=new URLSearchParams(window.location.search).get("example"),c=new URL(window.location);if(c.searchParams.delete("example"),history.replaceState(null,null,c.href),l=ge.find(_=>_.path==d),l==null){let _=await cr();_==null?i=it():(n={"":_},i={current_module:"",entrypoint:""})}else i={current_module:l.entrypoint,entrypoint:l.entrypoint};r={project_dir:await dt,files:n,has_file_system_access:!1}}else i=it(),r={project_dir:o,files:n,has_file_system_access:!0};await ao,j=jt.get_initial_state({...r,use_ts:localStorage.use_ts==null?!1:JSON.parse(localStorage.use_ts),on_deferred_call:(...a)=>x("on_deferred_call",...a)},i),globalThis.__state=j,V=new nt(e,j),globalThis.__ui=V,fr(V,j,l),Wt(j)},C=()=>j,x=(e,...t)=>{e=="input"||e=="write"?console.log("exec",e):console.log("exec",e,...t);let n=e.split(".").reduce((l,a)=>l?.[a],jt);if(n==null)throw new Error("command "+e+" + not found");let r=n(j,...t);console.log("nextstate",r);let i,o;if(r.state!=null?{state:i,effects:o}=r:(i=r,o=null),j?.current_module==null)throw console.error("command did not return state, returned",r),new Error("illegal state");hr(j,i,V,e),o!=null&&(Array.isArray(o)?o:[o]).forEach(l=>{l.type=="write"||l.type=="save_to_localstorage"?console.log("apply effect",l.type):console.log("apply effect",l.type,...l.args??[]),mr[l.type](i,l.args,V,j)}),globalThis.__prev_state=j,globalThis.__state=i,j=i};gr(globalThis.document.getElementById("app"),qe);