From 75b1c5e9423f754c5e81cf64fe5fee5059ed3216 Mon Sep 17 00:00:00 2001 From: dmitry-vsl Date: Fri, 30 May 2025 19:59:02 +0000 Subject: [PATCH] deploy: leporello-js/app@a6e3f1b36f70e54fbed6de3fba58fae9c5409db6 --- .../animated_fractal_tree.js | 19 +- .../canvas_animation_bubbles/bubbles.js | 44 +- docs/examples/domevents.js | 44 +- docs/examples/ethers/block_by_timestamp.js | 18 +- docs/examples/ethers/index.js | 12 +- docs/examples/fibonacci/index.js | 2 +- docs/examples/fractal_tree/fractal_tree.js | 19 +- docs/examples/github_api/index.js | 7 +- docs/examples/plot/index.js | 45 +- docs/examples/preact/index.js | 44 +- docs/examples/preact/stateful.js | 16 +- docs/examples/todos-preact/index.js | 64 +- docs/examples/todos-redux/public/index.html | 20 +- .../examples/todos-redux/src/actions/index.js | 18 +- .../todos-redux/src/components/App.js | 14 +- .../todos-redux/src/components/Footer.js | 19 +- .../todos-redux/src/components/Link.js | 21 +- .../todos-redux/src/components/Todo.js | 17 +- .../todos-redux/src/components/TodoList.js | 13 +- .../todos-redux/src/containers/AddTodo.js | 22 +- .../todos-redux/src/containers/FilterLink.js | 13 +- .../src/containers/VisibleTodoList.js | 23 +- docs/examples/todos-redux/src/index.js | 8 +- .../todos-redux/src/reducers/index.js | 6 +- .../todos-redux/src/reducers/todos.js | 12 +- .../src/reducers/visibilityFilter.js | 4 +- index.html | 523 +---------------- src/launch.js | 62 +- src/ts_libs.js | 114 ++++ styles.css | 548 ++++++++++++++++++ 30 files changed, 959 insertions(+), 832 deletions(-) create mode 100644 src/ts_libs.js create mode 100644 styles.css diff --git a/docs/examples/animated_fractal_tree/animated_fractal_tree.js b/docs/examples/animated_fractal_tree/animated_fractal_tree.js index ef66717..8673c69 100644 --- a/docs/examples/animated_fractal_tree/animated_fractal_tree.js +++ b/docs/examples/animated_fractal_tree/animated_fractal_tree.js @@ -2,34 +2,33 @@ // Author: Sarah Bricault // Canvas setup -const canvas = document.createElement('canvas') +const canvas = document.createElement("canvas") canvas.width = 700 canvas.height = 700 document.body.appendChild(canvas) -const ctx = canvas.getContext('2d') +const ctx = canvas.getContext("2d") ctx.translate(canvas.width / 2, canvas.height) // Draw a tree -await fractalTreeBasic({totalIterations: 10, basicLength: 10, rotate: 25}) +await fractalTreeBasic({ totalIterations: 10, basicLength: 10, rotate: 25 }) function sleep() { return new Promise(resolve => setTimeout(resolve, 3)) } -async function fractalTreeBasic({totalIterations, basicLength, rotate}) { - +async function fractalTreeBasic({ totalIterations, basicLength, rotate }) { // Draw the tree trunk const trunkLength = basicLength * 2 * Math.pow(1.2, totalIterations + 1) const width = Math.pow(totalIterations, 0.6) ctx.beginPath() ctx.moveTo(0, 0) - ctx.lineTo(0, - trunkLength) + ctx.lineTo(0, -trunkLength) ctx.lineWidth = width - ctx.strokeStyle = 'black' + ctx.strokeStyle = "black" ctx.stroke() - await drawBranch(90, [0, - trunkLength], totalIterations + 1) + await drawBranch(90, [0, -trunkLength], totalIterations + 1) async function drawBranch(angle, startPoint, iterations) { const len = basicLength * Math.pow(1.2, iterations) @@ -38,7 +37,7 @@ async function fractalTreeBasic({totalIterations, basicLength, rotate}) { const red = Math.floor(255 - (iterations / totalIterations) * 255) const green = 0 - const blue = Math.floor( 255 - (iterations / totalIterations) * 255) + const blue = Math.floor(255 - (iterations / totalIterations) * 255) const color = `rgb(${red}, ${green}, ${blue})` const x1 = startPoint[0] @@ -47,7 +46,7 @@ async function fractalTreeBasic({totalIterations, basicLength, rotate}) { const y2 = y1 - len * Math.sin((angle * Math.PI) / 180) const x2 = x1 + len * Math.cos((angle * Math.PI) / 180) - console.log('draw branch', x1, y1, x2, y2) + console.log("draw branch", x1, y1, x2, y2) ctx.beginPath() ctx.moveTo(x1, y1) diff --git a/docs/examples/canvas_animation_bubbles/bubbles.js b/docs/examples/canvas_animation_bubbles/bubbles.js index 50c0341..746d45a 100644 --- a/docs/examples/canvas_animation_bubbles/bubbles.js +++ b/docs/examples/canvas_animation_bubbles/bubbles.js @@ -1,8 +1,8 @@ -// Original source: +// Original source: // https://www.freecodecamp.org/news/how-to-create-animated-bubbles-with-html5-canvas-and-javascript/ -const canvas = document.createElement('canvas') -canvas.style.backgroundColor = '#00b4ff' +const canvas = document.createElement("canvas") +canvas.style.backgroundColor = "#00b4ff" document.body.appendChild(canvas) canvas.width = window.innerWidth canvas.height = window.innerHeight @@ -10,9 +10,9 @@ canvas.height = window.innerHeight const context = canvas.getContext("2d") context.font = "30px Arial" -context.textAlign = 'center' -context.fillStyle = 'white' -context.fillText('Click to spawn bubbles', canvas.width/2, canvas.height/2) +context.textAlign = "center" +context.fillStyle = "white" +context.fillText("Click to spawn bubbles", canvas.width / 2, canvas.height / 2) let circles = [] @@ -28,7 +28,7 @@ function draw(circle) { 1, circle.x + 0.5, circle.y + 0.5, - circle.radius + circle.radius, ) gradient.addColorStop(0.3, "rgba(255, 255, 255, 0.3)") @@ -39,20 +39,20 @@ function draw(circle) { } function move(circle, timeDelta) { - circle.x = circle.x + timeDelta*circle.dx - circle.y = circle.y - timeDelta*circle.dy + circle.x = circle.x + timeDelta * circle.dx + circle.y = circle.y - timeDelta * circle.dy } let intervalId function startAnimation() { - if(intervalId == null) { + if (intervalId == null) { intervalId = setInterval(animate, 20) } } function stopAnimation() { - if(intervalId != null) { + if (intervalId != null) { clearInterval(intervalId) intervalId = null } @@ -65,31 +65,31 @@ const animate = () => { const timeDelta = prevFrameTime == null ? 0 : now - prevFrameTime prevFrameTime = now - if(circles.length == 0) { + if (circles.length == 0) { return } - context.clearRect(0, 0, canvas.width, canvas.height) + context.clearRect(0, 0, canvas.width, canvas.height) - circles.forEach(circle => { - move(circle, timeDelta) - draw(circle) - }) + circles.forEach(circle => { + move(circle, timeDelta) + draw(circle) + }) } -const createCircles = (event) => { +const createCircles = event => { startAnimation() - circles = circles.concat(Array.from({length: 50}, () => ( - { + circles = circles.concat( + Array.from({ length: 50 }, () => ({ x: event.pageX, y: event.pageY, radius: Math.random() * 50, dx: Math.random() * 0.3, dy: Math.random() * 0.7, hue: 200, - } - ))) + })), + ) } canvas.addEventListener("click", createCircles) diff --git a/docs/examples/domevents.js b/docs/examples/domevents.js index 8d615cc..d7f7203 100644 --- a/docs/examples/domevents.js +++ b/docs/examples/domevents.js @@ -1,34 +1,40 @@ -window.addEventListener('load', () => { - const text = document.createElement('input') +window.addEventListener("load", () => { + const text = document.createElement("input") - const checkbox = document.createElement('input') - checkbox.setAttribute('type', 'checkbox') + const checkbox = document.createElement("input") + checkbox.setAttribute("type", "checkbox") - const radio = document.createElement('input') - radio.setAttribute('type', 'radio') + const radio = document.createElement("input") + radio.setAttribute("type", "radio") - const range = document.createElement('input') - range.setAttribute('type', 'range') + const range = document.createElement("input") + range.setAttribute("type", "range") - const select = document.createElement('select') - Array.from({length: 5}, (_, i) => i).forEach(i => { - const option = document.createElement('option') - option.setAttribute('value', i) + const select = document.createElement("select") + Array.from({ length: 5 }, (_, i) => i).forEach(i => { + const option = document.createElement("option") + option.setAttribute("value", i) option.innerText = i select.appendChild(option) }) - const div = document.createElement('div') + const div = document.createElement("div") + + const elements = { text, checkbox, range, select, radio, div } - const elements = { text, checkbox, range, select, radio, div} - Object.entries(elements).forEach(([name, el]) => { - document.body.appendChild(el); - ['click', 'input', 'change'].forEach(type => { + document.body.appendChild(el) + ;["click", "input", "change"].forEach(type => { el.addEventListener(type, e => { - const row = document.createElement('div') + const row = document.createElement("div") div.appendChild(row) - row.innerText = [name, type, e.target.value, e.target.checked, e.target.selectedIndex].join(', ') + row.innerText = [ + name, + type, + e.target.value, + e.target.checked, + e.target.selectedIndex, + ].join(", ") }) }) }) diff --git a/docs/examples/ethers/block_by_timestamp.js b/docs/examples/ethers/block_by_timestamp.js index 03f6f61..6e6de71 100644 --- a/docs/examples/ethers/block_by_timestamp.js +++ b/docs/examples/ethers/block_by_timestamp.js @@ -1,21 +1,25 @@ -import {ethers} from 'https://unpkg.com/ethers/dist/ethers.js' +import { ethers } from "ethers" -const URL = 'https://rpc.ankr.com/eth' +const URL = "https://eth-mainnet.public.blastapi.io" const provider = await ethers.getDefaultProvider(URL) -const latest = await provider.getBlock('latest') +const latest = await provider.getBlock("latest") /* Find ethereum block by timestamp using binary search */ -async function getBlockNumberByTimestamp(timestamp, low = 0, high = latest.number) { - if(low + 1 == high) { +async function getBlockNumberByTimestamp( + timestamp, + low = 0, + high = latest.number, +) { + if (low + 1 == high) { return low } else { const mid = Math.floor((low + high) / 2) const midBlock = await provider.getBlock(mid) - if(midBlock.timestamp > timestamp) { + if (midBlock.timestamp > timestamp) { return getBlockNumberByTimestamp(timestamp, low, mid) } else { return getBlockNumberByTimestamp(timestamp, mid, high) @@ -23,6 +27,6 @@ async function getBlockNumberByTimestamp(timestamp, low = 0, high = latest.numbe } } -const timestamp = new Date('2019-06-01').getTime()/1000 +const timestamp = new Date("2019-06-01").getTime() / 1000 const blockNumber = await getBlockNumberByTimestamp(timestamp) const block = await provider.getBlock(blockNumber) diff --git a/docs/examples/ethers/index.js b/docs/examples/ethers/index.js index fe7f5a3..eade781 100644 --- a/docs/examples/ethers/index.js +++ b/docs/examples/ethers/index.js @@ -1,15 +1,15 @@ -import {ethers} from 'https://unpkg.com/ethers@5.7.2/dist/ethers.esm.js' +import { ethers } from "ethers" -const URL = 'https://rpc.ankr.com/eth_goerli' +const URL = "https://eth-mainnet.public.blastapi.io" const p = ethers.getDefaultProvider(URL) const latest = await p.getBlock() -const txs = await Promise.all(latest.transactions.map(t => - p.getTransactionReceipt(t) -)) +const txs = await Promise.all( + latest.transactions.map(t => p.getTransactionReceipt(t)), +) const totalGas = txs .filter(tx => tx != null) - .reduce((gas,tx) => gas.add(tx.gasUsed), ethers.BigNumber.from(0)) + .reduce((gas, tx) => gas.add(tx.gasUsed), ethers.BigNumber.from(0)) diff --git a/docs/examples/fibonacci/index.js b/docs/examples/fibonacci/index.js index cc7a500..bc58101 100644 --- a/docs/examples/fibonacci/index.js +++ b/docs/examples/fibonacci/index.js @@ -1,7 +1,7 @@ // Fibonacci numbers function fib(n) { - if(n == 0 || n == 1) { + if (n == 0 || n == 1) { return n } else { return fib(n - 1) + fib(n - 2) diff --git a/docs/examples/fractal_tree/fractal_tree.js b/docs/examples/fractal_tree/fractal_tree.js index f884446..fd43f85 100644 --- a/docs/examples/fractal_tree/fractal_tree.js +++ b/docs/examples/fractal_tree/fractal_tree.js @@ -2,30 +2,29 @@ // Author: Sarah Bricault // Canvas setup -const canvas = document.createElement('canvas') +const canvas = document.createElement("canvas") canvas.width = 700 canvas.height = 700 document.body.appendChild(canvas) -const ctx = canvas.getContext('2d') +const ctx = canvas.getContext("2d") ctx.translate(canvas.width / 2, canvas.height) // Draw a tree -fractalTreeBasic({totalIterations: 10, basicLength: 10, rotate: 25}) - -function fractalTreeBasic({totalIterations, basicLength, rotate}) { +fractalTreeBasic({ totalIterations: 10, basicLength: 10, rotate: 25 }) +function fractalTreeBasic({ totalIterations, basicLength, rotate }) { // Draw the tree trunk const trunkLength = basicLength * 2 * Math.pow(1.2, totalIterations + 1) const width = Math.pow(totalIterations, 0.6) ctx.beginPath() ctx.moveTo(0, 0) - ctx.lineTo(0, - trunkLength) + ctx.lineTo(0, -trunkLength) ctx.lineWidth = width - ctx.strokeStyle = 'black' + ctx.strokeStyle = "black" ctx.stroke() - drawBranch(90, [0, - trunkLength], totalIterations + 1) + drawBranch(90, [0, -trunkLength], totalIterations + 1) function drawBranch(angle, startPoint, iterations) { const len = basicLength * Math.pow(1.2, iterations) @@ -34,7 +33,7 @@ function fractalTreeBasic({totalIterations, basicLength, rotate}) { const red = Math.floor(255 - (iterations / totalIterations) * 255) const green = 0 - const blue = Math.floor( 255 - (iterations / totalIterations) * 255) + const blue = Math.floor(255 - (iterations / totalIterations) * 255) const color = `rgb(${red}, ${green}, ${blue})` const x1 = startPoint[0] @@ -43,7 +42,7 @@ function fractalTreeBasic({totalIterations, basicLength, rotate}) { const y2 = y1 - len * Math.sin((angle * Math.PI) / 180) const x2 = x1 + len * Math.cos((angle * Math.PI) / 180) - console.log('draw branch', x1, y1, x2, y2) + console.log("draw branch", x1, y1, x2, y2) ctx.beginPath() ctx.moveTo(x1, y1) diff --git a/docs/examples/github_api/index.js b/docs/examples/github_api/index.js index 51c40aa..e38f056 100644 --- a/docs/examples/github_api/index.js +++ b/docs/examples/github_api/index.js @@ -1,7 +1,8 @@ -import _ from 'https://unpkg.com/lodash-es' +import _ from "lodash-es" async function getPopularLanguages() { - const url = 'https://api.github.com/search/repositories?q=stars:%3E1&sort=stars' + const url = + "https://api.github.com/search/repositories?q=stars:%3E1&sort=stars" const resp = await fetch(url) const repos = await resp.json() return _(repos.items) @@ -9,7 +10,7 @@ async function getPopularLanguages() { .filter(l => l != null) .countBy() .toPairs() - .orderBy(([lang, useCount]) => useCount, 'desc') + .orderBy(([lang, useCount]) => useCount, "desc") .map(([lang]) => lang) .value() } diff --git a/docs/examples/plot/index.js b/docs/examples/plot/index.js index 27bdec1..e60e36c 100644 --- a/docs/examples/plot/index.js +++ b/docs/examples/plot/index.js @@ -1,6 +1,6 @@ -import _ from 'https://unpkg.com/lodash-es' +import _ from "lodash-es" -const url = 'https://api.github.com/search/repositories?q=stars:%3E1&sort=stars' +const url = "https://api.github.com/search/repositories?q=stars:%3E1&sort=stars" const resp = await fetch(url) const repos = await resp.json() const langs = _(repos.items) @@ -8,43 +8,18 @@ const langs = _(repos.items) .filter(l => l != null) .countBy() .toPairs() - .map(([language, count]) => ({language, count})) + .map(([language, count]) => ({ language, count })) .value() -import {barY} from "https://cdn.jsdelivr.net/npm/@observablehq/plot@0.6/+esm"; +import { barY } from "@observablehq/plot" /* Move the cursor to the following line and see the plot displayed alongside the code */ -barY(langs, {x: "language", y: "count", sort: {x: "y", reverse: true}, fill: 'purple'}) - .plot() - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +barY(langs, { + x: "language", + y: "count", + sort: { x: "y", reverse: true }, + fill: "purple", +}).plot() diff --git a/docs/examples/preact/index.js b/docs/examples/preact/index.js index 1f45be4..6795647 100644 --- a/docs/examples/preact/index.js +++ b/docs/examples/preact/index.js @@ -1,38 +1,44 @@ const fib = n => { - if(n == 0) { + if (n == 0) { return 0 } - if(n == 1) { + if (n == 1) { return 1 } return fib(n - 1) + fib(n - 2) } - -/* external */ -import {h, render} from 'https://unpkg.com/preact?module'; /* external */ -import {Stateful} from './stateful.js' +import { h, render } from "preact" + +/* external */ +import { Stateful } from "./stateful.js" const Fibonacci = Stateful({ - getInitialState: () => ({index: 0}), + getInitialState: () => ({ index: 0 }), handlers: { - prev: ({index}, event) => ({index: index - 1}), - next: ({index}, event) => ({index: index + 1}), + prev: ({ index }, event) => ({ index: index - 1 }), + next: ({ index }, event) => ({ index: index + 1 }), }, - - render: (props, state, handlers) => - h('div', null, - h('h1', null, - 'nth Fibonacci number is ', + + render: (props, state, handlers) => + h( + "div", + null, + h( + "h1", + null, + "nth Fibonacci number is ", fib(state.index), - ' for n = ', - state.index + " for n = ", + state.index, ), - h('button', {onClick: handlers.prev}, 'Previous'), ' ', - h('button', {onClick: handlers.next}, 'Next'), ' ', - ) + h("button", { onClick: handlers.prev }, "Previous"), + " ", + h("button", { onClick: handlers.next }, "Next"), + " ", + ), }) render(h(Fibonacci), globalThis.document.body) diff --git a/docs/examples/preact/stateful.js b/docs/examples/preact/stateful.js index 3d835a9..25abc58 100644 --- a/docs/examples/preact/stateful.js +++ b/docs/examples/preact/stateful.js @@ -1,18 +1,15 @@ -import {Component} from 'https://unpkg.com/preact?module'; - -export const Stateful = ({getInitialState, handlers, render}) => { +import { Component } from "preact" +export const Stateful = ({ getInitialState, handlers, render }) => { return class extends Component { - constructor() { super() this.compState = getInitialState() this.handlers = Object.fromEntries( - Object - .entries(handlers) - .map(([name, h]) => - [name, this.makeHandler(h)] - ) + Object.entries(handlers).map(([name, h]) => [ + name, + this.makeHandler(h), + ]), ) } @@ -27,5 +24,4 @@ export const Stateful = ({getInitialState, handlers, render}) => { return render(this.props, this.compState, this.handlers) } } - } diff --git a/docs/examples/todos-preact/index.js b/docs/examples/todos-preact/index.js index 64f1cd7..53eb3ca 100644 --- a/docs/examples/todos-preact/index.js +++ b/docs/examples/todos-preact/index.js @@ -2,7 +2,7 @@ Example of a TODO app built using the Preact library */ -import React from 'https://esm.sh/preact/compat' +import React from "preact/compat" // Core @@ -13,7 +13,7 @@ let state if (globalThis.leporello) { // Retrieve initial state from Leporello storage // See: https://github.com/leporello-js/leporello-js?tab=readme-ov-file#saving-state-between-page-reloads - state = globalThis.leporello.storage.get('state') + state = globalThis.leporello.storage.get("state") } /* @@ -21,14 +21,16 @@ if (globalThis.leporello) { This helper function wraps such a function so that its result updates the global state and can be used as an event handler. */ -const handler = fn => (...args) => { - state = fn(state, ...args) - if (globalThis.leporello) { - // Persist state to Leporello storage to restore it after page reloads - globalThis.leporello.storage.set('state', state) +const handler = + fn => + (...args) => { + state = fn(state, ...args) + if (globalThis.leporello) { + // Persist state to Leporello storage to restore it after page reloads + globalThis.leporello.storage.set("state", state) + } + render() } - render() -} // Higher-order function that injects the current state into a component const connect = comp => props => comp(props, state) @@ -39,12 +41,12 @@ const render = () => React.render(, document.body) if (state == null) { state = { todos: [], - text: '', - filter: 'ALL', + text: "", + filter: "ALL", } } -window.addEventListener('load', render) +window.addEventListener("load", render) // Components @@ -68,10 +70,10 @@ const Footer = () => ( const FilterLink = connect(({ filter, children }, state) => { const disabled = state.filter == filter return ( - @@ -87,9 +89,9 @@ const TodoList = connect((_, state) => ( )) const Todo = ({ todo }) => ( -
  • {todo.text}
  • @@ -99,11 +101,7 @@ const AddTodo = connect((_, state) => { return (
    - +
    @@ -114,14 +112,14 @@ const AddTodo = connect((_, state) => { // Returns a filtered list of TODOs based on the current filter state function visibleTodos(state) { - if (state.filter == 'ALL') { + if (state.filter == "ALL") { return state.todos - } else if (state.filter == 'ACTIVE') { + } else if (state.filter == "ACTIVE") { return state.todos.filter(t => !t.completed) - } else if (state.filter == 'COMPLETED') { + } else if (state.filter == "COMPLETED") { return state.todos.filter(t => t.completed) } else { - throw new Error('Unknown filter') + throw new Error("Unknown filter") } } @@ -146,18 +144,18 @@ function createTodo(state, e) { } return { - ...state, + ...state, todos: [...state.todos, { text: state.text }], - text: '', + text: "", } } // Toggles the completion state of a TODO item function toggleTodo(todo, state) { return { - ...state, + ...state, todos: state.todos.map(t => - t == todo ? { ...todo, completed: !todo.completed } : t - ) + t == todo ? { ...todo, completed: !todo.completed } : t, + ), } } diff --git a/docs/examples/todos-redux/public/index.html b/docs/examples/todos-redux/public/index.html index 81b9dd9..a6c74e4 100644 --- a/docs/examples/todos-redux/public/index.html +++ b/docs/examples/todos-redux/public/index.html @@ -1,18 +1,20 @@ - - + + Redux Todos Example - - - - + + + + - diff --git a/docs/examples/todos-redux/src/actions/index.js b/docs/examples/todos-redux/src/actions/index.js index 43fb24f..c9a958f 100644 --- a/docs/examples/todos-redux/src/actions/index.js +++ b/docs/examples/todos-redux/src/actions/index.js @@ -6,23 +6,23 @@ const nextTodoId = new Function(` `)() export const addTodo = text => ({ - type: 'ADD_TODO', + type: "ADD_TODO", id: nextTodoId(), - text + text, }) export const setVisibilityFilter = filter => ({ - type: 'SET_VISIBILITY_FILTER', - filter + type: "SET_VISIBILITY_FILTER", + filter, }) export const toggleTodo = id => ({ - type: 'TOGGLE_TODO', - id + type: "TOGGLE_TODO", + id, }) export const VisibilityFilters = { - SHOW_ALL: 'SHOW_ALL', - SHOW_COMPLETED: 'SHOW_COMPLETED', - SHOW_ACTIVE: 'SHOW_ACTIVE' + SHOW_ALL: "SHOW_ALL", + SHOW_COMPLETED: "SHOW_COMPLETED", + SHOW_ACTIVE: "SHOW_ACTIVE", } diff --git a/docs/examples/todos-redux/src/components/App.js b/docs/examples/todos-redux/src/components/App.js index 11c7bb3..6418b21 100644 --- a/docs/examples/todos-redux/src/components/App.js +++ b/docs/examples/todos-redux/src/components/App.js @@ -1,15 +1,9 @@ -import Footer from './Footer.js' -import AddTodo from '../containers/AddTodo.js' -import VisibleTodoList from '../containers/VisibleTodoList.js' +import Footer from "./Footer.js" +import AddTodo from "../containers/AddTodo.js" +import VisibleTodoList from "../containers/VisibleTodoList.js" const h = React.createElement -const App = () => ( - h('div', null, - h(AddTodo), - h(VisibleTodoList), - h(Footer), - ) -) +const App = () => h("div", null, h(AddTodo), h(VisibleTodoList), h(Footer)) export default App diff --git a/docs/examples/todos-redux/src/components/Footer.js b/docs/examples/todos-redux/src/components/Footer.js index 045df7c..558b868 100644 --- a/docs/examples/todos-redux/src/components/Footer.js +++ b/docs/examples/todos-redux/src/components/Footer.js @@ -1,15 +1,16 @@ -import FilterLink from '../containers/FilterLink.js' -import { VisibilityFilters } from '../actions/index.js' +import FilterLink from "../containers/FilterLink.js" +import { VisibilityFilters } from "../actions/index.js" const h = React.createElement -const Footer = () => ( - h('div', null, - h('span', null, 'Show: '), - h(FilterLink, {filter: VisibilityFilters.SHOW_ALL}, 'All'), - h(FilterLink, {filter: VisibilityFilters.SHOW_ACTIVE}, 'Active'), - h(FilterLink, {filter: VisibilityFilters.SHOW_COMPLETED}, 'Completed'), +const Footer = () => + h( + "div", + null, + h("span", null, "Show: "), + h(FilterLink, { filter: VisibilityFilters.SHOW_ALL }, "All"), + h(FilterLink, { filter: VisibilityFilters.SHOW_ACTIVE }, "Active"), + h(FilterLink, { filter: VisibilityFilters.SHOW_COMPLETED }, "Completed"), ) -) export default Footer diff --git a/docs/examples/todos-redux/src/components/Link.js b/docs/examples/todos-redux/src/components/Link.js index 4375572..2620006 100644 --- a/docs/examples/todos-redux/src/components/Link.js +++ b/docs/examples/todos-redux/src/components/Link.js @@ -1,13 +1,16 @@ const h = React.createElement -const Link = ({ active, children, onClick }) => ( - h('button', { - onClick, - disabled: active, - style:{ - marginLeft: '4px', - } - }, children) -) +const Link = ({ active, children, onClick }) => + h( + "button", + { + onClick, + disabled: active, + style: { + marginLeft: "4px", + }, + }, + children, + ) export default Link diff --git a/docs/examples/todos-redux/src/components/Todo.js b/docs/examples/todos-redux/src/components/Todo.js index 05649d9..cb6787b 100644 --- a/docs/examples/todos-redux/src/components/Todo.js +++ b/docs/examples/todos-redux/src/components/Todo.js @@ -1,12 +1,15 @@ const h = React.createElement -const Todo = ({ onClick, completed, text }) => ( - h('li', { - onClick, - style: { - textDecoration: completed ? 'line-through' : 'none' +const Todo = ({ onClick, completed, text }) => + h( + "li", + { + onClick, + style: { + textDecoration: completed ? "line-through" : "none", + }, }, - }, text) -) + text, + ) export default Todo diff --git a/docs/examples/todos-redux/src/components/TodoList.js b/docs/examples/todos-redux/src/components/TodoList.js index d9d5401..0f2c0d3 100644 --- a/docs/examples/todos-redux/src/components/TodoList.js +++ b/docs/examples/todos-redux/src/components/TodoList.js @@ -1,17 +1,18 @@ -import Todo from './Todo.js' +import Todo from "./Todo.js" const h = React.createElement -const TodoList = ({ todos, toggleTodo }) => ( - h('ul', null, +const TodoList = ({ todos, toggleTodo }) => + h( + "ul", + null, todos.map(todo => h(Todo, { key: todo.id, ...todo, onClick: () => toggleTodo(todo.id), - }) - ) + }), + ), ) -) export default TodoList diff --git a/docs/examples/todos-redux/src/containers/AddTodo.js b/docs/examples/todos-redux/src/containers/AddTodo.js index 6612031..0600a0b 100644 --- a/docs/examples/todos-redux/src/containers/AddTodo.js +++ b/docs/examples/todos-redux/src/containers/AddTodo.js @@ -1,25 +1,27 @@ -import { addTodo } from '../actions/index.js' +import { addTodo } from "../actions/index.js" const h = React.createElement const AddTodo = ({ dispatch }) => { const inputref = {} - return ( - h('div', null, - h('form', { + return h( + "div", + null, + h( + "form", + { onSubmit: e => { e.preventDefault() if (inputref.input.value.trim()) { dispatch(addTodo(inputref.input.value)) - Object.assign(inputref.input, {value: ''}) + Object.assign(inputref.input, { value: "" }) } - } + }, }, - h('input', {ref: input => Object.assign(inputref, {input})}), - h('button', {type: 'submit'}, 'Add Todo') - ) - ) + h("input", { ref: input => Object.assign(inputref, { input }) }), + h("button", { type: "submit" }, "Add Todo"), + ), ) } diff --git a/docs/examples/todos-redux/src/containers/FilterLink.js b/docs/examples/todos-redux/src/containers/FilterLink.js index a772903..44cf165 100644 --- a/docs/examples/todos-redux/src/containers/FilterLink.js +++ b/docs/examples/todos-redux/src/containers/FilterLink.js @@ -1,15 +1,12 @@ -import { setVisibilityFilter } from '../actions/index.js' -import Link from '../components/Link.js' +import { setVisibilityFilter } from "../actions/index.js" +import Link from "../components/Link.js" const mapStateToProps = (state, ownProps) => ({ - active: ownProps.filter === state.visibilityFilter + active: ownProps.filter === state.visibilityFilter, }) const mapDispatchToProps = (dispatch, ownProps) => ({ - onClick: () => dispatch(setVisibilityFilter(ownProps.filter)) + onClick: () => dispatch(setVisibilityFilter(ownProps.filter)), }) -export default ReactRedux.connect( - mapStateToProps, - mapDispatchToProps -)(Link) +export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(Link) diff --git a/docs/examples/todos-redux/src/containers/VisibleTodoList.js b/docs/examples/todos-redux/src/containers/VisibleTodoList.js index 6e3a9d9..4ed41bf 100644 --- a/docs/examples/todos-redux/src/containers/VisibleTodoList.js +++ b/docs/examples/todos-redux/src/containers/VisibleTodoList.js @@ -1,28 +1,25 @@ -import { toggleTodo } from '../actions/index.js' -import TodoList from '../components/TodoList.js' -import { VisibilityFilters } from '../actions/index.js' +import { toggleTodo } from "../actions/index.js" +import TodoList from "../components/TodoList.js" +import { VisibilityFilters } from "../actions/index.js" const getVisibleTodos = (todos, filter) => { - if(filter == VisibilityFilters.SHOW_ALL) { + if (filter == VisibilityFilters.SHOW_ALL) { return todos - } else if(filter == VisibilityFilters.SHOW_COMPLETED) { + } else if (filter == VisibilityFilters.SHOW_COMPLETED) { return todos.filter(t => t.completed) - } else if(filter == VisibilityFilters.SHOW_ACTIVE) { + } else if (filter == VisibilityFilters.SHOW_ACTIVE) { return todos.filter(t => !t.completed) } else { - throw new Error('Unknown filter: ' + filter) + throw new Error("Unknown filter: " + filter) } } const mapStateToProps = state => ({ - todos: getVisibleTodos(state.todos, state.visibilityFilter) + todos: getVisibleTodos(state.todos, state.visibilityFilter), }) const mapDispatchToProps = dispatch => ({ - toggleTodo: id => dispatch(toggleTodo(id)) + toggleTodo: id => dispatch(toggleTodo(id)), }) -export default ReactRedux.connect( - mapStateToProps, - mapDispatchToProps -)(TodoList) +export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(TodoList) diff --git a/docs/examples/todos-redux/src/index.js b/docs/examples/todos-redux/src/index.js index 6df61b9..588f65e 100644 --- a/docs/examples/todos-redux/src/index.js +++ b/docs/examples/todos-redux/src/index.js @@ -1,11 +1,11 @@ -import App from './components/App.js' -import rootReducer from './reducers/index.js' +import App from "./components/App.js" +import rootReducer from "./reducers/index.js" const h = React.createElement const store = Redux.createStore(rootReducer) ReactDOM.render( - h(ReactRedux.Provider, {store}, h(App)), - document.getElementById('root') + h(ReactRedux.Provider, { store }, h(App)), + document.getElementById("root"), ) diff --git a/docs/examples/todos-redux/src/reducers/index.js b/docs/examples/todos-redux/src/reducers/index.js index 74e4c15..b049944 100644 --- a/docs/examples/todos-redux/src/reducers/index.js +++ b/docs/examples/todos-redux/src/reducers/index.js @@ -1,7 +1,7 @@ -import todos from './todos.js' -import visibilityFilter from './visibilityFilter.js' +import todos from "./todos.js" +import visibilityFilter from "./visibilityFilter.js" export default Redux.combineReducers({ todos, - visibilityFilter + visibilityFilter, }) diff --git a/docs/examples/todos-redux/src/reducers/todos.js b/docs/examples/todos-redux/src/reducers/todos.js index 8c2df46..11f9cc8 100644 --- a/docs/examples/todos-redux/src/reducers/todos.js +++ b/docs/examples/todos-redux/src/reducers/todos.js @@ -1,18 +1,16 @@ const todos = (state = [], action) => { - if(action.type == 'ADD_TODO') { + if (action.type == "ADD_TODO") { return [ ...state, { id: action.id, text: action.text, - completed: false - } + completed: false, + }, ] - } else if(action.type == 'TOGGLE_TODO') { + } else if (action.type == "TOGGLE_TODO") { return state.map(todo => - (todo.id === action.id) - ? {...todo, completed: !todo.completed} - : todo + todo.id === action.id ? { ...todo, completed: !todo.completed } : todo, ) } else { return state diff --git a/docs/examples/todos-redux/src/reducers/visibilityFilter.js b/docs/examples/todos-redux/src/reducers/visibilityFilter.js index 285a79a..4d3ba27 100644 --- a/docs/examples/todos-redux/src/reducers/visibilityFilter.js +++ b/docs/examples/todos-redux/src/reducers/visibilityFilter.js @@ -1,7 +1,7 @@ -import { VisibilityFilters } from '../actions/index.js' +import { VisibilityFilters } from "../actions/index.js" const visibilityFilter = (state = VisibilityFilters.SHOW_ALL, action) => { - if(action.type == 'SET_VISIBILITY_FILTER') { + if (action.type == "SET_VISIBILITY_FILTER") { return action.filter } else { return state diff --git a/index.html b/index.html index c969058..e64ee25 100644 --- a/index.html +++ b/index.html @@ -5,6 +5,8 @@ Leporello.js + + @@ -20,526 +22,7 @@ - + diff --git a/src/launch.js b/src/launch.js index 25c7d82..491649b 100644 --- a/src/launch.js +++ b/src/launch.js @@ -1,10 +1,10 @@ -var Ot=(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 Ke=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])}),Nt=()=>{Ke({type:"SET_DIR_HANDLE",data:null}),clearInterval(Ee),Ee=null},R,Ee,yr=()=>{Ee==null&&(Ee=setInterval(()=>{Ke({type:"SET_DIR_HANDLE",data:R})},1e4))},xr=async()=>(R=await globalThis.showDirectoryPicker(),await Ke({type:"SET_DIR_HANDLE",data:R}),R),it=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(()=>it(globalThis)).then(()=>Ke({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}),ot=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 ot(l,o,n,r)}},zt=async(e,t)=>{let r=await(await ot(R,e)).createWritable();await r.write(t),await r.close()},wr=e=>e.name=="node_modules"||e.name.startsWith("."),br=async e=>await(await e.getFile()).text(),It=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=>It(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 br(e)};throw new Error("unknown kind")}},Mt=(e,t)=>ot(R,e,t,{create:!0}),fe=async e=>{let t;return e?t=await xr():t=await kr(),t==null?null:(yr(),It(t,null))};window.addEventListener("unload",()=>{globalThis.app_window!=null&&globalThis.app_window.close()});Sr(window);function Sr(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 st=new URL("./__leporello_files",globalThis.location),lt=e=>{let t=st+"/";return e.html_file==""?t+"__leporello_blank.html":t+e.html_file+"?leporello"},Rt=e=>{it(e),he=!1,k("reload_app_window_finished")},re,Bt=e=>{he=!0,re=document.createElement("iframe"),re.src=lt(e),re.setAttribute("hidden",""),document.body.appendChild(re),globalThis.app_window=re.contentWindow,Wt(globalThis.app_window)},Vt=e=>{he=!0,k("open_app_window"),globalThis.app_window.close(),globalThis.app_window=open(lt(e)),Wt(globalThis.app_window)},Wt=e=>{let t=()=>{let i=e.performance.getEntriesByType("navigation")[0];return i!=null&&i.loadEventEnd>0},n=()=>{t()?(r(),Rt(e)):e.addEventListener("load",()=>{r(),Rt(e)},{once:!0})},r=()=>{e.addEventListener("unload",i=>{setTimeout(()=>{e.closed?e==globalThis.app_window&&(globalThis.app_window=re.contentWindow,at(C())):n()},100)})};n()},he=!1,at=e=>{if(!he){if(he=!0,e==null)throw new Error("illegal state");globalThis.app_window.location=lt(e)}};var s=ts;var vr=e=>e instanceof Error||e instanceof globalThis.app_window.Error,Er=e=>e?.[Symbol.toStringTag]=="Promise",ct=e=>e.clazz==null||e.clazz=="Object",Ce=e=>e==null?null:e.clazz=="Promise"?e.status==null?null:Ce(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,Ut=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}},Te=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():Er(e)?e.status==null?"Promise ":e.status.ok?`Promise `:`Promise `:vr(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 Kr(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(),k("goto_location",e.__location)}),i}function $(e){return typeof e=="function"?Kr(e):Te(e)}function ie(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=Ce(e).find(([o,l])=>o==n)[1];return G(i,r)}else{let n=Ce(e),r=n!=null&&n.length>0;return{displayed_entries:n,header:W(e),short_header:r?Ut(e):null,is_exp:r}}},$e=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),p=G(this.value,h).displayed_entries,f=p.findIndex(([g,x])=>g==_[_.length-1]),m=p[f+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(([p,f])=>p==this.current_path[this.current_path.length-1]),h=c[_-1];if(h==null)this.select_path(d);else{let p=f=>{let m=G(this.value,f);if(!m.is_exp||!this.is_expanded(f))return f;{let g=m.displayed_entries.map(([x,y])=>x);return p([...f,g[g.length-1]])}};this.select_path(p([...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,p])=>(n.children[h]??={},this.render_value_explorer_node([...t,h],n.children[h]))):[]);return n.el=_,_}};var Tr=(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 Cr(e,t){let n=e.renderer;n.$loop.changes?n.once("afterRender",t):t()}var Fe=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}),Tr(this.ace_editor,{on_change:()=>{try{k("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||k("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,p=()=>{h!=null&&d.setScrollTop(h),this.value_explorer.return_to==null?this.focus():this.value_explorer.return_to.focus()},f=()=>{k("step_into")};_.addEventListener("keydown",y=>{y.key=="Escape"&&p()});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:f},"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 $e({container:c,event_target:_,on_escape:p,on_enter:f,scroll_to_element:w=>{h==null&&(h=d.getScrollTop());let b=w.getBoundingClientRect().bottom-this.editor_container.getBoundingClientRect().bottom;b>0&&d.setScrollTop(d.getScrollTop()+b);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 x=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=Ot("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(x);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(x),Cr(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 k("step_into"),{command:"null"}}});let t=Ot("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=>{k("step_into")}}),this.ace_editor.commands.bindKey("Shift-F11","step_out"),this.ace_editor.commands.addCommand({name:"step_out",exec:n=>{k("calltree.arrow_left")}}),this.ace_editor.commands.addCommand({name:"expand_selection",exec:()=>{k("eval_selection",this.get_cursor_position(),!0)}}),this.ace_editor.commands.addCommand({name:"collapse_selection",exec:()=>{k("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];k("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&&k("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();k("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 Eo=new Function("arr","pred",` +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 Jt=(e,t)=>Object.fromEntries(Object.entries(e).map(([n,r])=>[n,t(n,r)]));var Ht=new Function("fn","acc","arr",` +`);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 = []; @@ -15,7 +15,7 @@ var Ot=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( idx += 1; } return [tuple[0], result]; -`),qt=(e,t)=>e.reduce((n,r,i)=>n??t(r,i),null);var Xt=e=>[...new Set(e)];var Gt=`function fib(n) { +`),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 { @@ -24,15 +24,15 @@ var Ot=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( } fib(6) -`,Yt=(e,t)=>{localStorage["examples_"+e]=t},$r=e=>localStorage["examples_"+e],me=[{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})),Fr=me.map(e=>(e.files??[]).concat([e.entrypoint])).flat().map(e=>e.split("/")),Qt=e=>{let t=Fr.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:$r(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 Qt(o)}})))},dt=Qt([]).then(e=>({kind:"directory",name:"examples",path:null,children:e}));var Dr=e=>e.endsWith(".htm")||e.endsWith(".html"),jr=e=>e==""||e.endsWith(".js")||e.endsWith(".ts")||e.endsWith(".mjs")||e.endsWith(".jsx")||e.endsWith(".tsx"),De=class{constructor(t){this.ui=t,this.el=u("div","files_container"),this.render(C())}change_entrypoint(t,n){k("change_entrypoint",t,n),this.ui.editor.focus()}change_html_file(t){let n=t.target.value;k("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:en},"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:Zt},"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:jr(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()})):Dr(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:qt(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 Mt(l,t),fe(!1).then(a=>{t?k("load_dir",a,!0):k("create_file",a,l)})}on_click(t,n){if(t.stopPropagation(),C().has_file_system_access)n.kind!="directory"&&k("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=me.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)}};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 ge=s.ScriptTarget.Latest,Lr=s.createSourceFile("leporello.d.ts",` +`,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 } - `,ge),je={target:ge,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},Le=e=>s.createSourceFile("temp.ts",e,ge,!1,s.ScriptKind.JSX),tn=["lib.d.ts","lib.decorators.d.ts","lib.decorators.legacy.d.ts","lib.dom.asynciterable.d.ts","lib.dom.d.ts","lib.dom.iterable.d.ts","lib.es2015.collection.d.ts","lib.es2015.core.d.ts","lib.es2015.d.ts","lib.es2015.generator.d.ts","lib.es2015.iterable.d.ts","lib.es2015.promise.d.ts","lib.es2015.proxy.d.ts","lib.es2015.reflect.d.ts","lib.es2015.symbol.d.ts","lib.es2015.symbol.wellknown.d.ts","lib.es2016.array.include.d.ts","lib.es2016.d.ts","lib.es2016.full.d.ts","lib.es2016.intl.d.ts","lib.es2017.arraybuffer.d.ts","lib.es2017.d.ts","lib.es2017.date.d.ts","lib.es2017.full.d.ts","lib.es2017.intl.d.ts","lib.es2017.object.d.ts","lib.es2017.sharedmemory.d.ts","lib.es2017.string.d.ts","lib.es2017.typedarrays.d.ts","lib.es2018.asyncgenerator.d.ts","lib.es2018.asynciterable.d.ts","lib.es2018.d.ts","lib.es2018.full.d.ts","lib.es2018.intl.d.ts","lib.es2018.promise.d.ts","lib.es2018.regexp.d.ts","lib.es2019.array.d.ts","lib.es2019.d.ts","lib.es2019.full.d.ts","lib.es2019.intl.d.ts","lib.es2019.object.d.ts","lib.es2019.string.d.ts","lib.es2019.symbol.d.ts","lib.es2020.bigint.d.ts","lib.es2020.d.ts","lib.es2020.date.d.ts","lib.es2020.full.d.ts","lib.es2020.intl.d.ts","lib.es2020.number.d.ts","lib.es2020.promise.d.ts","lib.es2020.sharedmemory.d.ts","lib.es2020.string.d.ts","lib.es2020.symbol.wellknown.d.ts","lib.es2021.d.ts","lib.es2021.full.d.ts","lib.es2021.intl.d.ts","lib.es2021.promise.d.ts","lib.es2021.string.d.ts","lib.es2021.weakref.d.ts","lib.es2022.array.d.ts","lib.es2022.d.ts","lib.es2022.error.d.ts","lib.es2022.full.d.ts","lib.es2022.intl.d.ts","lib.es2022.object.d.ts","lib.es2022.regexp.d.ts","lib.es2022.string.d.ts","lib.es2023.array.d.ts","lib.es2023.collection.d.ts","lib.es2023.d.ts","lib.es2023.full.d.ts","lib.es2023.intl.d.ts","lib.es2024.arraybuffer.d.ts","lib.es2024.collection.d.ts","lib.es2024.d.ts","lib.es2024.full.d.ts","lib.es2024.object.d.ts","lib.es2024.promise.d.ts","lib.es2024.regexp.d.ts","lib.es2024.sharedmemory.d.ts","lib.es2024.string.d.ts","lib.es5.d.ts","lib.es6.d.ts","lib.esnext.array.d.ts","lib.esnext.collection.d.ts","lib.esnext.d.ts","lib.esnext.decorators.d.ts","lib.esnext.disposable.d.ts","lib.esnext.full.d.ts","lib.esnext.intl.d.ts","lib.esnext.iterator.d.ts"],_t;if(globalThis.process==null)_t=Object.fromEntries(await Promise.all(tn.map(e=>fetch("typescript/"+e).then(t=>t.text()).then(t=>[e,t]))));else{let e=await import("fs");_t=Object.fromEntries(tn.map(t=>[t,e.readFileSync("typescript/"+t,"ascii")]))}var nn=Object.fromEntries(Object.entries(_t).map(([e,t])=>{let n=s.createSourceFile(e,t,ge,void 0,s.ScriptKind.TSX);return[e,n]})),rn=e=>e==""?".ts":e,Ae=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 Lr;if(nn[i]!=null)return nn[i];if(Ae(i)==e)return t;throw new Error("illegal state")}};return s.createProgram([e],je,n)};function Ar(e){let t=[];function n(r){r.kind==s.SyntaxKind.ImportDeclaration&&!r.moduleSpecifier.text.startsWith("https://")&&t.push({node:r,messageText:"Local imports are not implemented. Use only https:// imports."}),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 Pr=(e,t,n)=>{let r=s.createSourceFile(e,t,{languageVersion:ge,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,...Ar(r)]),a=l.length==0,d;if(n){let c=function(_,h){_.parent=h,s.forEachChild(_,p=>c(p,_))};d=s.transform(r,[s.transformTypeScript],je).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:Ae(c.file.fileName)}})}},on=(e,t,n)=>{let r=t(e),i=e==""?n:e.endsWith(".ts"),o=Pr(e,r,i);return{ok:o.ok,program:o.program,sorted:[e],modules:o.ok?{[e]:o.node}:null,problems:o.problems}};var Pe=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,Ne=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,ze=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},Oe=class{constructor(t,n,r){this.index=t,this.length=n,this.original=r}},Y=e=>e instanceof Oe,j=e=>{if(Y(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 Oe(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=[];if(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)}),e.kind==s.SyntaxKind.PropertyAccessExpression){if(t.length!=2)throw new Error("illegal state");return[t[0]]}return t},ye=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,Or=e=>(s.isPrefixUnaryExpression(e)||s.isPostfixUnaryExpression(e))&&(e.operator===s.SyntaxKind.PlusPlusToken||e.operator===s.SyntaxKind.MinusMinusToken),xe=(e,t)=>t.kind==Pe.VariableDeclaration&&t.name==e||s.isAssignmentExpression(t)&&t.left==e||t.kind==Pe.BindingElement&&t.name==e||t.kind==s.SyntaxKind.ForOfStatement&&t.initializer==e||t.kind==s.SyntaxKind.ForInStatement&&t.initializer==e||t.kind==Pe.Parameter||e.kind==Pe.BindingElement||t!=null&&Or(t)&&t.operand==e,Nr=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=Nr.printNode(s.EmitHint.Unspecified,t),r=Le(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(),L=(e,t)=>Q(e,t)?s.forEachChild(e,r=>L(r,t))??e:null,Q=(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)],A=(e,t)=>t(e)?e:e.children==null?null:e.children.reduce((n,r)=>n??A(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},Ie=(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 zr=e=>{let t=[];function n(r){if(S(r)){t.push(r);return}for(let i of j(r))n(i,r)}return n(e),t},an=(e,t)=>{let n=(c,_)=>{let h=c.kind==null?c.result:t.get(c),p=_.kind==null?_.result:t.get(_);return h==null?p==null:p!=null&&h.ok==p.ok&&!!h.is_error_origin==!!p.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=j(c).map(y=>l(y)).reduce((y,[w,...b])=>{if(y.length==0)return[w,...b];{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}},...b];if(!i(c)&&K.result==null&&w.result?.ok){let ne=K.index+K.length;return[...y,{...w,index:ne,length:w.index-ne+w.length},...b]}else return!i(c)&&K.result?.ok&&w.result==null?[...y.slice(0,y.length-1),{...K,length:w.index-K.index},w,...b]:[...y,w,...b]}},[]),p=t.get(c);if((p==null||p?.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 f=h[0],m=n(f,c)&&t.get(c)?.ok?[{...f,index:c.index,length:f.length+f.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 f;c.kind==s.SyntaxKind.WhileStatement?f=c.expression.index:f=c.statement.index;let m=t.get(c);return[{index:c.index,length:f-c.index,result:m==null?null:m.ok?{ok:!0}:{ok:!1,is_error_origin:!!m.is_error_origin}},{index:f,length:c.index+c.length-f,result:null}]}if((c.kind==s.SyntaxKind.ForOfStatement||c.kind==s.SyntaxKind.ForInStatement)&&!_){let f=t.get(c);return[{index:c.index,length:c.initializer.index-c.index,result:f==null?null:f.ok?{ok:!0}:{ok:!1,is_error_origin:!!f.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 f=t.get(c);return[{index:c.index,length:c.initializer.index-c.index,result:f==null?null:f.ok?{ok:!0}:{ok:!1,is_error_origin:!!f.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(Y(c)||j(c).length==0)return[r(c)];if(t.get(c)?.is_error_origin){let f=r(c),m=zr(c);return m.length==0?[f]:m.map((g,x)=>{let y;if(x==0)y=c.index;else{let w=m[x-1];y=w.index+w.length}return{index:y,length:g.index-y,result:f.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:f.result}])}let h=o(c,_),p=t.get(c);return p!=null&&!p.ok?h.map(f=>f.result==null?{...f,result:{ok:!1,is_error_origin:!1}}:f):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),Me=(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 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_abort_replay(),new e.window.Error("io replay aborted")},hn=(e,t,n,r,i)=>{let o=e.__cxt;if(o.io_trace_is_replay_aborted)throw new o.window.Error("io replay was aborted");return o.is_recording_deferred_calls?{is_return:!0,value:r?new t(...i):t.apply(n,i)}:{is_return:!1}},mn=(e,t,n,r,i)=>{let o=function(...l){let a=new.target!=null,{value:d,is_return:c}=hn(e,t,this,a,l);if(c)return d;let _=e.__cxt,h=_;if(_.io_trace_is_recording){let p,f,m;try{let g=_.io_trace.length;if(n=="setTimeout"){l=l.slice();let x=l[0];typeof x=="function"&&(l[0]=Object.defineProperty(function(){h==_&&(_.io_trace_is_replay_aborted||(_.io_trace.push({type:"resolution",index:g}),x()))},"name",{value:x.name}))}return f=a?new t(...l):t.apply(this,l),p=!0,f?.[Symbol.toStringTag]=="Promise"?(f=f.then(x=>(f.status={ok:!0,value:x},i?x:e.structuredClone(x))).catch(x=>{throw f.status={ok:!1,error:x},e.structuredClone(x)}).finally(()=>{h==_&&(_.io_trace_is_replay_aborted||_.io_trace.push({type:"resolution",index:g}))}),f):i?f:e.structuredClone(f)}catch(g){throw m=g,p=!1,e.structuredClone(g)}finally{_.io_trace.push({type:"call",name:n,ok:p,value:f,error:m,args:l,has_new_target:a,use_context:r,skip_clone:i,context:r?this:void 0})}}else{let p=_.io_trace[_.io_trace_index];if(p==null||p.type!="call"||p.has_new_target!=a||p.use_context&&p.context!=this||p.name!=n||n=="setTimeout"&&l[1]!=p.args[1]||n!="setTimeout"&&JSON.stringify(p.args)!=JSON.stringify(l))fn(_);else if(_.io_trace.find((m,g)=>m.type=="resolution"&&g>_.io_trace_index)!=null&&!_.io_trace_resolver_is_set&&(_.io_trace_resolver_is_set=!0,setTimeout(()=>{if(h!=_||_.io_trace_is_replay_aborted)return;if(_.io_trace_resolver_is_set=!1,_.io_trace_index>=_.io_trace.length)throw new Error("illegal state");if(_.io_trace[_.io_trace_index].type=="call")_.io_trace_is_replay_aborted=!0,_.io_trace_abort_replay();else for(;_.io_trace_index<_.io_trace.length&&_.io_trace[_.io_trace_index].type=="resolution";){let g=_.io_trace[_.io_trace_index],{resolve:x,reject:y}=_.io_trace_resolvers.get(g.index);if(_.io_trace_index++,_.io_trace[g.index].name=="setTimeout")x();else{let w=_.io_trace[g.index].value,b=_.io_trace[g.index].skip_clone;if(w.status==null)throw new Error("illegal state");w.status.ok?x(b?w.status.value:e.structuredClone(w.status.value)):y(e.structuredClone(w.status.error))}}},0)),_.io_trace_index++,p.ok){if(p.value?.[Symbol.toStringTag]=="Promise")return new _.window.Promise((m,g)=>{_.io_trace_resolvers.set(_.io_trace_index-1,{resolve:m,reject:g})});if(n=="setTimeout"){let m=l[0];return _.io_trace_resolvers.set(_.io_trace_index-1,{resolve:m}),p.value}else return i?p.value:e.structuredClone(p.value)}else throw e.structuredClone(p.error)}};return Object.defineProperty(o,"name",{value:t.name}),o},Ir=e=>{let t=e.Date,n=t.prototype,r=mn(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"])},pn=(e,t)=>{let n=e[t];e[t]=function(...r){let i=new.target!=null,{value:o,is_return:l}=hn(e,n,this,i,r);if(l)return o;let a=e.__cxt;return a.io_trace_is_recording||fn(a),i?new n(...r):n.apply(this,r)},Object.defineProperty(e[t],"name",{value:t})},gn=e=>{if(ae(e,["Math","random"]),ae(e,["setTimeout"],void 0,!0),ae(e,["clearTimeout"]),pn(e,"setInterval"),pn(e,"clearInterval"),Ir(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 yn=globalThis?.CanvasRenderingContext2D?.prototype?.reset;function Mr(e){yn!=null?yn.call(e):e.canvas.width=e.canvas.width+0}function Rr(e){for(let t of e.contexts)Mr(t)}function kn(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 xn(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 Re(e,t){if(e.calltree==null)return;let n=e.rt_cxt;if(n.canvas_ops.ops!=null)if(Rr(n.canvas_ops),t)for(let r of n.canvas_ops.ops)xn(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;xn(i)}}}var Br=["pointerId","buttons","altKey","ctrlKey","shiftKey","metaKey","pageX","pageY","deltaX","deltaY","key","which","timeStamp"],Vr=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"]),Wr=["bubbles","composed","cancelable"],wn=e=>{let t=e.window,n=t.EventTarget.prototype.addEventListener,r=new Set;t.EventTarget.prototype.addEventListener=function(o,...l){return!r.has(o)&&Vr.has(o)&&n.call(t.window,o,a=>{if(e.is_replaying_domevents||["change","input"].includes(o)&&["checkbox","radio"].includes(a.target.type))return;let d=a.constructor.name,c=Object.fromEntries(Br.map(p=>[p,a[p]])),_=Object.fromEntries(Wr.map(p=>[p,a[p]])),h=Jr(t.window,a.target);e.domevents.push({constructorName:d,type:o,props:c,dispatch_props:_,selectors:h,value:a.target.value})},!0),r.add(o),n.call(this,o,...l)}},bn=e=>{try{e.is_replaying_domevents=!0,e.window.document.dispatchEvent(new Event("DOMContentLoaded")),e.window.window.dispatchEvent(new Event("DOMContentLoaded")),e.window.window.dispatchEvent(new Event("load"));for(let t of e.domevents){let n=e.window[t.constructorName],r=Object.defineProperties(new n(t.type,t.dispatch_props),Object.fromEntries(Object.entries(t.props).map(([o,l])=>[o,{value:l}]))),i=Hr(e.window.window,t.selectors);["input","change"].includes(t.type)&&(i.value=t.value),i.dispatchEvent(r)}}finally{e.is_replaying_domevents=!1}};function Ur(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 Jr(e,t){if(t==e)return["window"];let n=[],r;for(;(r=t.getRootNode())&&(n.unshift(Ur(t)),!(r===e.document||r===t));)t=r.host;return n}function Hr(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 ce;try{(function e(){return e()})()}catch(e){ce=e}var qr=500,Xr=e=>(...t)=>{let n=e(...t),r=i=>i.done?i.value:i.value?.[Symbol.toStringTag]=="Promise"?i.value.then(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(o?.[Symbol.toStringTag]=="Promise"){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)])}}},Gr=()=>{let e;return[new Promise(n=>e=n),e]},Sn=Xr(function*(e,t,n){let[r,i]=Gr();if(t=n==null||n.length==0?{...t,logs:[],io_trace_is_recording:!0,io_trace:[]}:{...t,logs:[],io_trace_is_recording:!1,io_trace:n,io_trace_is_replay_aborted:!1,io_trace_resolver_is_set:!1,io_trace_resolvers:new Map,io_trace_index:0,io_trace_abort_replay:i},t.window.__cxt==null)t.window.__cxt=t,ri(t.window),Qr(t),gn(t.window),Yr(t),wn(t),kn(t.window);else throw new Error("illegal state");let o;for(let d=0;d{e.window.leporello={storage:e.storage}},Qr=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 t?.[Symbol.toStringTag]=="Promise"?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},ei=(e,t)=>{if(e.children=t.children_copy,t.status.ok)return t.status.value;throw t.status.error},ti=(e,t,n,r,i)=>{function o(...l){if(e.stack.length>qr)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 p,f,m,g=e.is_toplevel_call;e.is_toplevel_call=!1;try{return new.target==null?f=t.apply(this,l):f=new t(...l),p=!0,f?.[Symbol.toStringTag]=="Promise"&&U(e),h&&(_.ok=p,_.context_after=F(e.window,this),_.value=F(e.window,f)),f}catch(x){throw p=!1,m=x,h&&(_.context_after=F(e.window,this),_.error=F(e.window,m)),U(e),m}finally{let x={id:d,version_number:c,last_version_number:e.version_counter,ok:p,context:this,value:f,error:m,fn:o,args:r==null?l:l.slice(0,r),snapshot:_};if(e.stack.pop()?x.children=e.children:x.has_more_children=e.children!=null&&e.children.length!=0,e.children=a,e.children==null&&(e.children=[]),e.children.push(x),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 b=e.logs;e.logs=[],e.on_deferred_call(w,e.execution_id,b)}}}return Object.defineProperty(o,"name",{value:n}),o.__location=i,o.is_hosted=!0,t.prototype=o.prototype,o},ni=["log","error","info","debug","warn","trace"],ri=e=>{let t=e.console,n=e.__cxt;for(let r of ni){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}},ii=(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 p,f,m;try{return o?f=new t(...r):f=t.apply(n,r),p=!0,f?.[Symbol.toStringTag]=="Promise"&&U(e),h&&(_.ok=p,_.context_after=F(e.window,n),_.value=F(e.window,f)),f}catch(g){throw p=!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:p,value:f,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)}},oi=(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},si=(e,t,n)=>(t!=null&&(t.ok=!0,t.value=F(e.window,n)),n),li=(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},ai=Symbol("loop_break"),ci=Symbol("loop_continue"),di={trace:ti,trace_call:ii,await_start:Zr,await_finish:ei,before_take_node_snapshot:oi,take_node_snapshot_fast:si,take_node_snapshot:li,Symbol_loop_break:ai,Symbol_loop_continue:ci};var Ve=e=>e.should_collect_footprints&&e.breakpoint.function_node==e.current_function,vt=e=>(S(e)?sn(e):ye(e))?T`let __await_state;`:[],We=(e,t)=>[...T`const __call_id = __cxt.call_counter;`,...vt(e),...Ve(t)?T` + `,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); - `:[]],_i=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:""},vn=(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 wt(t,o,i)},ui=(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=We(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=vn(t,i,e),Ve(t)){let p=j(n)[0],f=`${p.index}_${p.length}`;i=[...i,T`__footprints.set(${f}, 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(p=>p.dotDotDotToken==null)?e.parameters.length:void 0,_=I`({index: ${n.index}, length: ${n.length}, module: ${t.module}})`,h=n.name!=null?n.name.escapedText:_i(n);return I`__rt.trace(__cxt, ${d}, ${h}, ${c}, ${_})`},pi=(e,t)=>e.getText(t.toplevel).replaceAll(new RegExp("\\(.*\\)","g"),"(...)"),fi=(e,t)=>s.factory.createStringLiteral(JSON.stringify({index:e.index,length:e.length,module:t.module})),hi=(e,t,n)=>{let r=s.factory.createArrayLiteralExpression(e.arguments),i=n.kind==s.SyntaxKind.NewExpression,o=s.factory.createStringLiteral(pi(n.expression,t)),l=fi(n,t);function a(d){return Ve(t)&&(d=Tn(d,n.expression)),n.expression==t.breakpoint.selected_node&&(d=En(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`( + `:[]],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`( @@ -40,27 +40,27 @@ fib(6) __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}) - `}},kt=(e,t)=>I` + `}},St=(e,t)=>I` __rt.take_node_snapshot_fast( __cxt, __rt.before_take_node_snapshot(__cxt, ${t}, __call_id), ${e} ) - `,wt=(e,t,n)=>T` + `,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 mi(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 En=(e,t,n)=>{let r=`${t.module}_${n.index}_${n.length}`;if(s.isExpression(n))return kt(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 wt(e,i,r)}if(n.kind==s.SyntaxKind.ThrowStatement)return 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(kt(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 wt(e,i,r)}return e},Kn=e=>(e.parent.kind==s.SyntaxKind.CallExpression||e.parent.kind==s.SyntaxKind.NewExpression)&&e==e.parent.expression,Tn=(e,t)=>{let n=`${t.index}_${t.length}`;return I` + `;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 Cn=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||xe(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),gi=(e,t,n)=>{if(!Ve(t)||!Cn(n)||Kn(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 Tn(e,n);{(n.kind==s.SyntaxKind.VariableStatement||n.kind==s.SyntaxKind.VariableDeclarationList)&&(e=mi(e).flatMap(i=>{let o=s.getOriginalNode(i.declarationList.declarations[0]),l=`${o.index}_${o.length}`;return T` + `},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); @@ -68,38 +68,38 @@ fib(6) __footprints.set(${r}, false); ${e}; __footprints.set(${r}, true); - `}},yi=s.createPrinter({newLine:s.NewLineKind.LineFeed,removeComments:!0});function xi(e,t,n){let r={...e,current_function:n},i=ye(n),o=We(n,r),l=n.index,a;if(r.breakpoint.function_node==n){let y=`${r.module}_${n.index}_${n.length}`;a=kt(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"),p=s.factory.createUniqueName("loop_location"),f;t.kind==s.SyntaxKind.WhileStatement?f=T` + `}},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 } - `:f=T` + `: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":""),x=ze(n);return T` - const ${p} = {index: ${l}, length: ${n.length}, module: ${r.module}} + `;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} () => { - ${vt(n)}; + ${Kt(n)}; const ${c} = __rt.trace( __cxt, ${m} () => { ${o}; ${a}; - ${f} + ${p} }, null, null, - ${p}, + ${f}, ) ${c}.__type = 'loop_iteration' @@ -108,7 +108,7 @@ fib(6) if(${_}++ > 1000) { throw new RangeError('Potential infinite loop: exceeded 1000 iterations.') } - const ${h} = ${g} ${c}(${x}); + const ${h} = ${g} ${c}(${k}); if(${h} == __rt.Symbol_loop_continue) { // do nothing, continue loop } else { @@ -118,7 +118,7 @@ fib(6) } }, '__location', - {value: ${p}}, + {value: ${f}}, ), null, null, @@ -128,19 +128,19 @@ fib(6) if(${d} != __rt.Symbol_loop_break) { return ${d} } - `}function $n(e,t){if(t=s.visitEachChild(t,n=>$n(e,n)),t.kind==s.SyntaxKind.WhileStatement||t.kind==s.SyntaxKind.DoStatement)return xi(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=ye(n),o=We(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"),p;if(n.initializer.kind==s.SyntaxKind.VariableDeclarationList){if(n.initializer.declarations.length!=1)throw new Error("illegal state");let y=t.initializer.declarations[0];p=s.factory.createVariableStatement(void 0,s.factory.updateVariableDeclarationList(t.initializer,[s.factory.updateVariableDeclaration(y,y.name,void 0,void 0,h)]))}else p=s.factory.createExpressionStatement(s.factory.createBinaryExpression(t.initializer,s.factory.createToken(s.SyntaxKind.EqualsToken),h));let f;r.breakpoint.function_node==n?f=vn(r,p,n.initializer):f=p;let m=new O(i?"async":""),g=new O(i?"await":""),x=new O(n.kind==s.SyntaxKind.ForOfStatement?"of":"in");return T` + `}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} () => { - ${vt(n)}; + ${Kt(n)}; const ${d} = __rt.trace( __cxt, ${m} (${h}) => { ${o}; - ${f}; + ${p}; ${t.statement}; return __rt.Symbol_loop_continue }, @@ -150,7 +150,7 @@ fib(6) ) ${d}.__type = 'loop_iteration' - for(const ${h} ${x} ${t.expression}) { + for(const ${h} ${k} ${t.expression}) { const ${c} = ${g} ${d}(${h}); if(${c} == __rt.Symbol_loop_continue) { // do nothing, continue loop @@ -173,16 +173,16 @@ fib(6) 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 de=e=>function(t){return n=>s.visitNode(n,e)},ki=(e,t)=>{let n=t.breakpoint;return s.transform(e,[de(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}),de(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}),de(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 _=Ne(a);_!=null&&(c=d={...o,current_function:_});let h=s.visitEachChild(i,p=>r(p,d,l+1));if(i.kind==s.SyntaxKind.ExportAssignment||i.kind==s.SyntaxKind.ExportDeclaration)return[];if(i.modifiers!=null&&i.modifiers.some(p=>p.kind==s.SyntaxKind.ExportKeyword)){let p=s.getEffectiveModifierFlags(i)&~s.ModifierFlags.Export;h=s.factory.replaceModifiers(h,p)}if(i.kind==s.SyntaxKind.ImportDeclaration){let p=[];i?.importClause?.namedBindings!=null&&(p=i.importClause.namedBindings.elements.map(m=>{let g=(m.propertyName??m.name).escapedText;return{name:m.name.escapedText,prop:g}})),i?.importClause?.name!=null&&p.push({prop:"default",name:i.importClause.name.escapedText});let f=s.factory.createObjectBindingPattern(p.map(({name:m,prop:g})=>s.factory.createBindingElement(void 0,g,m,void 0)));h=T` - const ${f} = __cxt.modules[${i.moduleSpecifier.text}]; - `}if((i.kind==s.SyntaxKind.CallExpression||i.kind==s.SyntaxKind.NewExpression)&&i.expression.kind!=s.SyntaxKind.ImportKeyword&&(h=hi(h,o,a)),S(i)&&(h=ui(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=gi(h,c,a),a==n.selected_node&&(Kn(a)||(h=En(h,o,a))),h}),de(r=>$n(t,r)),de(function r(i){let o=s.visitEachChild(i,r);return i.kind==s.SyntaxKind.AwaitExpression&&(o=I` + `}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}),de(function r(i){return i.kind==s.SyntaxKind.DebuggerStatement?null:s.visitEachChild(i,r)})]).transformed[0]},Fn=(e,t,n,r,i,o,l,a,d,c)=>{let _=globalThis.app_window.Function,h=globalThis.app_window.eval("(async function(){})").constructor,p=e.sorted.map(x=>{let y=e.modules[x],w={module:x,toplevel:y,breakpoint:c,current_function:y,should_collect_footprints:d};y=ki(y,w);let b=T`"use strict";let __obj, __fn, __tmp;`;y=s.factory.updateSourceFile(y,[...b,...We(y,w),...y.statements]);let K=s.transformNodes(e.program.getTypeChecker().getEmitResolver(),void 0,s.factory,je,[y],[s.transformJsx],!1).transformed;if(K.length!=1)throw new Error("illegal state");y=K[0];let ne=yi.printFile(y),gr=ye(y)?h:_,At;try{At=new gr("__cxt","__rt",ne)}catch(Pt){throw new Error(Pt.message,{cause:Pt})}return{module:x,fn:At}}),f={modules:t==null?{}:Jt(t,(x,{module:y})=>y),call_counter:0,version_counter:0,children:null,stack:new Array,is_recording_deferred_calls:!1,on_deferred_call:(x,y,w)=>n(Be(e.modules,x),y,w),domevents:r,execution_id:i,is_toplevel_call:!0,window:globalThis.app_window,storage:l,canvas_ops:{ops:[],contexts:new Set},snapshots:a,footprints:new Map,breakpoint:c},m=Sn(p,f,o),g=x=>{let y=Be(e.modules,Me(x.calltree,x.deferred_calls));return{...x,breakpoint:c,calltree:y,io_trace:x.rt_cxt.io_trace}};return m?.[Symbol.toStringTag]=="Promise"?Promise.resolve(m).then(g):g(m)},wi=(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},Be=(e,t)=>t.toplevel?{...t,code:e[t.module],children:t.children&&t.children.map(n=>Be(e,n))}:{...t,code:t.fn==null||t.fn.__location==null?null:wi(e[t.fn.__location.module],t.fn.__location),children:t.children&&t.children.map(n=>Be(e,n))},Et=(e,t,n)=>e.kind==s.SyntaxKind.AwaitExpression&&!n&&!t.toplevel&&t.value.status==null,St=class extends Map{get(t){return t=Y(t)?t.original:t,super.get(t)}},Kt=(e,t,n,r,i)=>{i??=new St;let o=bi(e,t,n,r,i);return i.set(e,o.result),i},bi=(e,t,n,r,i)=>{let o=p=>Kt(p,t,n,e,i),l=p=>n.get(p.index+"_"+p.length),a=l(e);if(e.kind==s.SyntaxKind.VariableDeclarationList&&e.parent.kind==s.SyntaxKind.VariableStatement&&(a=l(e.parent)),(r?.kind==s.SyntaxKind.PropertyAssignment||r?.kind==s.SyntaxKind.ShorthandPropertyAssignment)&&r.name==e&&l(r.parent)!=null&&(a=!0),Et(e,t,a)&&(a=void 0),S(e)){if(r!=null)return{result:a==null?void 0:{ok:a}};{let[p,f]=j(e);return l(p)?(i.set(p.original,{ok:!0}),o(f)):i.set(p.original,{ok:!1,is_error_origin:!0}),{result:{ok:i.get(f)?.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(Cn(e)&&!(e.kind==s.SyntaxKind.Block||e.kind==s.SyntaxKind.SourceFile)&&r!=null&&a==null)return{result:void 0};if(r!=null&&xe(e,r))if(e.kind==s.SyntaxKind.PropertyAccessExpression||e.kind==s.SyntaxKind.ElementAccessExpression){let p=j(e);return p.map(m=>o(m)),{result:{ok:p.every(m=>i.get(m)?.ok)}}}else a=!0;if(e.kind==s.SyntaxKind.VariableDeclaration){let[p,f]=[e.name,e.initializer];return f!=null&&o(f),(f==null||i.get(f)?.ok)&&o(p),{result:{ok:a,is_error_origin:a?void 0:i.get(f)?.ok}}}let d=j(e);d&&d.map(p=>o(p));let c=d==null||d.every(p=>i.get(p)?.ok),_=!a&&c;if((e.kind==s.SyntaxKind.Block||e.kind==s.SyntaxKind.SourceFile)&&(d.length!=0&&(a=d.reduce((p,f)=>p&&i.get(f)?.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 p=i.get(e.expression);return{result:p==null?null:{...p,is_error_origin:!1}}}if(e.kind==s.SyntaxKind.IfStatement&&(a=l(e.expression),d.some(p=>i.get(p)?.ok===!1)&&(a=!1)),E(e)&&r==null){if(e.kind==s.SyntaxKind.ForOfStatement||e.kind==s.SyntaxKind.ForInStatement){let p=e.statement;o(p);let f=i.get(p)!=null;i.set(e.initializer,{ok:f,is_error_origin:!f})}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 Dn(e){return new Map([...e.entries()].map(([t,n])=>[t,structuredClone(n)]))}var ke=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 _e=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 jn=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"?jn(e.children[0]):e,Ue=(e,t)=>{let n=S(e);if(n){let d=j(e)[0];if(Q(d,t))return e.parameters.length>0?d:null}let r=L(e,t),i=r==null||(r.kind==s.SyntaxKind.Block||r.kind==s.SyntaxKind.SourceFile)&&t>r.index?L(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 jn(a)};var v={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"},On=(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))},Si=e=>e.run_state?.status!=v.reload_app_window?J({...e,run_state:{status:v.reload_app_window_finished}},!1):e.run_state.on_reload_app_window_finished(e),Tt=(e,t,n,r)=>({function_node:n,module:t,selected_node:r,selected_call_id:Qn(e,t,n)}),Ct=e=>{let t=Z(e),n=Se(e,e.current_module,t),r=Ue(n,t);return Tt(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 _e,domevents:[],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==v.reload_app_window_finished?Ln(e):{...e,run_state:{status:v.reload_app_window,on_reload_app_window_finished:Ln,reload_counter:e.run_state?.reload_counter}}:e},Ln=e=>(e={...e,run_state:{breakpoint:Ct(e),on_eval_modules_finished:In}},Je(e)),Je=e=>{let t=Xt(ht(e.parse_result.modules).map(n=>n.url));return t.length!=0?{...e,run_state:{...e.run_state,status:v.load_external_imports,external_imports:t}}:Nn(e,e)},Nn=(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 _e([...e.snapshots.entries()].map(([l,a])=>[l,a==null?a:new Map(a)])),i=e.run_state.on_eval_modules_finished!=In,o=Fn(e.parse_result,n,e.on_deferred_call,e.domevents,e.execution_id,e.io_trace,Dn(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:v.eval_modules,promise:o}}:zn(e,e.execution_id,o)},zn=(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");e={...e,calltree:Zn(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:v.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)},In=(e,t)=>{if(t.rt_cxt.io_trace_is_replay_aborted)return qn(e);if(e={...e,calltree:t.calltree,rt_cxt:t.rt_cxt,logs:{logs:On(t.logs,t.calltree),log_position:null},modules:t.modules,io_trace:t.io_trace==null||t.io_trace.length==0?e.io_trace:t.io_trace,prev_storage:e.storage,storage:t.rt_cxt.storage},e=Hn(e),e.active_calltree_node==null){let{node:n,state:r}=Xe(e);e=pe(r,null,n)}else e=er(X(e,e.active_calltree_node));if(e.run_state.status==v.reload_app_window)return e;if(e.run_state.status!=v.eval_modules_finished)throw new Error("illegal state");return e},vi=(e,t,n)=>{let r={...e.files,[e.current_module]:t},i={...e,files:r},o=qe(i,n),l={type:"write",args:[o.current_module,o.files[o.current_module]]};return{state:J(o,!0),effects:[l]}},$t=(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=Se(e,e.current_module,t);if(n==null||n.kind==s.SyntaxKind.SourceFile&&n!=we(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"]}}},Ei=(e,t)=>{let n=e.parse_result.modules[e.current_module],r=L(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},Ki=e=>{let t=Z(e),n=$t(e,t);if(n!=null)return n;let r=Ei(e,t);if(r==null)return{state:e,effects:{type:"set_status",args:["no function call to step into"]}};if(e.run_state.status!=v.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"]}}:ue(i)?{state:e,effects:{type:"set_status",args:["Cannot step into: function is either builtin or from external lib"]}}:be(e,!0,i)},Mn=(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||!xe(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)),An=e=>e.find((t,n)=>{let r=e[n+1];return Mn(t,r)}),Ti=(e,t,n,r)=>{if(L(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=An(mt(e.node,t)),(o==null||!s.isExpression(o))&&(o=e.node));else{let a=L(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&&Mn(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=L(t,r),l=An(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}}},Ci=(e,t,n)=>{let r=$t(e,t);if(r!=null)return r;let i=Se(e,e.current_module,t);if(i==null)throw new Error("not implemented");let o=Ti(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=Tt(e,e.current_module,i,o.node);return Bn(l,a,!0)},Rn=(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}},Pn=(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}},Bn=(e,t,n=!1)=>(e=Un(e,t,n),e.run_state.status==v.reload_app_window?{...e,run_state:{...e.run_state,on_eval_modules_finished:$i}}:e.value_explorer!=null?e:{state:e,effects:{type:"set_status",args:["expression was not reached during program execution"]}}),$i=e=>{let t=e.selection_state;if(t==null||e.value_explorer!=null)return e;let n=Se(e,e.current_module,t.node.index),r=Tt(e,e.current_module,n,t.node);return Bn(e,r,!1)},Fi=(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},Di=(e,t,n=t)=>J({...e,entrypoint:t,current_module:n},!0),ji=(e,t)=>J({...e,html_file:t},!0),Li=(e,t)=>J({...e,use_ts:t},!0),Vn=(e,t)=>({state:Wn(H(e,t),t.index),effects:{type:"set_focus"}}),Ai=(e,t)=>{let n=e.parse_result.program.getSourceFile(rn(e.current_module)),r=L(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=Ae(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 Vn(e,a)}},Pi=(e,t)=>({state:H(e,t),effects:{type:"set_focus"}}),Wn=(e,t)=>(e=qe(e,t),e={...e,selection_state:null,value_explorer:null},$t(e,t)!=null?e:Jn(e,Ct(e),!0)),Ft=(e,t,n,r)=>{let i=r.call_id;if(i==null)throw new Error("illegal state");let o=A(e.calltree,a=>a.id==i);if(Et(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}}},Un=(e,t,n=!1)=>{if(t.selected_call_id==null){let l=A(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}:Pn(e,t.module,Y(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==we(e))d=D(e).id,l=e.footprints.get(d)==null;else{let{has_snapshot:c,node_snapshot:_}=Pn(e,t.module,t.function_node,t.selected_call_id);l=!c,d=_?.call_id}else o!=null&&(d=o.call_id,a=Ft(e,t.function_node,r,o));if(!l)return tr({...e,value_explorer:a},t.function_node,d)}if(!n)throw new Error("illegal state");return{...e,run_state:{status:v.reload_app_window,reload_counter:(e.run_state.reload_counter??0)+1,on_reload_app_window_finished:Je,breakpoint:t}}},Jn=(e,t,n)=>t.function_node.kind==s.SyntaxKind.SourceFile&&t.function_node!=we(e)?e:(e=Un(e,t,n),e.run_state.status==v.reload_app_window?{...e,run_state:{...e.run_state,on_eval_modules_finished:Hn}}:e),Hn=e=>e.selection_state!=null||e.value_explorer!=null?e:Jn(e,Ct(e),!0),Oi=(e,t,n,r)=>e.execution_id!=n||(e={...e,snapshots:new _e,footprints:new Map,collected_footprints_functions:new Set,calltree:Me(D(e),[...M(e)??[],t]),logs:{...e.logs,logs:e.logs.logs.concat(On(r,t))}},t.ok)?e:Xe(e,t).state,qn=e=>J({...e,io_trace:null,run_state:{...e.run_state,reload_counter:(e.run_state.reload_counter??0)+1}},!1),Xn=(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}},Yn=(e,t,n,r)=>{let i=Xn(e,t);return J({...r==null?i:Gn(i,r),has_file_system_access:n},!0)},Ni=(e,t,n)=>({...Yn(e,t,!0),current_module:n}),zi=e=>({...e,storage:new ke}),Ii=(e,t,n=0)=>{let r=e.project_dir==null?e:Xn(e,e.project_dir),i=Gn(r,t);return J({...i,execution_id:0,storage:new ke,cursor_position_by_file:{[i.current_module]:n}},!0)},He={get_initial_state:Ii,input:vi,open_app_window:zi,load_dir:Yn,create_file:Ni,step_into:Ki,change_current_module:Fi,change_entrypoint:Di,change_html_file:ji,change_use_ts:Li,goto_location:Vn,goto_definition:Ai,goto_problem:Pi,move_cursor:Wn,eval_selection:Ci,reload_app_window_finished:Si,external_imports_loaded:Nn,eval_modules_finished:zn,on_deferred_call:Oi,clear_io_trace:qn};var Z=e=>e.cursor_position_by_file[e.current_module]??0,qe=(e,t)=>({...e,cursor_position_by_file:{...e.cursor_position_by_file,[e.current_module]:t}});var H=(e,t)=>qe({...e,current_module:t.module},t.index),Mi=e=>e.error?.constructor==ce.constructor&&e.error?.message==ce.message,ee=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,Ri=e=>D(e).module,we=e=>e.parse_result.modules[Ri(e)],ue=e=>!e.toplevel&&!e.fn.is_hosted,Bi=(e,t)=>e?.[t.module]?.[t.index??-1],rr=(e,t,n)=>({...e,[t.module]:{...e?.[t.module],[t.index??-1]:n}}),Qn=(e,t,n)=>e.selected_calltree_node_by_loc?.[t]?.[e.parse_result.modules[t]==n?-1:n.index],Vi=(e,t,n)=>({...e,selected_calltree_node_by_loc:rr(e.selected_calltree_node_by_loc,t,n)}),pe=(e,t,n=e.current_calltree_node)=>({...e,active_calltree_node:t,current_calltree_node:n}),Dt=(e,t,n=t)=>{let r=N(t);if(Bi(e.colored_frames,r)!=t.id){e={...e,colored_frames:rr(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=Kt(t.code,t,l);let a=an(t.code,o);e.frames.set(t.id,o),e.frame_coloring.set(t.id,a)}}return pe(e,t,n)},Zn=(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];let[n,r]=Ht((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]},ir=(e,t)=>{let n=e.callsite_location;if(n==null)return null;n=JSON.parse(n);let r=Ie(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},nr=(e,t,n)=>{let{has_snapshot:r,node_snapshot:i}=Rn(e,N(e.current_calltree_node).module,t,n);if(r){let o;return i==null?o=null:o=Ft(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(f){if(i)throw new Error("illegal state");let m=c.code;return{...e,value_explorer:null,run_state:{status:v.reload_app_window,on_reload_app_window_finished:Je,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:f}}}}function l(f,m,g){if(g.current_calltree_node_id!=f.current_calltree_node.id)return f;let x=A(f.calltree,y=>y.id==t.id);return z(f,x,n,r,!0)}let[a]=ve(e.calltree,t);if(!t.toplevel&&!t.fn.is_hosted&&!a.toplevel&&!a.fn.is_hosted)return n({...pe(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:ue(t)?d=!1:ue(a)?d=!0:d=e.calltree_node_is_expanded[t.id];let c=d?t:a;e=pe(e,c,t);let _,h,p;if(t.toplevel){if(e.footprints.get(D(e).id)==null)return o();h=null,p=null,_=N(c)}else if(t.fn.__type=="loop_iteration"){let f=N(t).module,m=Z(e),g=!1;if(e.current_module==f&&Q(t.code,m)&&m!=t.code.index)_={module:f,index:m};else{let b=t.code,K=b.kind;if(K==s.SyntaxKind.WhileStatement||K==s.SyntaxKind.DoStatement||K==s.SyntaxKind.ForStatement){let ne=b.statement.kind==s.SyntaxKind.Block?b.statement.statements.length==0?K==s.SyntaxKind.ForStatement?b.initializer:b.expression:b.statement.statements[0]:b.statement;_={module:f,index:ne.index}}else _={module:f,index:b.initializer.index},g=!0}let x=e.selection_state?.node,y=x!=null&&!(x==t.code.expression&&(t.code.kind==s.SyntaxKind.ForOfStatement||t.code.kind==s.SyntaxKind.ForInStatement))&&x!=t.code.initializer&&Q(t.code,x.index),w;if((t.code.kind==s.SyntaxKind.ForOfStatement||t.code.kind==s.SyntaxKind.ForInStatement)&&(x==t.code.initializer||g)?(p={node:t.code.initializer},w=t.code):y?(p=e.selection_state,w=e.selection_state.node):(w=Ue(t.code,_.index),p=null),w==null)h=null,p=null;else{let b;if({value_explorer:h,should_replay:b}=nr(e,w,t.id),b)return o(w)}}else if(t.code!=null&&E(t.code)){let f=t.code.kind;if(f==s.SyntaxKind.WhileStatement||f==s.SyntaxKind.DoStatement)h=null,p=null;else{let m;f==s.SyntaxKind.ForStatement?m=t.code.initializer:m=t.code.expression,p={node:m};let g;if({value_explorer:h,should_replay:g}=nr(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 f;if(d){_=N(t),p=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?f=g.value:f=t.snapshot.args}else{let g=ir(t,c);if(g==null)return o();_={module:N(c).module,index:g.index},f=t.snapshot.args,p={node:g}}if(f==null)throw new Error("illegal state");let m=t.ok?{"*arguments*":f,"*return*":t.snapshot.value}:{"*arguments*":f,"*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({...Dt(Vi(e,N(c),e.active_calltree_node.id),c,t),value_explorer:h,selection_state:p})},Wi=e=>z(e,e.current_calltree_node,void 0,!0),ve=(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},te=e=>ue(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,Ui=e=>{let t=e.current_calltree_node,n;if(te(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,ve(e.calltree,t))}return n?.id=="deferred_calls"&&(n.children==null?n=null:n=n.children[0]),n==null?e:z(e,n)},Ji=e=>{let t=e.current_calltree_node;if(t.toplevel)return e;let[n]=ve(e.calltree,t),r=n.children.findIndex(a=>a==t),i=n.children[r-1],o=a=>!te(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)},Hi=e=>{let t=e.current_calltree_node,n=e.calltree_node_is_expanded[t.id];if(!te(t)||!n){let[r]=ve(e.calltree,t);return r.id=="calltree"||r.id=="deferred_calls"?e:z(e,r)}else return be(e)},qi=e=>{let t=e.current_calltree_node;return te(t)?e.calltree_node_is_expanded[t.id]?t.children!=null?z(e,t.children[0]):e:be(e):e},be=(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)},Xi=(e,t)=>{let n=A(e.calltree,r=>r.id==t);return z(e,n)},Gi=(e,t)=>{let n=A(e.calltree,r=>r.id==t);return te(n)?be(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(ve(e.calltree,t).map(n=>[n.id,!0])),[t.id]:!0}},Xe=(e,t)=>{if(t??=D(e),t.ok||Mi(t))return{state:X(e,t),node:t};{let n=A(t,r=>!q(r).ok&&(r.children==null||r.children.find(i=>!q(i).ok)==null));return{state:X(e,n),node:n}}},er=e=>Xe(e).state,Se=(e,t,n)=>{let r=e.parse_result.modules[t];if(r==null)return null;if(Q(r,n)){let i=L(r,n),o=s.forEachAncestor(i,l=>{let a=Ne(l);if(a!=null)return a;if(S(l)||E(l))return l});return o??r}else return r},tr=(e,t,n)=>{if(t==we(e)){let i=D(e);return Dt(X(e,i),i)}if(t.kind==s.SyntaxKind.SourceFile)return e;if(n==null)return pe(e,null);let r=A(e.calltree,i=>i.id==n);if(r==null)throw new Error("illegal state");return Dt(X(e,r),r)},Yi=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=Ie(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=Ie(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"}}},or=(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=j(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=ir(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}},Qi=e=>{let t=[e.current_calltree_node,e.active_calltree_node,D(e)].find(r=>ee(r));if(t==null)return{state:e,effects:[{type:"set_status",args:["no error found"]}]};let n=A(t,r=>ee(r)&&(r.children==null||r.children.every(i=>!ee(i)||ue(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"}}})},Zi=(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 sr(e,n)},sr=(e,t)=>{e={...e,logs:{...e.logs,log_position:t}};let n=A(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=or(r,!1);if(i.effects!=null)throw new Error("illegal state");return i.state})};He.calltree={arrow_down:Ui,arrow_up:Ji,arrow_left:Hi,arrow_right:qi,select_node:Xi,select_and_toggle_expanded:Gi,select_return_value:Yi,select_arguments:or,select_error:Qi,navigate_logs_position:sr,navigate_logs_increment:Zi,show_value_explorer:Wi};var Ye=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"&&k("calltree.select_arguments"),r.key=="e"&&k("calltree.select_error"),(r.key=="r"||r.key=="Enter")&&k("calltree.select_return_value"),(r.key=="ArrowDown"||r.key=="j")&&k("calltree.arrow_down"),(r.key=="ArrowUp"||r.key=="k")&&k("calltree.arrow_up"),(r.key=="ArrowLeft"||r.key=="h")&&k("calltree.arrow_left"),(r.key=="ArrowRight"||r.key=="l")&&k("calltree.arrow_right")})}on_click_node(t,n){t.target.classList.contains("expand_icon")?k("calltree.select_and_toggle_expanded",n):k("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=ze(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)},te(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 "+(ee(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,"(",...ie(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 Qe=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(),k("calltree.navigate_logs_increment",1)),(r.key=="ArrowUp"||r.key=="k")&&(r.preventDefault(),k("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;ik("calltree.navigate_logs_position",i)},u("a",{href:"javascript: void(0)"},l+": "+(o.toplevel?"toplevel":"fn "+(o.parent_name==""?"anonymous":o.parent_name))+":")," ",...ie(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 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=="F4"&&this.ui.editor.focus()})}clear(){this.el.innerHTML="",this.is_rendered=!1}render_io_trace(t,n){if(n&&(this.is_rendered=!1),this.is_rendered)return;this.is_rendered=!0,this.el.innerHTML="";let r=t.io_trace??[],i=t.rt_cxt.io_trace_index??r.length;for(let o=0;o$(d))),"): ",l.ok?$(l.value):$(l.error)))}}};var eo="leporello-js",lr=`https://firebasestorage.googleapis.com/v0/b/${eo}.appspot.com/o/`;async function to(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 no(e){let t=(await to(e)).slice(0,40),n=new Blob([e],{type:"text/plain"}),r=new FormData;r.append("file",n);let i=await fetch(lr+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 ro(e){let t=await fetch(lr+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 ar(){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 ro(t)}catch(r){return alert(r.message),null}}async function cr(e){let t=await no(e),n=new URL(window.location);n.searchParams.set("share_id",t),history.replaceState(null,null,n.href)}var et=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:` + `),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 cr(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 tt=class{constructor(t,n){this.open_app_window=this.open_app_window.bind(this),this.files=new De(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:()=>{k("change_use_ts",!1)}}),"JavaScript"),u("label",{for:"ts"},u("input",{id:"ts",type:"radio",name:"use_ts",checked:n.use_ts,change:()=>{k("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:"share_button",click:()=>this.share_dialog.showModal()},"Share"),this.help_dialog=this.render_help(),this.share_dialog=new et().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 Fe(this,this.editor_container),this.calltree=new Ye(this,this.debugger.calltree),this.logs=new Qe(this,this.debugger.logs),this.io_trace=new Ze(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,Re(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&&k("calltree.show_value_explorer")}clear_io_trace(){k("clear_io_trace")}open_app_window(){this.toggle_open_app_window_tooltip(!1),localStorage.onboarding_open_app_window=!0,Vt(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==v.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:()=>k("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 io=e=>new globalThis.app_window.Function("url",` + `},"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),oo=async e=>{let t=e.run_state.external_imports,n=await Promise.allSettled(t.map(i=>io(/^\w+:\/\//.test(i)?i:st+"/"+i))),r=Object.fromEntries(n.map((i,o)=>[t[o],{ok:i.status=="fulfilled",error:i.reason,module:i.value}]));k("external_imports_loaded",e,r)},nt=(e,t,n=t.current_module)=>{e.editor.ensure_session(n,t.files[n])},_r=(e,t)=>{e.editor.remove_markers_of_type(t,"evaluated_ok"),e.editor.remove_markers_of_type(t,"evaluated_error")},jt=e=>{e.editor.for_each_session((t,n)=>_r(e,t))},dr=(e,t)=>{let n=t.current_module;_r(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)})},ur=(e,t)=>{e.editor.clear_parse_result(),t.parse_result!=null&&(t.parse_result.ok?Object.keys(t.parse_result.modules).forEach(n=>{nt(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=>{nt(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)))},pr=(e,t,n)=>{nt(e,t),e.editor.switch_session(t.current_module),ur(e,t),n!=null&&n.with_app_window&&!localStorage.onboarding_open_app_window&&e.toggle_open_app_window_tooltip(!0)},fr=(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&&(nt(n,t),n.editor.unembed_value_explorer(),n.editor.switch_session(t.current_module)),Z(t)!=n.editor.get_cursor_position()&&r!="on_deferred_call"&&n.editor.set_cursor_position(Z(t)),(e.run_state?.status!=t.run_state.status||t.run_state.status==v.reload_app_window&&e.run_state.reload_counter!=t.run_state.reload_counter)&&(t.run_state.status==v.reload_app_window&&at(t),t.run_state.status==v.load_external_imports&&oo(t),t.run_state.status==v.eval_modules&&t.run_state.promise.then(i=>{k("eval_modules_finished",t.execution_id,i)}),n.loading_spinner.style.visibility=t.run_state.status==v.eval_modules_finished||t.run_state.status==v.reload_app_window_finished?"hidden":"initial"),e.parse_result!=t.parse_result&&ur(n,t),t.parse_result?.ok?e.calltree==null||e.execution_id!=t.execution_id?t.calltree==null?(n.calltree.clear_calltree(),jt(n),n.render_debugger_loading(t)):(n.render_debugger(t),jt(n),dr(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),(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&&dr(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")&&Re(t,n.is_focus_in_editor)):(n.calltree.clear_calltree(),jt(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))}},hr={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?zt(t,n):Yt(t,n)}};var rt=()=>({current_module:localStorage.current_module??"",entrypoint:localStorage.entrypoint??"",html_file:localStorage.html_file??""}),Zt=()=>{if(globalThis.showDirectoryPicker==null)throw new Error("Your browser is not supporting File System Access API");fe(!0).then(e=>{k("load_dir",e,!0,rt())})},en=async()=>{Nt(),k("load_dir",await dt,!1,rt())},Lt,V,P,mr=async(e,t)=>{Lt=t;let n={"":localStorage.code||Gt},r,i,o=await fe(!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=me.find(_=>_.path==d),l==null){let _=await ar();_==null?i=rt():(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=rt(),r={project_dir:o,files:n,has_file_system_access:!0};P=Lt.get_initial_state({...r,use_ts:localStorage.use_ts==null?!1:JSON.parse(localStorage.use_ts),on_deferred_call:(...a)=>k("on_deferred_call",...a)},i),globalThis.__state=P,V=new tt(e,P),globalThis.__ui=V,pr(V,P,l),Bt(P)},C=()=>P,k=(e,...t)=>{e=="input"||e=="write"?console.log("exec",e):console.log("exec",e,...t);let n=e.split(".").reduce((l,a)=>l?.[a],Lt);if(n==null)throw new Error("command "+e+" + not found");let r=n(P,...t);console.log("nextstate",r);let i,o;if(r.state!=null?{state:i,effects:o}=r:(i=r,o=null),P?.current_module==null)throw console.error("command did not return state, returned",r),new Error("illegal state");fr(P,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??[]),hr[l.type](i,l.args,V,P)}),globalThis.__prev_state=P,globalThis.__state=i,P=i};mr(globalThis.document.getElementById("app"),He); + `)(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); diff --git a/src/ts_libs.js b/src/ts_libs.js new file mode 100644 index 0000000..26e0f77 --- /dev/null +++ b/src/ts_libs.js @@ -0,0 +1,114 @@ +const lib_names = [ + 'lib.d.ts', + 'lib.decorators.d.ts', + 'lib.decorators.legacy.d.ts', + 'lib.dom.asynciterable.d.ts', + 'lib.dom.d.ts', + 'lib.dom.iterable.d.ts', + 'lib.es2015.collection.d.ts', + 'lib.es2015.core.d.ts', + 'lib.es2015.d.ts', + 'lib.es2015.generator.d.ts', + 'lib.es2015.iterable.d.ts', + 'lib.es2015.promise.d.ts', + 'lib.es2015.proxy.d.ts', + 'lib.es2015.reflect.d.ts', + 'lib.es2015.symbol.d.ts', + 'lib.es2015.symbol.wellknown.d.ts', + 'lib.es2016.array.include.d.ts', + 'lib.es2016.d.ts', + 'lib.es2016.full.d.ts', + 'lib.es2016.intl.d.ts', + 'lib.es2017.arraybuffer.d.ts', + 'lib.es2017.d.ts', + 'lib.es2017.date.d.ts', + 'lib.es2017.full.d.ts', + 'lib.es2017.intl.d.ts', + 'lib.es2017.object.d.ts', + 'lib.es2017.sharedmemory.d.ts', + 'lib.es2017.string.d.ts', + 'lib.es2017.typedarrays.d.ts', + 'lib.es2018.asyncgenerator.d.ts', + 'lib.es2018.asynciterable.d.ts', + 'lib.es2018.d.ts', + 'lib.es2018.full.d.ts', + 'lib.es2018.intl.d.ts', + 'lib.es2018.promise.d.ts', + 'lib.es2018.regexp.d.ts', + 'lib.es2019.array.d.ts', + 'lib.es2019.d.ts', + 'lib.es2019.full.d.ts', + 'lib.es2019.intl.d.ts', + 'lib.es2019.object.d.ts', + 'lib.es2019.string.d.ts', + 'lib.es2019.symbol.d.ts', + 'lib.es2020.bigint.d.ts', + 'lib.es2020.d.ts', + 'lib.es2020.date.d.ts', + 'lib.es2020.full.d.ts', + 'lib.es2020.intl.d.ts', + 'lib.es2020.number.d.ts', + 'lib.es2020.promise.d.ts', + 'lib.es2020.sharedmemory.d.ts', + 'lib.es2020.string.d.ts', + 'lib.es2020.symbol.wellknown.d.ts', + 'lib.es2021.d.ts', + 'lib.es2021.full.d.ts', + 'lib.es2021.intl.d.ts', + 'lib.es2021.promise.d.ts', + 'lib.es2021.string.d.ts', + 'lib.es2021.weakref.d.ts', + 'lib.es2022.array.d.ts', + 'lib.es2022.d.ts', + 'lib.es2022.error.d.ts', + 'lib.es2022.full.d.ts', + 'lib.es2022.intl.d.ts', + 'lib.es2022.object.d.ts', + 'lib.es2022.regexp.d.ts', + 'lib.es2022.string.d.ts', + 'lib.es2023.array.d.ts', + 'lib.es2023.collection.d.ts', + 'lib.es2023.d.ts', + 'lib.es2023.full.d.ts', + 'lib.es2023.intl.d.ts', + 'lib.es2024.arraybuffer.d.ts', + 'lib.es2024.collection.d.ts', + 'lib.es2024.d.ts', + 'lib.es2024.full.d.ts', + 'lib.es2024.object.d.ts', + 'lib.es2024.promise.d.ts', + 'lib.es2024.regexp.d.ts', + 'lib.es2024.sharedmemory.d.ts', + 'lib.es2024.string.d.ts', + 'lib.es5.d.ts', + 'lib.es6.d.ts', + 'lib.esnext.array.d.ts', + 'lib.esnext.collection.d.ts', + 'lib.esnext.d.ts', + 'lib.esnext.decorators.d.ts', + 'lib.esnext.disposable.d.ts', + 'lib.esnext.full.d.ts', + 'lib.esnext.intl.d.ts', + 'lib.esnext.iterator.d.ts', +] + +export let ts_libs_promise = load_ts_libs() + +async function load_ts_libs() { + if(globalThis.process == null) { + return Object.fromEntries(await Promise.all( + lib_names.map(name => + fetch('typescript/' + name).then(r => r.text()).then(text => ([name, text])) + ) + )) + } else { + const fs = await import('fs') + return Object.fromEntries( + lib_names.map(name => + [name, fs.readFileSync('typescript/' + name, 'ascii')] + ) + ) + } +} + + diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..024d55a --- /dev/null +++ b/styles.css @@ -0,0 +1,548 @@ +:root { + --shadow_color: rgb(171 200 214); + --active_color: rgb(173, 228, 253); + --error-color: #ff000024; + --warn-color: #fff6d5; +} + +html, body, .app { + height: 100%; + background-color: #f4f4f4; +} + +body { + margin: 0px; +} + +.spinner { + display: inline-block; + height: 0.8em; + width: 0.8em; + min-width: 0.8em; + border-radius: 50%; + border-top: none !important; + border: 2px solid; + animation: rotate 0.6s linear infinite; +} +@keyframes rotate { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} + +.app { + /* same as ace editor */ + font-family: Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospace; +} + +.app::backdrop { + background-color: white; +} + +.root { + height: 100%; + display: grid; + grid-template-areas: + "code" + "bottom" + "statusbar"; + grid-template-rows: auto 1fr 2.5em; +} + +.editor_container, .bottom, .statusbar { + box-shadow: 1px 1px 3px 0px var(--shadow_color); + background-color: white; +} + +.editor_container, .bottom, .statusbar { + margin: 8px; +} + +.editor_container:focus-within, +.bottom:focus-within, +dialog { + outline: none; + box-shadow: 1px 1px 6px 3px var(--shadow_color); +} + +.tab_content:focus-within, .problems_container:focus-within { + outline: none; +} + +.editor_container { + height: 55vh; + resize: vertical; + position: relative; + grid-area: code; + font-size: 16px; +} + +/* ace markers */ + +.selection { + position: absolute; + background-color: #ff00ff; + z-index: 1; /* make it on top of evaluated_ok and evaluated_error */ +} + +.evaluated_ok { + position: absolute; + background-color: rgb(225, 244, 253); +} +.evaluated_error { + position: absolute; + background-color: var(--error-color); +} +.error-code { + /* + TODO: make underline like in all editors + */ + position: absolute; + border-bottom: 4px solid red; +} + +/* end of ace markers */ + +.eval_error { + padding: 0em 1em; + color: red; +} + +/* Tabs */ + +.tabs { + font-family: system-ui; + display: flex; + padding-bottom: 0.5em; +} + +.tabs > .tab { + margin-right: 1em; + padding: 0.3em 1em; + display: flex; + align-items: center; +} + +.tabs > .tab.active { + background-color: rgb(225, 244, 253); +} + +/* debugger */ + +.bottom { + grid-area: bottom; + overflow: auto; + display: grid; +} + +.debugger { + display: flex; + flex-direction: column; +} + +.debugger_wrapper { + display: flex; + flex: 1; + flex-direction: column; + overflow: auto; +} + +.debugger, .problems_container { + padding: 5px; + overflow: auto; +} + +.logs, .io_trace { + padding-left: 1em; +} + +.logs .log { + cursor: pointer; +} + +.logs .log.active { + background-color: var(--active_color) !important; +} + +.logs .log.error { + background-color: var(--error-color); + color: black !important; /* override red color that is set for calltree */ + &.native { + color: grey !important; + } +} + +.logs .log.warn { + background-color: var(--warn-color); +} + +.tab_content { + flex: 1; + overflow: auto; +} + +.callnode { + /* This makes every callnode be the size of the the longest one, so + * every callnode is clickable anywhere in the calltree view, and + * background for active callnodes is as wide as the entire container. + * Useful when scrolling very wide call trees */ + min-width: fit-content; + margin-left: 1em; +} +.callnode .active { + background-color: var(--active_color); +} +.call_el { + /* + Make active callnode background start from the left of the calltree + view + */ + margin-left: -1000vw; + padding-left: 1000vw; + width: 100%; + + cursor: pointer; + display: inline-block; +} +.call_el .expand_icon, .call_el .expand_icon_placeholder { + padding-left: 5px; + padding-right: 2px; +} + +.call_header { + white-space: nowrap; +} +.call_header.error { + color: red; +} +.call_header.error.native { + color: red; +} +.call_header.native { + font-style: italic; + color: grey; +} + +.call_header .loop_step { + color: grey; + font-size: 0.9em; + margin-right: 0.3em; +} + +/* io trace */ +.io_trace .event { + border-radius: 1em; + line-height: 2em; + padding: 0.1em 0.5em; + background-color: var(--active_color); +} + +/* problems view */ +.problem a { + color: red; +} + +/* files */ + +.files_container { + overflow: auto; + display: flex; + flex-direction: column; +} + +.allow_file_access { + display: flex; + flex-direction: column; +} +.allow_file_access .subtitle { + font-size: 0.8em; +} + +.files { + overflow: auto; + padding: 5px; +} + +.files .file { + margin-left: 1em; +} + +.files > .file { + margin-left: 0em !important; +} + +.files .file_title { + display: flex; + margin-left: -100vw; + padding-left: 100vw; +} + +.files .file_title.active { + background-color: var(--active_color); +} + +.files .file_title .select_entrypoint { + margin-left: auto; + width: 3em; + margin-right: 0.7em; + text-align: center; +} + +.files .file_title .icon { + display: inline-block; + margin-right: 5px; + width: 1em; +} + +.file_actions { + font-family: system-ui; + display: flex; + flex-direction: row; + justify-content: flex-start; + align-items: center; + padding: 1em; + background-color: rgb(225 244 253 / 80%); +} + +.file_actions .file_action { + margin-right: 2em; +} + +.file_actions .select_entrypoint_title { + width: 3em; + text-align: center; +} + +/* value_explorer */ + +.embed_value_explorer_container.is_not_dom_el { + height: 0px; +} + +.embed_value_explorer_container.is_dom_el { + padding: 1em; +} + +.embed_value_explorer_wrapper { + /* preserve wrapper from getting clicks for code line left to it */ + pointer-events: none; +} + +.embed_value_explorer_container.is_not_dom_el .embed_value_explorer_wrapper { + margin-left: 1em; +} + +.embed_value_explorer_content { + pointer-events: initial; + white-space: pre; + max-width: fit-content; + background-color: white; + box-shadow: 1px 2px 9px -1px var(--shadow_color); +} + +.embed_value_explorer_content:focus { + outline: none; + box-shadow: 1px 2px 11px 1px var(--shadow_color); +} + +.embed_value_explorer_content > .value_explorer_node { + margin-left: 0 !important; +} + +.embed_value_explorer_control { + display: block; + margin-bottom: 1em; + font-size: 0.9em; +} + +.value_explorer_node { + margin-left: 1em; +} + +.value_explorer_header { + display: inline-block; + padding-right: 1em; + cursor: pointer; +} + +.value_explorer_header .expand_icon { + padding: 5px; +} + +.value_explorer_header.active { + background-color: rgb(148, 227, 191); +} + +.value_explorer_key { + color: rgb(150, 0, 128); + font-weight: bold; +} + +/* status */ + +.statusbar { + font-family: system-ui; + margin-bottom: 0px; + grid-area: statusbar; + display: flex; + flex-direction: row; + align-items: center; + justify-content: flex-start; +} + +.statusbar .spinner { + margin-right: 0.5em; +} + +.status, .current_file { + font-size: 1.5em; +} +.status { + color: red; +} + +.statusbar_action { + margin-right: 2em; +} + +.statusbar_action.first { + margin-left: auto; +} + +.open_app_window_button { + position: relative; +} +.open_app_window_tooltip { + padding: 1em; + position: absolute; + margin-bottom: 20px; + bottom: 100%; + border: none; + font-size: 1.7em; + background-color: rgb(120 206 247); + border-radius: 21px; + transform: scale(0); + transition: transform 0.3s; +} +.open_app_window_tooltip.on { + transform: scale(1); +} +.open_app_window_tooltip:after { + content: ''; + width: 0; + height: 0; + border-left: 20px solid transparent; + border-right: 20px solid transparent; + border-top: 20px solid rgb(120 206 247); + position: absolute; + bottom: -20px; + left: 50%; + transform: translate(-50%); +} + +.options { + padding: 5px; +} +.options > * { + margin: 5px; +} + +.show_help, .github { + margin: 0em 0.5em; +} + +.statusbar_button, .upload_button { + border: none; + color: white; + background: rgb(23 166 236); +} + +.statusbar_button { + font-size: 1.2em; + margin-left: 1em; + &:last-of-type { + margin: 0em 0.5em; + } +} + +.statusbar_button[disabled] { + background: grey; +} + +.share_dialog input, .share_dialog button { + font-size: 1.2em; +} + +.share_dialog button { + padding: 5px; + height: 2em; +} + +dialog { + border: none; +} + +dialog::backdrop { + background-color: rgb(225 244 253 / 80%); +} + +.help_dialog[open] { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + padding: 0; + min-width: 70%; + min-height: 70%; + background-color: white; +} + +.help { + padding: 2em; + border-spacing: 5px; +} + +.help th { + padding: 0.5em; +} + +.help th.key { + width: 5em; +} + +.help td.key { + background-color: rgb(225, 244, 253, 0.5); + border-radius: 10px; + text-align: center; +} + +.help_dialog form { + margin-bottom: 1em; +} + +.panel:not([open]) { + display: none; +} + +.panel[open] { + padding: 0px; + margin: 0px 0px 0px auto; + height: 100%; + max-height: 100%; + animation: slide-in 0.2s ease-in forwards; + &::backdrop { + background-color: rgb(225 244 253 / 60%); + } +} + +@keyframes slide-in{ + 0% { + transform: translateX(100%); + } + 100% { + transform: translateX(0); + } +}