diff --git a/040eac22c498dfa1649f.js b/040eac22c498dfa1649f.js
deleted file mode 100644
index 5e37681..0000000
--- a/040eac22c498dfa1649f.js
+++ /dev/null
@@ -1,768 +0,0 @@
-// input range 스타일 적용을 위한 코드
-const sliders = document.querySelectorAll('.slider');
-const rangeValueText = document.querySelectorAll('.slider + strong');
-
-const setSliderTrack = (element) => {
- const value = element.value;
- const max = parseInt(element.max);
- const min = parseInt(element.min);
- const width = ((value - min) / (max - min)) * 100;
- const color = getComputedStyle(element).color;
-
- element.style.background = `linear-gradient(to right, ${color} 0%, ${color} ${width}%, #d9dbe0 ${width}%, #d9dbe0 100%)`;
-};
-
-const sliderValueObserver = new MutationObserver((mutationsList) => {
- mutationsList.forEach((mutation) => {
- if (mutation.type === 'childList') {
- const slider = mutation.target.previousElementSibling;
- setSliderTrack(slider);
- }
- });
-});
-
-sliders.forEach((slider) => {
- setSliderTrack(slider);
-});
-
-rangeValueText.forEach((target) => {
- sliderValueObserver.observe(target, {
- childList: true,
- characterData: true,
- });
-});
-
-// 다크모드
-const userColorTheme = localStorage.getItem('color-theme');
-const osColorTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
- ? 'dark'
- : 'light';
-const darkModeButton = document.querySelector('.btn-dark-mode');
-
-const getUserTheme = () => (userColorTheme ? userColorTheme : osColorTheme);
-
-window.addEventListener('load', () => {
- if (getUserTheme() === 'dark') {
- localStorage.setItem('color-theme', 'dark');
- document.documentElement.setAttribute('color-theme', 'dark');
- darkModeButton.classList.add('active');
- darkModeButton.setAttribute('name', '다크모드 OFF');
- } else {
- localStorage.setItem('color-theme', 'light');
- document.documentElement.setAttribute('color-theme', 'light');
- darkModeButton.classList.remove('active');
- darkModeButton.setAttribute('name', '다크모드 ON');
- }
-});
-
-darkModeButton.addEventListener('click', () => {
- if (darkModeButton.classList.contains('active')) {
- localStorage.setItem('color-theme', 'light');
- document.documentElement.setAttribute('color-theme', 'light');
- darkModeButton.classList.remove('active');
- darkModeButton.setAttribute('name', '다크모드 ON');
- } else {
- localStorage.setItem('color-theme', 'dark');
- document.documentElement.setAttribute('color-theme', 'dark');
- darkModeButton.classList.add('active');
- darkModeButton.setAttribute('name', '다크모드 OFF');
- }
-});
-
-// 스토리 section / 스토리 컨텐츠 여닫기
-const storyShowButton = document.querySelector('.btn-story');
-const storyCloseButton = document.querySelector('.btn-close-story');
-const storySection = document.querySelector('.story');
-const storyList = document.querySelector('.story-list');
-const storyResizer = document.querySelector('.story-resizer');
-
-// 월드 편집 기능
-const wallEditButton = document.querySelector('.btn-wall');
-const assetsSelectButton = document.querySelector('.btn-assets');
-const mapResizeButton = document.querySelector('.btn-resize');
-const mobSelectButton = document.querySelector('.btn-mob');
-const uploadWorldDataButton = document.getElementById('btn-upload-worlddata');
-const worldDataInput = document.getElementById('worldFileInput');
-
-storyShowButton.addEventListener('click', () => {
- storyShowButton.classList.toggle('active');
- storySection.classList.toggle('show');
- storyResizer.style.display = 'block';
-
- const mapContainer = document.querySelector('.map-container');
-
- if (storyShowButton.classList.contains('active')) {
- // TODO: 모달이나 토스트로 변경
- alert('스토리 모드에서는 월드 편집 기능이 제한됩니다.');
-
- wallEditButton.classList.remove('active');
- wallEditButton.setAttribute('disabled', true);
-
- assetsSelectButton.classList.remove('active');
- assetsSelectButton.setAttribute('disabled', true);
-
- mobSelectButton.classList.remove('active');
- mobSelectButton.setAttribute('disabled', true);
-
- mapResizeButton.classList.remove('active');
- mapResizeButton.setAttribute('disabled', true);
-
- uploadWorldDataButton.classList.add('hidden');
- worldDataInput.setAttribute('disabled', true);
- } else {
- wallEditButton.removeAttribute('disabled');
- assetsSelectButton.removeAttribute('disabled');
- mobSelectButton.removeAttribute('disabled');
- mapResizeButton.removeAttribute('disabled');
- uploadWorldDataButton.classList.remove('hidden');
- worldDataInput.removeAttribute('disabled');
- }
-});
-
-storyCloseButton.addEventListener('click', () => {
- const mapContainer = document.querySelector('.map-container');
- mapContainer.style.pointerEvents = '';
-
- wallEditButton.removeAttribute('disabled');
- assetsSelectButton.removeAttribute('disabled');
- mobSelectButton.removeAttribute('disabled');
- mapResizeButton.removeAttribute('disabled');
- uploadWorldDataButton.classList.remove('hidden');
- worldDataInput.removeAttribute('disabled');
-
- storyShowButton.classList.remove('active');
- storySection.classList.remove('show');
- storyResizer.style.display = 'none';
-});
-
-// 툴팁 표시
-const tooltipTargetElement = document.querySelectorAll('.show-tooltip');
-
-const createTooltip = (textContent) => {
- const div = document.createElement('div');
- div.setAttribute('class', 'tooltip');
- div.innerHTML = textContent;
-
- return div;
-};
-
-const addTooltip = (target) => {
- const textContent = target.getAttribute('name');
-
- if (textContent) {
- const targetHeight = target.clientHeight;
- const tooltip = createTooltip(textContent);
- tooltip.style.top = `${targetHeight + 10}px`;
-
- target.append(tooltip);
- }
-};
-
-const removeTooltip = (target) => {
- const tooltip = target.querySelector('.tooltip');
-
- tooltip && tooltip.remove();
-};
-
-const addTooltipEvent = (target) => {
- target.addEventListener(
- 'mouseover',
- () => {
- addTooltip(target);
- },
- false,
- );
-
- target.addEventListener(
- 'mouseout',
- () => {
- removeTooltip(target);
- },
- false,
- );
-
- target.addEventListener('click', () => {
- removeTooltip(target);
- });
-};
-
-tooltipTargetElement.forEach((target) => {
- addTooltipEvent(target);
-});
-
-// world 메뉴 - 버튼 이벤트 추가(모달 여닫기)
-const worldMenu = document.querySelector('.world-menu');
-
-const toggleActive = (target) => {
- const currentActiveItem = worldMenu.querySelector('.active');
-
- if (target.classList.contains('btn-toggle')) {
- if (target == currentActiveItem) {
- target.classList.remove('active');
- } else {
- currentActiveItem && currentActiveItem.classList.remove('active');
- target.classList.add('active');
- }
- } else {
- currentActiveItem && currentActiveItem.classList.remove('active');
- }
-};
-
-worldMenu.addEventListener('click', (e) => {
- if (e.target.tagName == 'BUTTON') {
- toggleActive(e.target);
- }
-});
-
-window.addEventListener('click', (e) => {
- if (e.target == worldMenu || !worldMenu.contains(e.target)) {
- toggleActive(e.target);
- }
-});
-
-// worldmenu - 모달 크기 조절
-const world = document.querySelector('.world');
-const modals = document.querySelectorAll('.controller-modal');
-
-const resizeModal = (target, ratio) => {
- const targetWidth = target.clientWidth;
- const resizedWidth = targetWidth * ratio;
-
- target.style.maxWidth = `${resizedWidth}px`;
-};
-
-const resizeIfHidden = (targetModal) => {
- const modalRect = targetModal.getBoundingClientRect();
- const containerRect = world.getBoundingClientRect();
-
- const isPartiallyHiddenOrFullyHidden =
- modalRect.right >= containerRect.right;
-
- if (isPartiallyHiddenOrFullyHidden) {
- const term = modalRect.right - containerRect.right;
- const visibleRatio = 1 - term / modalRect.width;
- resizeModal(targetModal, visibleRatio);
- } else {
- targetModal.style.maxWidth = '700px';
- }
-};
-
-const resizeObserver = new ResizeObserver(() => {
- const activeButton = world.querySelector('.active');
- if (activeButton) {
- const targetModal = activeButton
- .closest('li')
- .querySelector('.controller-modal');
-
- resizeIfHidden(targetModal);
- }
-});
-
-const observerCallback = (entries, observer) => {
- entries.forEach((entry) => {
- if (entry.isIntersecting) {
- const intersectionRatio = entry.intersectionRatio;
- if (intersectionRatio < 1) {
- resizeModal(entry.target, intersectionRatio);
- }
- } else {
- entry.target.style.maxWidth = '700px';
- }
- });
-};
-
-const modalIntersectionObserver = new IntersectionObserver(observerCallback, {
- root: null,
- rootMargin: '0px',
- threshold: 0.1,
-});
-
-modals.forEach((modal) => {
- modalIntersectionObserver.observe(modal);
-});
-
-resizeObserver.observe(world);
-resizeObserver.observe(window.document.body);
-
-const addCodeNextCellFromSelectCell = (target) => {
- const selectCell = target.target.parentNode;
- const nextCell = selectCell.nextElementSibling;
- const newCell = document.createElement('py-repl');
- newCell.innerHTML = ``;
- selectCell.parentNode.insertBefore(newCell, nextCell);
-};
-
-const downloadCode = (target) => {
- const pyRepl = target.target.closest('py-repl');
- const code = pyRepl.querySelector('.cm-content').innerText;
- const blob = new Blob([code], { type: 'text/plain' });
- const link = document.createElement('a');
- link.href = URL.createObjectURL(blob);
- link.download = `code_${dateFormat()}.py`;
- link.click();
-};
-const uploadCode = (target) => {
- const pyRepl = target.target.closest('py-repl');
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = '.py';
- input.onchange = (e) => {
- const file = e.target.files[0];
- const reader = new FileReader();
- reader.onload = (e) => {
- pyRepl.querySelector('.cm-content').innerText = e.target.result;
- };
- reader.readAsText(file);
- };
- input.click();
-};
-const deleteCode = (target) => {
- const pyRepl = target.target.closest('py-repl');
- const nextpyReplBtnWrapFromPyRepl = pyRepl.nextElementSibling;
- nextpyReplBtnWrapFromPyRepl.remove();
- pyRepl.remove();
-};
-
-// 함수, 변수 리스트 클립보드에 복사
-const functionList = document.querySelector('.function-list');
-const variableList = document.querySelector('.variable-list');
-
-const copyToClipboard = (target) => {
- if (target.tagName == 'BUTTON' && target.classList.contains('code-item')) {
- const code = target.innerText;
- navigator.clipboard.writeText(code).then(() => {
- alert('클립보드에 복사되었습니다.');
- });
- }
-};
-
-functionList.addEventListener('click', (e) => {
- copyToClipboard(e.target);
-});
-
-variableList.addEventListener('click', (e) => {
- copyToClipboard(e.target);
-});
-
-// 케밥 메뉴 - 버튼 이벤트 추가
-const kebabMenu = document.querySelector('.btn-kebab');
-
-kebabMenu.addEventListener('click', () => {
- kebabMenu.classList.toggle('active');
-});
-
-window.addEventListener('click', (e) => {
- if (!kebabMenu.contains(e.target)) {
- kebabMenu.classList.contains('active') &&
- kebabMenu.classList.remove('active');
- }
-});
-
-// 이미지 프리로드
-const preloadImage = (imgList) => {
- imgList.forEach((src) => {
- const img = new Image();
- img.src = src;
- });
-};
-// 라이캣 이미지 프리로드
-preloadImage([
- './assets/img/characters/licat-0.webp',
- './assets/img/characters/licat-1.webp',
- './assets/img/characters/licat-2.webp',
- './assets/img/characters/licat-3.webp',
- './assets/img/icon/icon-alert-circle.svg',
-]);
-
-// 상태바(체력,마나)
-// 로컬 스토리지에서 값 가져오기
-const statusModeButton = document.querySelector('.btn-status');
-const srText = statusModeButton.querySelector('.sr-only');
-const getStatusMode = () => {
- const statusVisible = localStorage.getItem('status-mode');
- return statusVisible ? statusVisible : 'hide';
-};
-const setStatusVisiblity = () => {
- const status = getStatusMode();
- const statusContainers = document.querySelectorAll('.status-item');
- if (status === 'show') {
- statusContainers.forEach((container) => {
- container.classList.remove('hide');
- });
- } else {
- statusContainers.forEach((container) => {
- container.classList.add('hide');
- });
- }
-};
-
-window.addEventListener('DOMContentLoaded', () => {
- if (getStatusMode() === 'show') {
- localStorage.setItem('status-mode', 'show');
- statusModeButton.classList.remove('hide');
- statusModeButton.setAttribute('name', '체력 상태 숨기기');
- srText.innerText = '체력 상태 숨기기';
- } else {
- localStorage.setItem('status-mode', 'hide');
- statusModeButton.classList.add('hide');
- statusModeButton.setAttribute('name', '체력 상태 보기');
- srText.innerText = '체력 상태 보기';
- }
- setStatusVisiblity();
-});
-
-statusModeButton.addEventListener('click', () => {
- if (getStatusMode() === 'show') {
- localStorage.setItem('status-mode', 'hide');
- statusModeButton.classList.add('hide');
- statusModeButton.setAttribute('name', '체력 상태 보기');
- srText.innerText = '체력 상태 보기';
- } else {
- localStorage.setItem('status-mode', 'show');
- statusModeButton.classList.remove('hide');
- statusModeButton.setAttribute('name', '체력 상태 숨기기');
- srText.innerText = '체력 상태 숨기기';
- }
- setStatusVisiblity();
-});
-
-const APP = document.getElementById('app');
-const statusObserver = new MutationObserver((mutationsList) => {
- mutationsList.forEach((mutation) => {
- if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
- mutation.addedNodes.forEach((addedNode) => {
- if (
- addedNode.classList?.contains('map-container') ||
- addedNode.classList?.contains('character') ||
- addedNode.classList?.contains('mob')
- ) {
- const statusContainer =
- addedNode.querySelectorAll('.status-item');
- if (getStatusMode() === 'hide') {
- statusContainer.forEach((container) => {
- container.classList.add('hide');
- });
- }
- }
- });
- }
- });
-});
-
-statusObserver.observe(APP, { childList: true, subtree: true });
-
-// 프로필 모달
-const profileModal = document.querySelector('.profile-modal');
-const btnProfileOpen = document.querySelector('.btn-profile');
-const btnProfileClose = profileModal.querySelector('.btn-close');
-window.addEventListener('click', (e) => {
- if (btnProfileOpen.contains(e.target)) {
- btnProfileOpen.classList.toggle('active');
- } else if (e.target == btnProfileClose) {
- btnProfileOpen.classList.remove('active');
- } else if (!profileModal.contains(e.target)) {
- btnProfileOpen.classList.remove('active');
- }
-});
-
-const profileImages = document.querySelectorAll('.profile-img');
-const profileName = profileModal.querySelector('.txt-name');
-const inpProfileName = profileModal.querySelector('.inp-name');
-const initProfile = () => {
- const profile = JSON.parse(localStorage.getItem('profile'));
- if (profile) {
- profileImages.forEach((profileImage) => {
- profileImage.src = profile?.img.replace(window.location.origin, '');
- });
- profileName.innerHTML =
- profile?.name || '프로필 편집을 눌러
이름을 입력하세요';
- inpProfileName.value = profile?.name;
- }
-};
-initProfile();
-
-// 변경 설정
-const profileImage = document.querySelector('.profileimg-wrap .profile-img');
-const changeProfileImg = (e) => {
- const file = e.target.files[0];
- const reader = new FileReader();
- reader.onload = (evt) => {
- profileImage.src = evt.target.result;
- };
- reader.readAsDataURL(file);
-};
-const inpProfileImg = profileModal.querySelector('.inp-profile');
-inpProfileImg.addEventListener('change', (e) => changeProfileImg(e));
-const changeProfile = (e) => {
- localStorage.setItem(
- 'profile',
- JSON.stringify({
- img: profileImage.src,
- name: inpProfileName.value,
- }),
- );
- profileName.innerHTML =
- inpProfileName.value || '프로필 편집을 눌러
이름을 입력하세요';
- const profileMenuImg = document.querySelector('button .profile-img');
- profileMenuImg.src = profileImage.src;
-};
-
-const profileImageWrap = profileModal.querySelector('.profileimg-wrap');
-const profileView = profileModal.querySelector('.profile-view');
-const profileEdit = profileModal.querySelector('.profile-edit');
-const changeProfileMode = (mode) => {
- if (mode === 'edit') {
- profileImageWrap.classList.add('active');
- profileView.classList.remove('active');
- profileEdit.classList.add('active');
- } else if (mode === 'view') {
- profileImageWrap.classList.remove('active');
- profileView.classList.add('active');
- profileEdit.classList.remove('active');
- }
-};
-
-const btnProfileEdit = profileModal.querySelector('.btn-edit');
-const btnProfileSave = profileModal.querySelector('.btn-confirm');
-const btnProfileCancel = profileModal.querySelector('.btn-cancel');
-btnProfileEdit.addEventListener('click', () => {
- changeProfileMode('edit');
- initProfile();
-});
-btnProfileSave.addEventListener('click', () => {
- changeProfileMode('view');
- changeProfile();
-});
-btnProfileCancel.addEventListener('click', () => {
- changeProfileMode('view');
- initProfile();
-});
-
-/* 인증서 모달 */
-const certifBtn = document.querySelector('.btn-certif');
-const certifWrap = document.querySelector('.certif-wrap');
-const certifClose = certifWrap.querySelector('.btn-close');
-window.addEventListener('click', (e) => {
- if (certifBtn.contains(e.target)) {
- certifBtn.classList.toggle('active');
- } else if (e.target == certifClose) {
- certifBtn.classList.remove('active');
- } else if (!certifWrap.contains(e.target)) {
- certifBtn.classList.remove('active');
- }
- if (certifBtn.classList.contains('active')) {
- updateCertifItem();
- }
-});
-
-/* 인증서 초기화 */
-const certifList = certifWrap.querySelector('.certif-list');
-const storyChapter = {
- 입문: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
- 기초: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
-};
-const setCertifItem = () => {
- Object.keys(storyChapter).forEach((chapter) => {
- const li = document.createElement('li');
- li.classList.add('certif-item');
-
- li.innerHTML = `
-
${chapter}
- 0/${storyChapter[chapter].length}
-
-
- `;
- li.querySelector('.btn-download-certif').addEventListener(
- 'click',
- () => {
- createCertifImg(chapter);
- },
- );
- certifList.append(li);
- });
-};
-
-const createCertifImg = (chapter) => {
- const img = new Image();
- img.src = `./assets/img/certif-${chapter}.jpg`;
- img.onload = () => {
- const canvas = document.createElement('canvas');
- const ctx = canvas.getContext('2d');
- canvas.width = img.width;
- canvas.height = img.height;
- ctx.drawImage(img, 0, 0);
-
- // 이름이 비어있는 경우 하이픈 표시
- const localData = localStorage.getItem('profile');
- const name = JSON.parse(localData)?.name || '-';
-
- ctx.font = '400 74px pretendard';
- ctx.fillStyle = '#3a72ff';
- ctx.textAlign = 'center';
- ctx.fillText(name, canvas.width / 2, 570);
-
- const current = new Date();
- const currentTime = `${current.getFullYear()}.${(current.getMonth() + 1)
- .toString()
- .padStart(2, '0')}.${current
- .getDate()
- .toString()
- .padStart(2, '0')}`;
-
- //로컬스토리지의 값을 가져오지 못하는 경우 현재 시간으로 대체
- const date =
- localStorage.getItem(`${chapter}_certif_time`) || currentTime;
-
- ctx.font = '400 36px pretendard';
- ctx.fillStyle = 'black';
- ctx.fillText(date, 1340, 1000);
-
- const certif = canvas.toDataURL('image/png');
- const a = document.createElement('a');
- a.href = certif;
- a.download = `${chapter}_인증서.png`;
- a.click();
- };
-};
-
-const updateCertifItem = () => {
- const certifItems = certifList.querySelectorAll('.certif-item');
- Object.entries(storyChapter).forEach(([key, value], index) => {
- const li = certifItems[index];
- const solved = value.reduce((acc, cur) => {
- const check = localStorage.getItem(`${cur}_check`);
- if (check === '정답') {
- return acc + 1;
- }
- return acc;
- }, 0);
-
- li.querySelector('.solved').innerText = solved;
- li.querySelector('.progress-bar-inner').style.transform = `scaleX(${
- (solved / value.length) * 100
- }%)`;
- if (solved === value.length) {
- li.querySelector('.btn-download-certif').removeAttribute(
- 'disabled',
- );
- } else {
- li.querySelector('.btn-download-certif').setAttribute(
- 'disabled',
- true,
- );
- }
- });
-};
-setCertifItem();
-document.addEventListener('DOMContentLoaded', () => {
- updateCertifItem();
-});
-// const solved_count = storyChapter[chapter].reduce((acc, cur) => {
-// const check = localStorage.getItem(`element_check_${cur}`);
-// if (check === '통과') {
-// return acc + 1;
-// }
-// return acc;
-// }, 0);
-
-const dateFormat = () => {
- // yyyy-mm-dd-hh-mm-ss korean time
- const date = new Date();
- let format = '';
- format += date.getFullYear() + '-';
- format += date.getMonth() + 1 + '-';
- format += date.getDate() + '-';
- format += date.getHours() + '-';
- format += date.getMinutes() + '-';
- format += date.getSeconds();
- return format;
-};
-const downloadBtn = document.querySelector('.downloadNotebookBtn');
-downloadBtn.addEventListener('click', () => {
- downloadNotebook();
-});
-function downloadNotebook() {
- const notebook = {
- cells: [],
- metadata: {
- kernelspec: {
- display_name: 'Python 3',
- language: 'python',
- name: 'python3',
- },
- language_info: {
- codemirror_mode: {
- name: 'ipython',
- version: 3,
- },
- file_extension: '.py',
- mimetype: 'text/x-python',
- name: 'python',
- nbconvert_exporter: 'python',
- pygments_lexer: 'ipython3',
- version: '3.7.9',
- },
- },
- nbformat: 4,
- nbformat_minor: 4,
- };
-
- const cells = document.querySelectorAll('.py-repl-editor');
-
- for (let i = 0; i < cells.length; i++) {
- notebook.cells.push({
- cell_type: 'code',
- execution_count: null,
- metadata: {},
- outputs: [],
- // document.querySelector("#my-repl > div > div.py-repl-editor > div > div > div.cm-scroller > div.cm-content")
- source: cells[i].querySelector('.cm-content').innerText,
- });
- }
- const notebookJson = JSON.stringify(notebook, null, 2);
- const blob = new Blob([notebookJson], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
-
- const a = document.createElement('a');
- a.download = `notebook_${dateFormat()}.ipynb`;
- a.href = url;
- a.click();
-}
-const uploadBtn = document.querySelector('.uploadNotebookBtn');
-uploadBtn.addEventListener('click', () => {
- uploadNotebook();
-});
-function uploadNotebook() {
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = '.ipynb';
- input.onchange = (e) => {
- const file = e.target.files[0];
- const reader = new FileReader();
- reader.readAsText(file, 'UTF-8');
- reader.onload = (readerEvent) => {
- const content = readerEvent.target.result;
- const notebook = JSON.parse(content);
- const cells = notebook.cells;
- const $notebookSection = document.querySelector('#notebookSection');
- const autoGenerate = $notebookSection.querySelectorAll(
- 'py-repl[auto-generate="true"]',
- );
- autoGenerate.forEach((el) => el.removeAttribute('auto-generate'));
-
- for (const cell of cells) {
- const newRepl = document.createElement('py-repl');
-
- // 마지막 코드블럭만 auto-generate
- if (cell === cells[cells.length - 1]) {
- newRepl.setAttribute('auto-generate', 'true');
- }
- newRepl.textContent = cell.source;
- document.getElementById('notebookSection').appendChild(newRepl);
- }
- };
- };
- input.click();
-}
diff --git a/05d46b9abf6bf5ff59c6.webp b/05d46b9abf6bf5ff59c6.webp
deleted file mode 100644
index b76a11c..0000000
Binary files a/05d46b9abf6bf5ff59c6.webp and /dev/null differ
diff --git a/0969f7a3aaa125011c8d.png b/0969f7a3aaa125011c8d.png
deleted file mode 100644
index df1331b..0000000
Binary files a/0969f7a3aaa125011c8d.png and /dev/null differ
diff --git a/0d4a42fbabab76026332.svg b/0d4a42fbabab76026332.svg
deleted file mode 100644
index 6528171..0000000
--- a/0d4a42fbabab76026332.svg
+++ /dev/null
@@ -1,5 +0,0 @@
-
diff --git a/0d53fa7e7349d1ee8f23.svg b/0d53fa7e7349d1ee8f23.svg
deleted file mode 100644
index 1037f19..0000000
--- a/0d53fa7e7349d1ee8f23.svg
+++ /dev/null
@@ -1,4 +0,0 @@
-
diff --git a/0f97d79973f7a1d8d603.svg b/0f97d79973f7a1d8d603.svg
deleted file mode 100644
index df98e6b..0000000
--- a/0f97d79973f7a1d8d603.svg
+++ /dev/null
@@ -1,5 +0,0 @@
-
diff --git a/10e3942eeb8275061c1a.svg b/10e3942eeb8275061c1a.svg
deleted file mode 100644
index e50d136..0000000
--- a/10e3942eeb8275061c1a.svg
+++ /dev/null
@@ -1,5 +0,0 @@
-
diff --git a/1924bbc73bde14764134.png b/1924bbc73bde14764134.png
deleted file mode 100644
index 4f3a6b4..0000000
Binary files a/1924bbc73bde14764134.png and /dev/null differ
diff --git a/19e673e2ef5249b452f8.png b/19e673e2ef5249b452f8.png
deleted file mode 100644
index c597d79..0000000
Binary files a/19e673e2ef5249b452f8.png and /dev/null differ
diff --git a/1c7d19fcce58bdf57542.svg b/1c7d19fcce58bdf57542.svg
deleted file mode 100644
index d62ecce..0000000
--- a/1c7d19fcce58bdf57542.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-
diff --git a/1d5925e9da1f1c11421f.svg b/1d5925e9da1f1c11421f.svg
deleted file mode 100644
index 7c485de..0000000
--- a/1d5925e9da1f1c11421f.svg
+++ /dev/null
@@ -1,16 +0,0 @@
-
diff --git a/1f49bc9354250ef054d7.svg b/1f49bc9354250ef054d7.svg
deleted file mode 100644
index 05f5e29..0000000
--- a/1f49bc9354250ef054d7.svg
+++ /dev/null
@@ -1,6 +0,0 @@
-
diff --git a/2548fbcc3fab31e6fab5.svg b/2548fbcc3fab31e6fab5.svg
deleted file mode 100644
index 8258bd6..0000000
--- a/2548fbcc3fab31e6fab5.svg
+++ /dev/null
@@ -1,4 +0,0 @@
-
diff --git a/29bd8950b4a884d4802f.js b/29bd8950b4a884d4802f.js
deleted file mode 100644
index ad5696c..0000000
--- a/29bd8950b4a884d4802f.js
+++ /dev/null
@@ -1,29243 +0,0 @@
-var pyscript = (() => {
- var __create = Object.create;
- var __defProp = Object.defineProperty;
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
- var __getOwnPropNames = Object.getOwnPropertyNames;
- var __getProtoOf = Object.getPrototypeOf;
- var __hasOwnProp = Object.prototype.hasOwnProperty;
- var __commonJS = (cb, mod) => function __require() {
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
- };
- var __export = (target, all) => {
- for (var name2 in all)
- __defProp(target, name2, { get: all[name2], enumerable: true });
- };
- var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
- };
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
- // If the importer is in node compatibility mode or this is not an ESM
- // file that has been converted to a CommonJS file using a Babel-
- // compatible transform (i.e. "__esModule" has not been set), then set
- // "default" to the CommonJS "module.exports" for node compatibility.
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
- mod
- ));
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
- // node_modules/@hoodmane/toml-j0.4/lib/parser.js
- var require_parser = __commonJS({
- "node_modules/@hoodmane/toml-j0.4/lib/parser.js"(exports, module) {
- module.exports = /*
- * Generated by PEG.js 0.10.0.
- *
- * http://pegjs.org/
- */
- function() {
- "use strict";
- function peg$subclass(child, parent) {
- function ctor() {
- this.constructor = child;
- }
- ctor.prototype = parent.prototype;
- child.prototype = new ctor();
- }
- function peg$SyntaxError(message, expected, found, location) {
- this.message = message;
- this.expected = expected;
- this.found = found;
- this.location = location;
- this.name = "SyntaxError";
- if (typeof Error.captureStackTrace === "function") {
- Error.captureStackTrace(this, peg$SyntaxError);
- }
- }
- peg$subclass(peg$SyntaxError, Error);
- peg$SyntaxError.buildMessage = function(expected, found) {
- var DESCRIBE_EXPECTATION_FNS = {
- literal: function(expectation) {
- return '"' + literalEscape(expectation.text) + '"';
- },
- "class": function(expectation) {
- var escapedParts = "", i;
- for (i = 0; i < expectation.parts.length; i++) {
- escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]);
- }
- return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]";
- },
- any: function(expectation) {
- return "any character";
- },
- end: function(expectation) {
- return "end of input";
- },
- other: function(expectation) {
- return expectation.description;
- }
- };
- function hex(ch) {
- return ch.charCodeAt(0).toString(16).toUpperCase();
- }
- function literalEscape(s) {
- return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function(ch) {
- return "\\x0" + hex(ch);
- }).replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) {
- return "\\x" + hex(ch);
- });
- }
- function classEscape(s) {
- return s.replace(/\\/g, "\\\\").replace(/\]/g, "\\]").replace(/\^/g, "\\^").replace(/-/g, "\\-").replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function(ch) {
- return "\\x0" + hex(ch);
- }).replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) {
- return "\\x" + hex(ch);
- });
- }
- function describeExpectation(expectation) {
- return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);
- }
- function describeExpected(expected2) {
- var descriptions = new Array(expected2.length), i, j;
- for (i = 0; i < expected2.length; i++) {
- descriptions[i] = describeExpectation(expected2[i]);
- }
- descriptions.sort();
- if (descriptions.length > 0) {
- for (i = 1, j = 1; i < descriptions.length; i++) {
- if (descriptions[i - 1] !== descriptions[i]) {
- descriptions[j] = descriptions[i];
- j++;
- }
- }
- descriptions.length = j;
- }
- switch (descriptions.length) {
- case 1:
- return descriptions[0];
- case 2:
- return descriptions[0] + " or " + descriptions[1];
- default:
- return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1];
- }
- }
- function describeFound(found2) {
- return found2 ? '"' + literalEscape(found2) + '"' : "end of input";
- }
- return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found.";
- };
- function peg$parse(input, options) {
- options = options !== void 0 ? options : {};
- var peg$FAILED = {}, peg$startRuleFunctions = { Expressions: peg$parseExpressions }, peg$startRuleFunction = peg$parseExpressions, peg$c0 = function() {
- return g_root;
- }, peg$c1 = function(path) {
- g_context = findContext(g_root, true, path);
- }, peg$c2 = function(path) {
- g_context = findContext(g_root, false, path);
- }, peg$c3 = function(keyValue) {
- checkTableKey(g_context.table, keyValue[0]);
- g_context.table[keyValue[0]] = keyValue[1];
- }, peg$c4 = peg$otherExpectation("Newline"), peg$c5 = "\n", peg$c6 = peg$literalExpectation("\n", false), peg$c7 = "\r\n", peg$c8 = peg$literalExpectation("\r\n", false), peg$c9 = peg$otherExpectation("Whitespace"), peg$c10 = /^[ \t]/, peg$c11 = peg$classExpectation([" ", " "], false, false), peg$c12 = peg$otherExpectation("Comment"), peg$c13 = "#", peg$c14 = peg$literalExpectation("#", false), peg$c15 = peg$anyExpectation(), peg$c16 = "=", peg$c17 = peg$literalExpectation("=", false), peg$c18 = function(key, value) {
- return [key, value.value];
- }, peg$c19 = function() {
- return text();
- }, peg$c20 = peg$otherExpectation('[a-z], [A-Z], [0-9], "-", "_"'), peg$c21 = /^[a-zA-Z0-9\-_]/, peg$c22 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-", "_"], false, false), peg$c23 = function(chars) {
- return chars.join("");
- }, peg$c24 = peg$otherExpectation("DoubleQuote"), peg$c25 = '"', peg$c26 = peg$literalExpectation('"', false), peg$c27 = peg$otherExpectation("SingleQuote"), peg$c28 = "'", peg$c29 = peg$literalExpectation("'", false), peg$c30 = peg$otherExpectation("ThreeDoubleQuotes"), peg$c31 = '"""', peg$c32 = peg$literalExpectation('"""', false), peg$c33 = peg$otherExpectation("ThreeSingleQuotes"), peg$c34 = "'''", peg$c35 = peg$literalExpectation("'''", false), peg$c36 = function(chars) {
- return {
- type: "String",
- value: chars.join("")
- };
- }, peg$c37 = peg$otherExpectation("NormalCharacter"), peg$c38 = /^[^\0-\x1F"\\]/, peg$c39 = peg$classExpectation([["\0", ""], '"', "\\"], true, false), peg$c40 = "u", peg$c41 = peg$literalExpectation("u", false), peg$c42 = "U", peg$c43 = peg$literalExpectation("U", false), peg$c44 = function() {
- var s = text();
- if (s.length <= 2) {
- return unescape(s[1]);
- }
- return fromCodePoint2(parseInt(s.substr(2), 16));
- }, peg$c45 = peg$otherExpectation('"b", "f", "n", "r", "t"'), peg$c46 = /^[bfnrt]/, peg$c47 = peg$classExpectation(["b", "f", "n", "r", "t"], false, false), peg$c48 = peg$otherExpectation("Backslash"), peg$c49 = "\\", peg$c50 = peg$literalExpectation("\\", false), peg$c51 = peg$otherExpectation("FourHexadecimalDigits"), peg$c52 = peg$otherExpectation("EightHexadecimalDigits"), peg$c53 = /^[0-9A-Fa-f]/, peg$c54 = peg$classExpectation([["0", "9"], ["A", "F"], ["a", "f"]], false, false), peg$c55 = function() {
- var s = text();
- return {
- type: "String",
- value: s.substr(1, s.length - 2)
- };
- }, peg$c56 = /^[^\0-\x08\n-\x1F']/, peg$c57 = peg$classExpectation([["\0", "\b"], ["\n", ""], "'"], true, false), peg$c58 = function() {
- return "";
- }, peg$c59 = /^[^\0-\x1F\\]/, peg$c60 = peg$classExpectation([["\0", ""], "\\"], true, false), peg$c61 = peg$otherExpectation("AnyCharacter"), peg$c62 = /^[^\0-\x08\n-\x1F]/, peg$c63 = peg$classExpectation([["\0", "\b"], ["\n", ""]], true, false), peg$c64 = "true", peg$c65 = peg$literalExpectation("true", false), peg$c66 = function() {
- return {
- type: "Boolean",
- value: true
- };
- }, peg$c67 = "false", peg$c68 = peg$literalExpectation("false", false), peg$c69 = function() {
- return {
- type: "Boolean",
- value: false
- };
- }, peg$c70 = function() {
- var s = text();
- var number2 = parseFloat(s.replace(/_/g, ""));
- if (!isFiniteNumber(number2)) {
- error(s + "is not a 64-bit floating-point number.");
- }
- return {
- type: "Float",
- value: number2
- };
- }, peg$c71 = ".", peg$c72 = peg$literalExpectation(".", false), peg$c73 = "_", peg$c74 = peg$literalExpectation("_", false), peg$c75 = "e", peg$c76 = peg$literalExpectation("e", false), peg$c77 = "E", peg$c78 = peg$literalExpectation("E", false), peg$c79 = function() {
- var s = text();
- if (/^[-+]?0./.test(s)) {
- error("integer must not contain leading zeros");
- }
- var number2 = s.replace(/_/g, "");
- var invalid2 = false;
- if (number2[0] === "-") {
- var minInt = "-9223372036854775808";
- if (number2.length > minInt.length || number2.length === minInt.length && number2 > minInt) {
- invalid2 = true;
- }
- } else {
- if (number2[0] === "+") {
- number2 = number2.substr(1);
- }
- var maxInt = "9223372036854775807";
- if (number2.length > maxInt.length || number2.length === maxInt.length && number2 > maxInt) {
- invalid2 = true;
- }
- }
- if (invalid2) {
- error(s + " is not a 64-bit signed integer.");
- }
- number2 = parseInt(number2, 10);
- if (!isFiniteNumber(number2)) {
- error(s + " is not a 64-bit signed integer.");
- }
- return {
- type: "Integer",
- value: number2
- };
- }, peg$c80 = "+", peg$c81 = peg$literalExpectation("+", false), peg$c82 = "-", peg$c83 = peg$literalExpectation("-", false), peg$c84 = /^[0-9]/, peg$c85 = peg$classExpectation([["0", "9"]], false, false), peg$c86 = "T", peg$c87 = peg$literalExpectation("T", false), peg$c88 = function() {
- var s = text();
- var date = new Date(s);
- if (!isFiniteNumber(date.getTime())) {
- error("Date-time " + s + " is invalid. It does not conform to RFC 3339 or this is a browser-specific problem.");
- }
- return {
- type: "DateTime",
- value: date
- };
- }, peg$c89 = peg$otherExpectation("FullDate (YYYY-mm-dd)"), peg$c90 = ":", peg$c91 = peg$literalExpectation(":", false), peg$c92 = peg$otherExpectation("Hour (HH)"), peg$c93 = peg$otherExpectation("Minute (MM)"), peg$c94 = peg$otherExpectation("Second (SS)"), peg$c95 = peg$otherExpectation("TimeOffset (Z or +/-HH:MM)"), peg$c96 = "Z", peg$c97 = peg$literalExpectation("Z", false), peg$c98 = "[", peg$c99 = peg$literalExpectation("[", false), peg$c100 = ",", peg$c101 = peg$literalExpectation(",", false), peg$c102 = "]", peg$c103 = peg$literalExpectation("]", false), peg$c104 = function(values) {
- var o = {
- type: "Array",
- value: values ? values[0] : []
- };
- for (var i = 0, arr = o.value, l = arr.length; i < l; i++) {
- arr[i] = arr[i].value;
- }
- return o;
- }, peg$c105 = function(value, opt) {
- var array = [value];
- if (opt) {
- var type = value.type;
- for (var i = 0, arr = opt[3], l = arr.length; i < l; i++) {
- if (type !== arr[i].type) {
- error(stringify(arr[i].value) + ' should be of type "' + type + '".');
- }
- array.push(arr[i]);
- }
- }
- return array;
- }, peg$c106 = "{", peg$c107 = peg$literalExpectation("{", false), peg$c108 = "}", peg$c109 = peg$literalExpectation("}", false), peg$c110 = function(opt) {
- var table = {};
- if (opt) {
- table[opt[0][0]] = opt[0][1];
- for (var i = 0, arr = opt[1], l = arr.length; i < l; i++) {
- var kv = arr[i][3];
- checkTableKey(table, kv[0]);
- table[kv[0]] = kv[1];
- }
- }
- return {
- type: "InlineTable",
- value: table
- };
- }, peg$c111 = function(path) {
- return path;
- }, peg$c112 = function(key, arr) {
- var path = [key];
- for (var i = 0, l = arr.length; i < l; i++) {
- path.push(arr[i][3]);
- }
- return path;
- }, peg$currPos = 0, peg$savedPos = 0, peg$posDetailsCache = [{ line: 1, column: 1 }], peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result;
- if ("startRule" in options) {
- if (!(options.startRule in peg$startRuleFunctions)) {
- throw new Error(`Can't start parsing from rule "` + options.startRule + '".');
- }
- peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
- }
- function text() {
- return input.substring(peg$savedPos, peg$currPos);
- }
- function location() {
- return peg$computeLocation(peg$savedPos, peg$currPos);
- }
- function expected(description, location2) {
- location2 = location2 !== void 0 ? location2 : peg$computeLocation(peg$savedPos, peg$currPos);
- throw peg$buildStructuredError(
- [peg$otherExpectation(description)],
- input.substring(peg$savedPos, peg$currPos),
- location2
- );
- }
- function error(message, location2) {
- location2 = location2 !== void 0 ? location2 : peg$computeLocation(peg$savedPos, peg$currPos);
- throw peg$buildSimpleError(message, location2);
- }
- function peg$literalExpectation(text2, ignoreCase) {
- return { type: "literal", text: text2, ignoreCase };
- }
- function peg$classExpectation(parts, inverted, ignoreCase) {
- return { type: "class", parts, inverted, ignoreCase };
- }
- function peg$anyExpectation() {
- return { type: "any" };
- }
- function peg$endExpectation() {
- return { type: "end" };
- }
- function peg$otherExpectation(description) {
- return { type: "other", description };
- }
- function peg$computePosDetails(pos) {
- var details = peg$posDetailsCache[pos], p;
- if (details) {
- return details;
- } else {
- p = pos - 1;
- while (!peg$posDetailsCache[p]) {
- p--;
- }
- details = peg$posDetailsCache[p];
- details = {
- line: details.line,
- column: details.column
- };
- while (p < pos) {
- if (input.charCodeAt(p) === 10) {
- details.line++;
- details.column = 1;
- } else {
- details.column++;
- }
- p++;
- }
- peg$posDetailsCache[pos] = details;
- return details;
- }
- }
- function peg$computeLocation(startPos, endPos) {
- var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos);
- return {
- start: {
- offset: startPos,
- line: startPosDetails.line,
- column: startPosDetails.column
- },
- end: {
- offset: endPos,
- line: endPosDetails.line,
- column: endPosDetails.column
- }
- };
- }
- function peg$fail(expected2) {
- if (peg$currPos < peg$maxFailPos) {
- return;
- }
- if (peg$currPos > peg$maxFailPos) {
- peg$maxFailPos = peg$currPos;
- peg$maxFailExpected = [];
- }
- peg$maxFailExpected.push(expected2);
- }
- function peg$buildSimpleError(message, location2) {
- return new peg$SyntaxError(message, null, null, location2);
- }
- function peg$buildStructuredError(expected2, found, location2) {
- return new peg$SyntaxError(
- peg$SyntaxError.buildMessage(expected2, found),
- expected2,
- found,
- location2
- );
- }
- function peg$parseExpressions() {
- var s0, s1, s2, s3, s4, s5, s6, s7;
- s0 = peg$currPos;
- s1 = [];
- s2 = peg$parseWhitespace();
- if (s2 === peg$FAILED) {
- s2 = peg$parseNewline();
- if (s2 === peg$FAILED) {
- s2 = peg$parseComment();
- }
- }
- while (s2 !== peg$FAILED) {
- s1.push(s2);
- s2 = peg$parseWhitespace();
- if (s2 === peg$FAILED) {
- s2 = peg$parseNewline();
- if (s2 === peg$FAILED) {
- s2 = peg$parseComment();
- }
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = peg$currPos;
- s3 = peg$parseExpression();
- if (s3 !== peg$FAILED) {
- s4 = [];
- s5 = peg$parseWhitespace();
- if (s5 === peg$FAILED) {
- s5 = peg$parseComment();
- }
- while (s5 !== peg$FAILED) {
- s4.push(s5);
- s5 = peg$parseWhitespace();
- if (s5 === peg$FAILED) {
- s5 = peg$parseComment();
- }
- }
- if (s4 !== peg$FAILED) {
- s5 = peg$currPos;
- s6 = peg$parseNewline();
- if (s6 !== peg$FAILED) {
- s7 = peg$parseExpressions();
- if (s7 !== peg$FAILED) {
- s6 = [s6, s7];
- s5 = s6;
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- if (s5 === peg$FAILED) {
- s5 = null;
- }
- if (s5 !== peg$FAILED) {
- s3 = [s3, s4, s5];
- s2 = s3;
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- if (s2 === peg$FAILED) {
- s2 = null;
- }
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c0();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseExpression() {
- var s0, s1;
- s0 = peg$currPos;
- s1 = peg$parseTableArrayHeader();
- if (s1 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c1(s1);
- }
- s0 = s1;
- if (s0 === peg$FAILED) {
- s0 = peg$currPos;
- s1 = peg$parseTableHeader();
- if (s1 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c2(s1);
- }
- s0 = s1;
- if (s0 === peg$FAILED) {
- s0 = peg$currPos;
- s1 = peg$parseKeyValue();
- if (s1 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c3(s1);
- }
- s0 = s1;
- }
- }
- return s0;
- }
- function peg$parseNewline() {
- var s0, s1;
- peg$silentFails++;
- if (input.charCodeAt(peg$currPos) === 10) {
- s0 = peg$c5;
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c6);
- }
- }
- if (s0 === peg$FAILED) {
- if (input.substr(peg$currPos, 2) === peg$c7) {
- s0 = peg$c7;
- peg$currPos += 2;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c8);
- }
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c4);
- }
- }
- return s0;
- }
- function peg$parseWhitespace() {
- var s0, s1;
- peg$silentFails++;
- if (peg$c10.test(input.charAt(peg$currPos))) {
- s0 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c11);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c9);
- }
- }
- return s0;
- }
- function peg$parseComment() {
- var s0, s1, s2, s3, s4, s5;
- peg$silentFails++;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 35) {
- s1 = peg$c13;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c14);
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$currPos;
- s4 = peg$currPos;
- peg$silentFails++;
- s5 = peg$parseNewline();
- peg$silentFails--;
- if (s5 === peg$FAILED) {
- s4 = void 0;
- } else {
- peg$currPos = s4;
- s4 = peg$FAILED;
- }
- if (s4 !== peg$FAILED) {
- if (input.length > peg$currPos) {
- s5 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s5 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c15);
- }
- }
- if (s5 !== peg$FAILED) {
- s4 = [s4, s5];
- s3 = s4;
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$currPos;
- s4 = peg$currPos;
- peg$silentFails++;
- s5 = peg$parseNewline();
- peg$silentFails--;
- if (s5 === peg$FAILED) {
- s4 = void 0;
- } else {
- peg$currPos = s4;
- s4 = peg$FAILED;
- }
- if (s4 !== peg$FAILED) {
- if (input.length > peg$currPos) {
- s5 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s5 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c15);
- }
- }
- if (s5 !== peg$FAILED) {
- s4 = [s4, s5];
- s3 = s4;
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- }
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c12);
- }
- }
- return s0;
- }
- function peg$parseKeyValue() {
- var s0, s1, s2, s3, s4, s5;
- s0 = peg$currPos;
- s1 = peg$parseKey();
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseWhitespace();
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseWhitespace();
- }
- if (s2 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 61) {
- s3 = peg$c16;
- peg$currPos++;
- } else {
- s3 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c17);
- }
- }
- if (s3 !== peg$FAILED) {
- s4 = [];
- s5 = peg$parseWhitespace();
- while (s5 !== peg$FAILED) {
- s4.push(s5);
- s5 = peg$parseWhitespace();
- }
- if (s4 !== peg$FAILED) {
- s5 = peg$parseValue();
- if (s5 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c18(s1, s5);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseKey() {
- var s0;
- s0 = peg$parseBareKey();
- if (s0 === peg$FAILED) {
- s0 = peg$parseQuotedKey();
- }
- return s0;
- }
- function peg$parseBareKey() {
- var s0, s1, s2;
- s0 = peg$currPos;
- s1 = [];
- s2 = peg$parseBareKeyCharacter();
- if (s2 !== peg$FAILED) {
- while (s2 !== peg$FAILED) {
- s1.push(s2);
- s2 = peg$parseBareKeyCharacter();
- }
- } else {
- s1 = peg$FAILED;
- }
- if (s1 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c19();
- }
- s0 = s1;
- return s0;
- }
- function peg$parseBareKeyCharacter() {
- var s0, s1;
- peg$silentFails++;
- if (peg$c21.test(input.charAt(peg$currPos))) {
- s0 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c22);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c20);
- }
- }
- return s0;
- }
- function peg$parseQuotedKey() {
- var s0, s1, s2, s3;
- s0 = peg$currPos;
- s1 = peg$parseDoubleQuote();
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseBasicCharacter();
- if (s3 !== peg$FAILED) {
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseBasicCharacter();
- }
- } else {
- s2 = peg$FAILED;
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseDoubleQuote();
- if (s3 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c23(s2);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseDoubleQuote() {
- var s0, s1;
- peg$silentFails++;
- if (input.charCodeAt(peg$currPos) === 34) {
- s0 = peg$c25;
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c26);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c24);
- }
- }
- return s0;
- }
- function peg$parseSingleQuote() {
- var s0, s1;
- peg$silentFails++;
- if (input.charCodeAt(peg$currPos) === 39) {
- s0 = peg$c28;
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c29);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c27);
- }
- }
- return s0;
- }
- function peg$parseThreeDoubleQuotes() {
- var s0, s1;
- peg$silentFails++;
- if (input.substr(peg$currPos, 3) === peg$c31) {
- s0 = peg$c31;
- peg$currPos += 3;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c32);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c30);
- }
- }
- return s0;
- }
- function peg$parseThreeSingleQuotes() {
- var s0, s1;
- peg$silentFails++;
- if (input.substr(peg$currPos, 3) === peg$c34) {
- s0 = peg$c34;
- peg$currPos += 3;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c35);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c33);
- }
- }
- return s0;
- }
- function peg$parseValue() {
- var s0;
- s0 = peg$parseString();
- if (s0 === peg$FAILED) {
- s0 = peg$parseBoolean();
- if (s0 === peg$FAILED) {
- s0 = peg$parseDateTime();
- if (s0 === peg$FAILED) {
- s0 = peg$parseFloat();
- if (s0 === peg$FAILED) {
- s0 = peg$parseInteger();
- if (s0 === peg$FAILED) {
- s0 = peg$parseArray();
- if (s0 === peg$FAILED) {
- s0 = peg$parseInlineTable();
- }
- }
- }
- }
- }
- }
- return s0;
- }
- function peg$parseString() {
- var s0;
- s0 = peg$parseMultilineBasicString();
- if (s0 === peg$FAILED) {
- s0 = peg$parseBasicString();
- if (s0 === peg$FAILED) {
- s0 = peg$parseMultilineLiteralString();
- if (s0 === peg$FAILED) {
- s0 = peg$parseLiteralString();
- }
- }
- }
- return s0;
- }
- function peg$parseBasicString() {
- var s0, s1, s2, s3;
- s0 = peg$currPos;
- s1 = peg$parseDoubleQuote();
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseBasicCharacter();
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseBasicCharacter();
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseDoubleQuote();
- if (s3 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c36(s2);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseBasicCharacter() {
- var s0;
- s0 = peg$parseNormalCharacter();
- if (s0 === peg$FAILED) {
- s0 = peg$parseEscapedCharacter();
- }
- return s0;
- }
- function peg$parseNormalCharacter() {
- var s0, s1, s2;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$currPos;
- peg$silentFails++;
- s2 = peg$parseNewline();
- peg$silentFails--;
- if (s2 === peg$FAILED) {
- s1 = void 0;
- } else {
- peg$currPos = s1;
- s1 = peg$FAILED;
- }
- if (s1 !== peg$FAILED) {
- if (peg$c38.test(input.charAt(peg$currPos))) {
- s2 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c39);
- }
- }
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c19();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c37);
- }
- }
- return s0;
- }
- function peg$parseEscapedCharacter() {
- var s0, s1, s2, s3, s4;
- s0 = peg$currPos;
- s1 = peg$parseBackslash();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseControlCharacter();
- if (s2 === peg$FAILED) {
- s2 = peg$parseDoubleQuote();
- if (s2 === peg$FAILED) {
- s2 = peg$parseBackslash();
- if (s2 === peg$FAILED) {
- s2 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 117) {
- s3 = peg$c40;
- peg$currPos++;
- } else {
- s3 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c41);
- }
- }
- if (s3 !== peg$FAILED) {
- s4 = peg$parseFourHexadecimalDigits();
- if (s4 !== peg$FAILED) {
- s3 = [s3, s4];
- s2 = s3;
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- if (s2 === peg$FAILED) {
- s2 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 85) {
- s3 = peg$c42;
- peg$currPos++;
- } else {
- s3 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c43);
- }
- }
- if (s3 !== peg$FAILED) {
- s4 = peg$parseEightHexadecimalDigits();
- if (s4 !== peg$FAILED) {
- s3 = [s3, s4];
- s2 = s3;
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- }
- }
- }
- }
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c44();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseControlCharacter() {
- var s0, s1;
- peg$silentFails++;
- if (peg$c46.test(input.charAt(peg$currPos))) {
- s0 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c47);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c45);
- }
- }
- return s0;
- }
- function peg$parseBackslash() {
- var s0, s1;
- peg$silentFails++;
- if (input.charCodeAt(peg$currPos) === 92) {
- s0 = peg$c49;
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c50);
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c48);
- }
- }
- return s0;
- }
- function peg$parseFourHexadecimalDigits() {
- var s0, s1, s2, s3, s4;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$parseHexDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseHexDigit();
- if (s2 !== peg$FAILED) {
- s3 = peg$parseHexDigit();
- if (s3 !== peg$FAILED) {
- s4 = peg$parseHexDigit();
- if (s4 !== peg$FAILED) {
- s1 = [s1, s2, s3, s4];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c51);
- }
- }
- return s0;
- }
- function peg$parseEightHexadecimalDigits() {
- var s0, s1, s2, s3, s4, s5, s6, s7, s8;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$parseHexDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseHexDigit();
- if (s2 !== peg$FAILED) {
- s3 = peg$parseHexDigit();
- if (s3 !== peg$FAILED) {
- s4 = peg$parseHexDigit();
- if (s4 !== peg$FAILED) {
- s5 = peg$parseHexDigit();
- if (s5 !== peg$FAILED) {
- s6 = peg$parseHexDigit();
- if (s6 !== peg$FAILED) {
- s7 = peg$parseHexDigit();
- if (s7 !== peg$FAILED) {
- s8 = peg$parseHexDigit();
- if (s8 !== peg$FAILED) {
- s1 = [s1, s2, s3, s4, s5, s6, s7, s8];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c52);
- }
- }
- return s0;
- }
- function peg$parseHexDigit() {
- var s0;
- if (peg$c53.test(input.charAt(peg$currPos))) {
- s0 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c54);
- }
- }
- return s0;
- }
- function peg$parseLiteralString() {
- var s0, s1, s2, s3;
- s0 = peg$currPos;
- s1 = peg$parseSingleQuote();
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseLiteralCharacter();
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseLiteralCharacter();
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseSingleQuote();
- if (s3 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c55();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseLiteralCharacter() {
- var s0, s1, s2;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$currPos;
- peg$silentFails++;
- s2 = peg$parseNewline();
- peg$silentFails--;
- if (s2 === peg$FAILED) {
- s1 = void 0;
- } else {
- peg$currPos = s1;
- s1 = peg$FAILED;
- }
- if (s1 !== peg$FAILED) {
- if (peg$c56.test(input.charAt(peg$currPos))) {
- s2 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c57);
- }
- }
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c37);
- }
- }
- return s0;
- }
- function peg$parseMultilineBasicString() {
- var s0, s1, s2, s3, s4;
- s0 = peg$currPos;
- s1 = peg$parseThreeDoubleQuotes();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseNewline();
- if (s2 === peg$FAILED) {
- s2 = null;
- }
- if (s2 !== peg$FAILED) {
- s3 = [];
- s4 = peg$parseMultilineBasicText();
- while (s4 !== peg$FAILED) {
- s3.push(s4);
- s4 = peg$parseMultilineBasicText();
- }
- if (s3 !== peg$FAILED) {
- s4 = peg$parseThreeDoubleQuotes();
- if (s4 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c36(s3);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseMultilineBasicText() {
- var s0, s1, s2, s3, s4;
- s0 = peg$parseMultilineBasicCharacter();
- if (s0 === peg$FAILED) {
- s0 = peg$currPos;
- s1 = peg$parseBackslash();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseNewline();
- if (s2 !== peg$FAILED) {
- s3 = [];
- s4 = peg$parseWhitespace();
- if (s4 === peg$FAILED) {
- s4 = peg$parseNewline();
- }
- while (s4 !== peg$FAILED) {
- s3.push(s4);
- s4 = peg$parseWhitespace();
- if (s4 === peg$FAILED) {
- s4 = peg$parseNewline();
- }
- }
- if (s3 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c58();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- if (s0 === peg$FAILED) {
- s0 = peg$parseNewline();
- }
- }
- return s0;
- }
- function peg$parseMultilineBasicCharacter() {
- var s0, s1, s2;
- s0 = peg$currPos;
- s1 = peg$currPos;
- peg$silentFails++;
- s2 = peg$parseThreeDoubleQuotes();
- peg$silentFails--;
- if (s2 === peg$FAILED) {
- s1 = void 0;
- } else {
- peg$currPos = s1;
- s1 = peg$FAILED;
- }
- if (s1 !== peg$FAILED) {
- s2 = peg$parseMultilineNormalCharacter();
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c19();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- if (s0 === peg$FAILED) {
- s0 = peg$parseEscapedCharacter();
- }
- return s0;
- }
- function peg$parseMultilineNormalCharacter() {
- var s0, s1, s2;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$currPos;
- peg$silentFails++;
- s2 = peg$parseNewline();
- peg$silentFails--;
- if (s2 === peg$FAILED) {
- s1 = void 0;
- } else {
- peg$currPos = s1;
- s1 = peg$FAILED;
- }
- if (s1 !== peg$FAILED) {
- if (peg$c59.test(input.charAt(peg$currPos))) {
- s2 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c60);
- }
- }
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c37);
- }
- }
- return s0;
- }
- function peg$parseMultilineLiteralString() {
- var s0, s1, s2, s3, s4;
- s0 = peg$currPos;
- s1 = peg$parseThreeSingleQuotes();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseNewline();
- if (s2 === peg$FAILED) {
- s2 = null;
- }
- if (s2 !== peg$FAILED) {
- s3 = [];
- s4 = peg$parseMultilineLiteralText();
- while (s4 !== peg$FAILED) {
- s3.push(s4);
- s4 = peg$parseMultilineLiteralText();
- }
- if (s3 !== peg$FAILED) {
- s4 = peg$parseThreeSingleQuotes();
- if (s4 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c36(s3);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseMultilineLiteralText() {
- var s0, s1, s2;
- s0 = peg$currPos;
- s1 = peg$currPos;
- peg$silentFails++;
- if (input.substr(peg$currPos, 3) === peg$c34) {
- s2 = peg$c34;
- peg$currPos += 3;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c35);
- }
- }
- peg$silentFails--;
- if (s2 === peg$FAILED) {
- s1 = void 0;
- } else {
- peg$currPos = s1;
- s1 = peg$FAILED;
- }
- if (s1 !== peg$FAILED) {
- s2 = peg$parseMultilineLiteralCharacter();
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c19();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- if (s0 === peg$FAILED) {
- s0 = peg$parseNewline();
- }
- return s0;
- }
- function peg$parseMultilineLiteralCharacter() {
- var s0, s1, s2;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$currPos;
- peg$silentFails++;
- s2 = peg$parseNewline();
- peg$silentFails--;
- if (s2 === peg$FAILED) {
- s1 = void 0;
- } else {
- peg$currPos = s1;
- s1 = peg$FAILED;
- }
- if (s1 !== peg$FAILED) {
- if (peg$c62.test(input.charAt(peg$currPos))) {
- s2 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c63);
- }
- }
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c61);
- }
- }
- return s0;
- }
- function peg$parseBoolean() {
- var s0, s1;
- s0 = peg$currPos;
- if (input.substr(peg$currPos, 4) === peg$c64) {
- s1 = peg$c64;
- peg$currPos += 4;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c65);
- }
- }
- if (s1 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c66();
- }
- s0 = s1;
- if (s0 === peg$FAILED) {
- s0 = peg$currPos;
- if (input.substr(peg$currPos, 5) === peg$c67) {
- s1 = peg$c67;
- peg$currPos += 5;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c68);
- }
- }
- if (s1 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c69();
- }
- s0 = s1;
- }
- return s0;
- }
- function peg$parseFloat() {
- var s0, s1, s2, s3, s4;
- s0 = peg$currPos;
- s1 = peg$parseInteger();
- if (s1 !== peg$FAILED) {
- s2 = peg$currPos;
- s3 = peg$parseFraction();
- if (s3 !== peg$FAILED) {
- s4 = peg$parseExponent();
- if (s4 === peg$FAILED) {
- s4 = null;
- }
- if (s4 !== peg$FAILED) {
- s3 = [s3, s4];
- s2 = s3;
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- if (s2 === peg$FAILED) {
- s2 = peg$parseExponent();
- }
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c70();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseFraction() {
- var s0, s1, s2, s3, s4, s5, s6;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 46) {
- s1 = peg$c71;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c72);
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = peg$parseDigit();
- if (s2 !== peg$FAILED) {
- s3 = [];
- s4 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 95) {
- s5 = peg$c73;
- peg$currPos++;
- } else {
- s5 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c74);
- }
- }
- if (s5 === peg$FAILED) {
- s5 = null;
- }
- if (s5 !== peg$FAILED) {
- s6 = peg$parseDigit();
- if (s6 !== peg$FAILED) {
- s5 = [s5, s6];
- s4 = s5;
- } else {
- peg$currPos = s4;
- s4 = peg$FAILED;
- }
- } else {
- peg$currPos = s4;
- s4 = peg$FAILED;
- }
- while (s4 !== peg$FAILED) {
- s3.push(s4);
- s4 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 95) {
- s5 = peg$c73;
- peg$currPos++;
- } else {
- s5 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c74);
- }
- }
- if (s5 === peg$FAILED) {
- s5 = null;
- }
- if (s5 !== peg$FAILED) {
- s6 = peg$parseDigit();
- if (s6 !== peg$FAILED) {
- s5 = [s5, s6];
- s4 = s5;
- } else {
- peg$currPos = s4;
- s4 = peg$FAILED;
- }
- } else {
- peg$currPos = s4;
- s4 = peg$FAILED;
- }
- }
- if (s3 !== peg$FAILED) {
- s1 = [s1, s2, s3];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseExponent() {
- var s0, s1, s2, s3;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 101) {
- s1 = peg$c75;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c76);
- }
- }
- if (s1 === peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 69) {
- s1 = peg$c77;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c78);
- }
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = peg$parseSign();
- if (s2 === peg$FAILED) {
- s2 = null;
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseIntDigits();
- if (s3 !== peg$FAILED) {
- s1 = [s1, s2, s3];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseInteger() {
- var s0, s1, s2;
- s0 = peg$currPos;
- s1 = peg$parseSign();
- if (s1 === peg$FAILED) {
- s1 = null;
- }
- if (s1 !== peg$FAILED) {
- s2 = peg$parseIntDigits();
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c79();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseSign() {
- var s0;
- if (input.charCodeAt(peg$currPos) === 43) {
- s0 = peg$c80;
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c81);
- }
- }
- if (s0 === peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 45) {
- s0 = peg$c82;
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c83);
- }
- }
- }
- return s0;
- }
- function peg$parseIntDigits() {
- var s0, s1, s2, s3, s4, s5;
- s0 = peg$currPos;
- s1 = peg$parseDigit();
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 95) {
- s4 = peg$c73;
- peg$currPos++;
- } else {
- s4 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c74);
- }
- }
- if (s4 === peg$FAILED) {
- s4 = null;
- }
- if (s4 !== peg$FAILED) {
- s5 = peg$parseDigit();
- if (s5 !== peg$FAILED) {
- s4 = [s4, s5];
- s3 = s4;
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 95) {
- s4 = peg$c73;
- peg$currPos++;
- } else {
- s4 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c74);
- }
- }
- if (s4 === peg$FAILED) {
- s4 = null;
- }
- if (s4 !== peg$FAILED) {
- s5 = peg$parseDigit();
- if (s5 !== peg$FAILED) {
- s4 = [s4, s5];
- s3 = s4;
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- }
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseDigit() {
- var s0;
- if (peg$c84.test(input.charAt(peg$currPos))) {
- s0 = input.charAt(peg$currPos);
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c85);
- }
- }
- return s0;
- }
- function peg$parseDateTime() {
- var s0, s1, s2, s3;
- s0 = peg$currPos;
- s1 = peg$parseFullDate();
- if (s1 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 84) {
- s2 = peg$c86;
- peg$currPos++;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c87);
- }
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseFullTime();
- if (s3 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c88();
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseFullDate() {
- var s0, s1, s2, s3, s4, s5;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$parseYear();
- if (s1 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 45) {
- s2 = peg$c82;
- peg$currPos++;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c83);
- }
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseMonth();
- if (s3 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 45) {
- s4 = peg$c82;
- peg$currPos++;
- } else {
- s4 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c83);
- }
- }
- if (s4 !== peg$FAILED) {
- s5 = peg$parseMDay();
- if (s5 !== peg$FAILED) {
- s1 = [s1, s2, s3, s4, s5];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c89);
- }
- }
- return s0;
- }
- function peg$parseYear() {
- var s0, s1, s2, s3, s4;
- s0 = peg$currPos;
- s1 = peg$parseDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseDigit();
- if (s2 !== peg$FAILED) {
- s3 = peg$parseDigit();
- if (s3 !== peg$FAILED) {
- s4 = peg$parseDigit();
- if (s4 !== peg$FAILED) {
- s1 = [s1, s2, s3, s4];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseMonth() {
- var s0, s1, s2;
- s0 = peg$currPos;
- s1 = peg$parseDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseDigit();
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseMDay() {
- var s0, s1, s2;
- s0 = peg$currPos;
- s1 = peg$parseDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseDigit();
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseFullTime() {
- var s0, s1, s2;
- s0 = peg$currPos;
- s1 = peg$parseTime();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseTimeOffset();
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseTime() {
- var s0, s1, s2, s3, s4, s5, s6;
- s0 = peg$currPos;
- s1 = peg$parseHour();
- if (s1 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 58) {
- s2 = peg$c90;
- peg$currPos++;
- } else {
- s2 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c91);
- }
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseMinute();
- if (s3 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 58) {
- s4 = peg$c90;
- peg$currPos++;
- } else {
- s4 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c91);
- }
- }
- if (s4 !== peg$FAILED) {
- s5 = peg$parseSecond();
- if (s5 !== peg$FAILED) {
- s6 = peg$parseSecondFraction();
- if (s6 === peg$FAILED) {
- s6 = null;
- }
- if (s6 !== peg$FAILED) {
- s1 = [s1, s2, s3, s4, s5, s6];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseHour() {
- var s0, s1, s2;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$parseDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseDigit();
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c92);
- }
- }
- return s0;
- }
- function peg$parseMinute() {
- var s0, s1, s2;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$parseDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseDigit();
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c93);
- }
- }
- return s0;
- }
- function peg$parseSecond() {
- var s0, s1, s2;
- peg$silentFails++;
- s0 = peg$currPos;
- s1 = peg$parseDigit();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseDigit();
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c94);
- }
- }
- return s0;
- }
- function peg$parseSecondFraction() {
- var s0, s1, s2, s3;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 46) {
- s1 = peg$c71;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c72);
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseDigit();
- if (s3 !== peg$FAILED) {
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseDigit();
- }
- } else {
- s2 = peg$FAILED;
- }
- if (s2 !== peg$FAILED) {
- s1 = [s1, s2];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseTimeOffset() {
- var s0, s1, s2, s3, s4;
- peg$silentFails++;
- if (input.charCodeAt(peg$currPos) === 90) {
- s0 = peg$c96;
- peg$currPos++;
- } else {
- s0 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c97);
- }
- }
- if (s0 === peg$FAILED) {
- s0 = peg$currPos;
- s1 = peg$parseSign();
- if (s1 !== peg$FAILED) {
- s2 = peg$parseHour();
- if (s2 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 58) {
- s3 = peg$c90;
- peg$currPos++;
- } else {
- s3 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c91);
- }
- }
- if (s3 !== peg$FAILED) {
- s4 = peg$parseMinute();
- if (s4 !== peg$FAILED) {
- s1 = [s1, s2, s3, s4];
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- }
- peg$silentFails--;
- if (s0 === peg$FAILED) {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c95);
- }
- }
- return s0;
- }
- function peg$parseArray() {
- var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 91) {
- s1 = peg$c98;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c99);
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseArraySpace();
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseArraySpace();
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$currPos;
- s4 = peg$parseArrayValue();
- if (s4 !== peg$FAILED) {
- s5 = [];
- s6 = peg$parseArraySpace();
- while (s6 !== peg$FAILED) {
- s5.push(s6);
- s6 = peg$parseArraySpace();
- }
- if (s5 !== peg$FAILED) {
- s6 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 44) {
- s7 = peg$c100;
- peg$currPos++;
- } else {
- s7 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c101);
- }
- }
- if (s7 !== peg$FAILED) {
- s8 = [];
- s9 = peg$parseArraySpace();
- while (s9 !== peg$FAILED) {
- s8.push(s9);
- s9 = peg$parseArraySpace();
- }
- if (s8 !== peg$FAILED) {
- s7 = [s7, s8];
- s6 = s7;
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- if (s6 === peg$FAILED) {
- s6 = null;
- }
- if (s6 !== peg$FAILED) {
- s4 = [s4, s5, s6];
- s3 = s4;
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- if (s3 === peg$FAILED) {
- s3 = null;
- }
- if (s3 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 93) {
- s4 = peg$c102;
- peg$currPos++;
- } else {
- s4 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c103);
- }
- }
- if (s4 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c104(s3);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseArrayValue() {
- var s0, s1, s2, s3, s4, s5, s6;
- s0 = peg$currPos;
- s1 = peg$parseValue();
- if (s1 !== peg$FAILED) {
- s2 = peg$currPos;
- s3 = [];
- s4 = peg$parseArraySpace();
- while (s4 !== peg$FAILED) {
- s3.push(s4);
- s4 = peg$parseArraySpace();
- }
- if (s3 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 44) {
- s4 = peg$c100;
- peg$currPos++;
- } else {
- s4 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c101);
- }
- }
- if (s4 !== peg$FAILED) {
- s5 = [];
- s6 = peg$parseArraySpace();
- while (s6 !== peg$FAILED) {
- s5.push(s6);
- s6 = peg$parseArraySpace();
- }
- if (s5 !== peg$FAILED) {
- s6 = peg$parseArrayValue();
- if (s6 !== peg$FAILED) {
- s3 = [s3, s4, s5, s6];
- s2 = s3;
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- } else {
- peg$currPos = s2;
- s2 = peg$FAILED;
- }
- if (s2 === peg$FAILED) {
- s2 = null;
- }
- if (s2 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c105(s1, s2);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseArraySpace() {
- var s0;
- s0 = peg$parseWhitespace();
- if (s0 === peg$FAILED) {
- s0 = peg$parseNewline();
- if (s0 === peg$FAILED) {
- s0 = peg$parseComment();
- }
- }
- return s0;
- }
- function peg$parseInlineTable() {
- var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 123) {
- s1 = peg$c106;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c107);
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseWhitespace();
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseWhitespace();
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$currPos;
- s4 = peg$parseKeyValue();
- if (s4 !== peg$FAILED) {
- s5 = [];
- s6 = peg$currPos;
- s7 = [];
- s8 = peg$parseWhitespace();
- while (s8 !== peg$FAILED) {
- s7.push(s8);
- s8 = peg$parseWhitespace();
- }
- if (s7 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 44) {
- s8 = peg$c100;
- peg$currPos++;
- } else {
- s8 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c101);
- }
- }
- if (s8 !== peg$FAILED) {
- s9 = [];
- s10 = peg$parseWhitespace();
- while (s10 !== peg$FAILED) {
- s9.push(s10);
- s10 = peg$parseWhitespace();
- }
- if (s9 !== peg$FAILED) {
- s10 = peg$parseKeyValue();
- if (s10 !== peg$FAILED) {
- s7 = [s7, s8, s9, s10];
- s6 = s7;
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- while (s6 !== peg$FAILED) {
- s5.push(s6);
- s6 = peg$currPos;
- s7 = [];
- s8 = peg$parseWhitespace();
- while (s8 !== peg$FAILED) {
- s7.push(s8);
- s8 = peg$parseWhitespace();
- }
- if (s7 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 44) {
- s8 = peg$c100;
- peg$currPos++;
- } else {
- s8 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c101);
- }
- }
- if (s8 !== peg$FAILED) {
- s9 = [];
- s10 = peg$parseWhitespace();
- while (s10 !== peg$FAILED) {
- s9.push(s10);
- s10 = peg$parseWhitespace();
- }
- if (s9 !== peg$FAILED) {
- s10 = peg$parseKeyValue();
- if (s10 !== peg$FAILED) {
- s7 = [s7, s8, s9, s10];
- s6 = s7;
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- } else {
- peg$currPos = s6;
- s6 = peg$FAILED;
- }
- }
- if (s5 !== peg$FAILED) {
- s6 = [];
- s7 = peg$parseWhitespace();
- while (s7 !== peg$FAILED) {
- s6.push(s7);
- s7 = peg$parseWhitespace();
- }
- if (s6 !== peg$FAILED) {
- s4 = [s4, s5, s6];
- s3 = s4;
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- } else {
- peg$currPos = s3;
- s3 = peg$FAILED;
- }
- if (s3 === peg$FAILED) {
- s3 = null;
- }
- if (s3 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 125) {
- s4 = peg$c108;
- peg$currPos++;
- } else {
- s4 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c109);
- }
- }
- if (s4 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c110(s3);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseTableArrayHeader() {
- var s0, s1, s2, s3;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 91) {
- s1 = peg$c98;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c99);
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = peg$parseTableHeader();
- if (s2 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 93) {
- s3 = peg$c102;
- peg$currPos++;
- } else {
- s3 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c103);
- }
- }
- if (s3 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c111(s2);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- function peg$parseTableHeader() {
- var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
- s0 = peg$currPos;
- if (input.charCodeAt(peg$currPos) === 91) {
- s1 = peg$c98;
- peg$currPos++;
- } else {
- s1 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c99);
- }
- }
- if (s1 !== peg$FAILED) {
- s2 = [];
- s3 = peg$parseWhitespace();
- while (s3 !== peg$FAILED) {
- s2.push(s3);
- s3 = peg$parseWhitespace();
- }
- if (s2 !== peg$FAILED) {
- s3 = peg$parseKey();
- if (s3 !== peg$FAILED) {
- s4 = [];
- s5 = peg$currPos;
- s6 = [];
- s7 = peg$parseWhitespace();
- while (s7 !== peg$FAILED) {
- s6.push(s7);
- s7 = peg$parseWhitespace();
- }
- if (s6 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 46) {
- s7 = peg$c71;
- peg$currPos++;
- } else {
- s7 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c72);
- }
- }
- if (s7 !== peg$FAILED) {
- s8 = [];
- s9 = peg$parseWhitespace();
- while (s9 !== peg$FAILED) {
- s8.push(s9);
- s9 = peg$parseWhitespace();
- }
- if (s8 !== peg$FAILED) {
- s9 = peg$parseKey();
- if (s9 !== peg$FAILED) {
- s6 = [s6, s7, s8, s9];
- s5 = s6;
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- while (s5 !== peg$FAILED) {
- s4.push(s5);
- s5 = peg$currPos;
- s6 = [];
- s7 = peg$parseWhitespace();
- while (s7 !== peg$FAILED) {
- s6.push(s7);
- s7 = peg$parseWhitespace();
- }
- if (s6 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 46) {
- s7 = peg$c71;
- peg$currPos++;
- } else {
- s7 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c72);
- }
- }
- if (s7 !== peg$FAILED) {
- s8 = [];
- s9 = peg$parseWhitespace();
- while (s9 !== peg$FAILED) {
- s8.push(s9);
- s9 = peg$parseWhitespace();
- }
- if (s8 !== peg$FAILED) {
- s9 = peg$parseKey();
- if (s9 !== peg$FAILED) {
- s6 = [s6, s7, s8, s9];
- s5 = s6;
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- } else {
- peg$currPos = s5;
- s5 = peg$FAILED;
- }
- }
- if (s4 !== peg$FAILED) {
- s5 = [];
- s6 = peg$parseWhitespace();
- while (s6 !== peg$FAILED) {
- s5.push(s6);
- s6 = peg$parseWhitespace();
- }
- if (s5 !== peg$FAILED) {
- if (input.charCodeAt(peg$currPos) === 93) {
- s6 = peg$c102;
- peg$currPos++;
- } else {
- s6 = peg$FAILED;
- if (peg$silentFails === 0) {
- peg$fail(peg$c103);
- }
- }
- if (s6 !== peg$FAILED) {
- peg$savedPos = s0;
- s1 = peg$c112(s3, s4);
- s0 = s1;
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- } else {
- peg$currPos = s0;
- s0 = peg$FAILED;
- }
- return s0;
- }
- var genMsgRedefined, isFiniteNumber, isArray, hasOwnProperty, stringify, unescape, fromCodePoint2, checkTableKey, findContext;
- genMsgRedefined = function(key) {
- return "Value for " + key + " should not be redefined in the same table.";
- };
- isFiniteNumber = Number.isFinite || function(n) {
- return typeof n === "number" && isFinite(n);
- };
- isArray = Array.isArray || function(obj) {
- return Object.prototype.toString.call(obj) === "[object Array]";
- };
- hasOwnProperty = function(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj, key);
- };
- stringify = typeof JSON === "object" && JSON ? JSON.stringify : function(o) {
- return '"' + String(o).replace(/[\x00-\x1F"\\]/g, function(c) {
- switch (c) {
- case '"':
- case "\\":
- return "\\" + c;
- case " ":
- return "\\t";
- case "\n":
- return "\\n";
- case "\r":
- return "\\r";
- case "\b":
- return "\\b";
- case "\f":
- return "\\f";
- default:
- var hex = c.charCodeAt(0).toString(16);
- return "\\u" + "0000".substr(hex.length) + hex;
- }
- }) + '"';
- };
- unescape = function(c) {
- switch (c) {
- case '"':
- case "\\":
- return c;
- case "t":
- return " ";
- case "n":
- return "\n";
- case "r":
- return "\r";
- case "b":
- return "\b";
- case "f":
- return "\f";
- default:
- error(stringify(c) + " cannot be escaped.");
- }
- };
- fromCodePoint2 = function(codepoint) {
- if (!isFiniteNumber(codepoint) || codepoint < 0 || codepoint > 1114111) {
- error("U+" + codepoint.toString(16) + " is not a valid Unicode code point.");
- }
- if (String.fromCodePoint) {
- return String.fromCodePoint(codepoint);
- }
- var c = "";
- if (codepoint > 65535) {
- codepoint -= 65536;
- c += String.fromCharCode(codepoint >>> 10 & 1023 | 55296);
- codepoint = 56320 | codepoint & 1023;
- }
- c += String.fromCharCode(codepoint);
- return c;
- };
- checkTableKey = function(table, k) {
- if (hasOwnProperty(table, k)) {
- error(genMsgRedefined(stringify(k)));
- }
- };
- findContext = function(table, isTableArray, path) {
- var s = "";
- for (var i = 0, l = path.length; i < l; i++) {
- var k = path[i];
- s += (s ? "." : "") + stringify(k);
- if (!hasOwnProperty(table, k)) {
- if (isTableArray && i + 1 === l) {
- var t2 = {};
- table[k] = [t2];
- table = t2;
- g_table_arrays[s] = true;
- } else {
- table = table[k] = {};
- g_tables[s] = true;
- }
- } else {
- if (isTableArray) {
- if (isArray(table[k])) {
- if (!g_table_arrays[s]) {
- error(genMsgRedefined(s));
- }
- if (i + 1 === l) {
- var t2 = {};
- table[k].push(t2);
- table = t2;
- } else {
- s += "." + stringify(table[k].length - 1);
- table = table[k][table[k].length - 1];
- }
- } else {
- if (!g_tables[s]) {
- error(genMsgRedefined(s));
- }
- table = table[k];
- }
- } else {
- if (isArray(table[k])) {
- if (!g_table_arrays[s] || i + 1 === l) {
- error(genMsgRedefined(s));
- }
- s += "." + stringify(table[k].length - 1);
- table = table[k][table[k].length - 1];
- } else {
- if (!g_tables[s]) {
- error(genMsgRedefined(s));
- }
- table = table[k];
- }
- }
- }
- }
- if (isTableArray) {
- if (!g_table_arrays[s]) {
- error(genMsgRedefined(s));
- }
- } else {
- if (g_defined_tables[s] || g_table_arrays[s]) {
- error(genMsgRedefined(s));
- }
- g_defined_tables[s] = true;
- }
- return {
- table,
- path
- };
- };
- var g_root = {};
- var g_context = {
- // current context
- table: g_root,
- path: []
- };
- var g_tables = {};
- var g_defined_tables = {};
- var g_table_arrays = {};
- peg$result = peg$startRuleFunction();
- if (peg$result !== peg$FAILED && peg$currPos === input.length) {
- return peg$result;
- } else {
- if (peg$result !== peg$FAILED && peg$currPos < input.length) {
- peg$fail(peg$endExpectation());
- }
- throw peg$buildStructuredError(
- peg$maxFailExpected,
- peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,
- peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)
- );
- }
- }
- return {
- SyntaxError: peg$SyntaxError,
- parse: peg$parse
- };
- }();
- }
- });
-
- // node_modules/@hoodmane/toml-j0.4/toml.js
- var require_toml = __commonJS({
- "node_modules/@hoodmane/toml-j0.4/toml.js"(exports, module) {
- "use strict";
- function subclass(child, parent) {
- function ctor() {
- this.constructor = child;
- }
- ctor.prototype = parent.prototype;
- child.prototype = new ctor();
- }
- function TomlSyntaxError(message, offset, line, column) {
- this.message = message;
- this.offset = offset;
- this.line = line;
- this.column = column;
- }
- subclass(TomlSyntaxError, SyntaxError);
- var parser2 = require_parser();
- var toml2 = {
- parse: function(src) {
- try {
- return parser2.parse(src);
- } catch (err) {
- if (err instanceof parser2.SyntaxError) {
- err.line = err.location.start.line;
- err.column = err.location.start.column;
- err.offset = err.location.start.offset;
- throw new TomlSyntaxError(
- err.message,
- err.location.start.offset,
- err.location.start.line,
- err.location.start.column
- );
- } else {
- throw err;
- }
- }
- },
- SyntaxError: TomlSyntaxError
- };
- module.exports = toml2;
- }
- });
-
- // src/main.ts
- var main_exports = {};
- __export(main_exports, {
- PyScriptApp: () => PyScriptApp,
- interpreter: () => interpreter,
- runtime: () => runtime,
- version: () => version
- });
-
- // node_modules/basic-devtools/esm/index.js
- var $ = (css, root = document) => root.querySelector(css);
- var $$ = (css, root = document) => [...root.querySelectorAll(css)];
- var $x = (path, root = document) => {
- const expression = new XPathEvaluator().createExpression(path);
- const xpath = expression.evaluate(root, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
- const result = [];
- for (let i = 0, { snapshotLength } = xpath; i < snapshotLength; i++)
- result.push(xpath.snapshotItem(i));
- return result;
- };
-
- // src/pyconfig.ts
- var import_toml_j0 = __toESM(require_toml());
-
- // src/logger.ts
- var _cache = /* @__PURE__ */ new Map();
- function getLogger(prefix) {
- let logger12 = _cache.get(prefix);
- if (logger12 === void 0) {
- logger12 = _makeLogger(prefix);
- _cache.set(prefix, logger12);
- }
- return logger12;
- }
- function _makeLogger(prefix) {
- prefix = `[${prefix}] `;
- function make(level) {
- const out_fn = console[level].bind(console);
- function fn(fmt, ...args) {
- out_fn(prefix + fmt, ...args);
- }
- return fn;
- }
- const debug = make("debug");
- const info = make("info");
- const warn = make("warn");
- const error = make("error");
- return { debug, info, warn, error };
- }
-
- // src/version.ts
- var version = "2022.12.1.dev";
-
- // src/exceptions.ts
- var CLOSEBUTTON = ``;
- var UserError = class extends Error {
- constructor(errorCode, message, messageType = "text") {
- super(`(${errorCode}): ${message}`);
- this.errorCode = errorCode;
- this.messageType = messageType;
- this.name = "UserError";
- this.$$isUserError = true;
- }
- };
- var FetchError = class extends UserError {
- constructor(errorCode, message) {
- super(errorCode, message);
- this.name = "FetchError";
- }
- };
- var InstallError = class extends UserError {
- constructor(errorCode, message) {
- super(errorCode, message);
- this.name = "InstallError";
- }
- };
- function _createAlertBanner(message, level = "error", messageType = "text", logMessage = true) {
- switch (`log-${level}-${logMessage}`) {
- case "log-error-true":
- console.error(message);
- break;
- case "log-warning-true":
- console.warn(message);
- break;
- }
- const content2 = messageType === "html" ? "innerHTML" : "textContent";
- const banner = Object.assign(document.createElement("div"), {
- className: `alert-banner py-${level}`,
- [content2]: message
- });
- if (level === "warning") {
- const closeButton = Object.assign(document.createElement("button"), {
- id: "alert-close-button",
- innerHTML: CLOSEBUTTON
- });
- banner.appendChild(closeButton).addEventListener("click", () => {
- banner.remove();
- });
- }
- document.body.prepend(banner);
- }
-
- // src/utils.ts
- function escape(str) {
- return str.replace(//g, ">");
- }
- function htmlDecode(input) {
- const doc2 = new DOMParser().parseFromString(ltrim(escape(input)), "text/html");
- return doc2.documentElement.textContent;
- }
- function ltrim(code) {
- const lines = code.split("\n");
- if (lines.length == 0)
- return code;
- const lengths = lines.filter((line) => line.trim().length != 0).map((line) => {
- return line.match(/^\s*/)?.pop()?.length;
- });
- const k = Math.min(...lengths);
- return k != 0 ? lines.map((line) => line.substring(k)).join("\n") : code;
- }
- var _uniqueIdCounter = 0;
- function ensureUniqueId(el) {
- if (el.id === "")
- el.id = `py-internal-${_uniqueIdCounter++}`;
- }
- function showWarning(msg, messageType = "text") {
- _createAlertBanner(msg, "warning", messageType);
- }
- function readTextFromPath(path) {
- const request = new XMLHttpRequest();
- request.open("GET", path, false);
- request.send();
- const returnValue = request.responseText;
- return returnValue;
- }
- function joinPaths(parts, separator = "/") {
- const res = parts.map(function(part) {
- return part.trim().replace(/(^[/]*|[/]*$)/g, "");
- }).filter((p) => p !== "" && p !== ".").join(separator || "/");
- if (parts[0].startsWith("/")) {
- return "/" + res;
- }
- return res;
- }
- function createDeprecationWarning(msg, elementName) {
- createSingularWarning(msg, elementName);
- }
- function createSingularWarning(msg, sentinelText) {
- const banners = $$(".alert-banner, .py-warning", document);
- let bannerCount = 0;
- for (const banner of banners) {
- if (banner.innerHTML.includes(sentinelText || msg)) {
- bannerCount++;
- }
- }
- if (bannerCount == 0) {
- _createAlertBanner(msg, "warning");
- }
- }
- function createLock() {
- let _lock = Promise.resolve();
- async function acquireLock() {
- const old_lock = _lock;
- let releaseLock;
- _lock = new Promise((resolve) => releaseLock = resolve);
- await old_lock;
- return releaseLock;
- }
- return acquireLock;
- }
-
- // src/pyconfig.ts
- var logger = getLogger("py-config");
- var allKeys = Object.entries({
- string: ["name", "description", "version", "type", "author_name", "author_email", "license", "execution_thread"],
- number: ["schema_version"],
- array: ["runtimes", "interpreters", "packages", "fetch", "plugins"]
- });
- var defaultConfig = {
- schema_version: 1,
- type: "app",
- interpreters: [
- {
- src: "https://cdn.jsdelivr.net/pyodide/v0.23.2/full/pyodide.js",
- name: "pyodide-0.23.2",
- lang: "python"
- }
- ],
- // This is for backward compatibility, we need to remove it in the future
- runtimes: [],
- packages: [],
- fetch: [],
- plugins: [],
- execution_thread: "main"
- };
- function loadConfigFromElement(el) {
- let srcConfig;
- let inlineConfig;
- if (el === null) {
- srcConfig = {};
- inlineConfig = {};
- } else {
- const configType = el.getAttribute("type") || "toml";
- srcConfig = extractFromSrc(el, configType);
- inlineConfig = extractFromInline(el, configType);
- }
- srcConfig = mergeConfig(srcConfig, defaultConfig);
- const result = mergeConfig(inlineConfig, srcConfig);
- result.pyscript = {
- version,
- time: (/* @__PURE__ */ new Date()).toISOString()
- };
- return result;
- }
- function extractFromSrc(el, configType) {
- const src = el.getAttribute("src");
- if (src) {
- logger.info("loading ", src);
- return validateConfig(readTextFromPath(src), configType);
- }
- return {};
- }
- function extractFromInline(el, configType) {
- if (el.innerHTML !== "") {
- logger.info("loading content");
- return validateConfig(htmlDecode(el.innerHTML), configType);
- }
- return {};
- }
- function fillUserData(inputConfig, resultConfig) {
- for (const key in inputConfig) {
- if (!(key in defaultConfig)) {
- resultConfig[key] = inputConfig[key];
- }
- }
- return resultConfig;
- }
- function mergeConfig(inlineConfig, externalConfig) {
- if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) {
- return defaultConfig;
- } else if (Object.keys(inlineConfig).length === 0) {
- return externalConfig;
- } else if (Object.keys(externalConfig).length === 0) {
- return inlineConfig;
- } else {
- let merged = {};
- for (const [keyType, keys2] of allKeys) {
- keys2.forEach(function(item) {
- if (keyType === "boolean") {
- merged[item] = typeof inlineConfig[item] !== "undefined" ? inlineConfig[item] : externalConfig[item];
- } else {
- merged[item] = inlineConfig[item] || externalConfig[item];
- }
- });
- }
- merged = fillUserData(externalConfig, merged);
- merged = fillUserData(inlineConfig, merged);
- return merged;
- }
- }
- function parseConfig(configText, configType = "toml") {
- if (configType === "toml") {
- if (configText.trim()[0] === "{") {
- throw new UserError(
- "PY1000" /* BAD_CONFIG */,
- `The config supplied: ${configText} is an invalid TOML and cannot be parsed`
- );
- }
- try {
- return import_toml_j0.default.parse(configText);
- } catch (e) {
- const err = e;
- const errMessage = err.toString();
- throw new UserError(
- "PY1000" /* BAD_CONFIG */,
- `The config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}`
- );
- }
- } else if (configType === "json") {
- try {
- return JSON.parse(configText);
- } catch (e) {
- const err = e;
- const errMessage = err.toString();
- throw new UserError(
- "PY1000" /* BAD_CONFIG */,
- `The config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}`
- );
- }
- } else {
- throw new UserError(
- "PY1000" /* BAD_CONFIG */,
- `The type of config supplied '${configType}' is not supported, supported values are ["toml", "json"]`
- );
- }
- }
- function validateConfig(configText, configType = "toml") {
- const config2 = parseConfig(configText, configType);
- const finalConfig = {};
- for (const [keyType, keys2] of allKeys) {
- keys2.forEach(function(item) {
- if (validateParamInConfig(item, keyType, config2)) {
- if (item === "interpreters") {
- finalConfig[item] = [];
- const interpreters = config2[item];
- interpreters.forEach(function(eachInterpreter) {
- const interpreterConfig = {};
- for (const eachInterpreterParam in eachInterpreter) {
- if (validateParamInConfig(eachInterpreterParam, "string", eachInterpreter)) {
- interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam];
- }
- }
- finalConfig[item].push(interpreterConfig);
- });
- } else if (item === "runtimes") {
- createDeprecationWarning(
- "The configuration option `config.runtimes` is deprecated. Please use `config.interpreters` instead.",
- ""
- );
- finalConfig["interpreters"] = [];
- const interpreters = config2[item];
- interpreters.forEach(function(eachInterpreter) {
- const interpreterConfig = {};
- for (const eachInterpreterParam in eachInterpreter) {
- if (validateParamInConfig(eachInterpreterParam, "string", eachInterpreter)) {
- interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam];
- }
- }
- finalConfig["interpreters"].push(interpreterConfig);
- });
- } else if (item === "fetch") {
- finalConfig[item] = [];
- const fetchList = config2[item];
- fetchList.forEach(function(eachFetch) {
- const eachFetchConfig = {};
- for (const eachFetchConfigParam in eachFetch) {
- const targetType = eachFetchConfigParam === "files" ? "array" : "string";
- if (validateParamInConfig(eachFetchConfigParam, targetType, eachFetch)) {
- eachFetchConfig[eachFetchConfigParam] = eachFetch[eachFetchConfigParam];
- }
- }
- finalConfig[item].push(eachFetchConfig);
- });
- } else if (item == "execution_thread") {
- const value = config2[item];
- if (value !== "main" && value !== "worker") {
- throw new UserError(
- "PY1000" /* BAD_CONFIG */,
- `"${value}" is not a valid value for the property "execution_thread". The only valid values are "main" and "worker"`
- );
- }
- finalConfig[item] = value;
- } else {
- finalConfig[item] = config2[item];
- }
- }
- });
- }
- return fillUserData(config2, finalConfig);
- }
- function validateParamInConfig(paramName, paramType, config2) {
- if (paramName in config2) {
- return paramType === "array" ? Array.isArray(config2[paramName]) : typeof config2[paramName] === paramType;
- }
- return false;
- }
-
- // node_modules/synclink/dist/esm/synclink.mjs
- var synclink_exports = {};
- __export(synclink_exports, {
- FakeMessageChannel: () => FakeMessageChannel,
- Syncifier: () => Syncifier,
- createEndpoint: () => createEndpoint,
- expose: () => expose,
- interrupt_buffer: () => interrupt_buffer,
- proxy: () => proxy,
- proxyMarker: () => proxyMarker,
- releaseProxy: () => releaseProxy,
- setInterruptHandler: () => setInterruptHandler,
- transfer: () => transfer,
- transferHandlers: () => transferHandlers,
- windowEndpoint: () => windowEndpoint,
- wrap: () => wrap
- });
- var __defProp2 = Object.defineProperty;
- var __defProps = Object.defineProperties;
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
- var __pow = Math.pow;
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
- var __spreadValues = (a, b) => {
- for (var prop in b ||= {})
- if (__hasOwnProp2.call(b, prop))
- __defNormalProp(a, prop, b[prop]);
- if (__getOwnPropSymbols)
- for (var prop of __getOwnPropSymbols(b)) {
- if (__propIsEnum.call(b, prop))
- __defNormalProp(a, prop, b[prop]);
- }
- return a;
- };
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
- var __name = (target, value) => __defProp2(target, "name", { value, configurable: true });
- var __async = (__this, __arguments, generator) => {
- return new Promise((resolve, reject) => {
- var fulfilled = (value) => {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- };
- var rejected = (value) => {
- try {
- step(generator.throw(value));
- } catch (e) {
- reject(e);
- }
- };
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
- step((generator = generator.apply(__this, __arguments)).next());
- });
- };
- var wireValueTypeRecord = {
- [
- "RAW"
- /* RAW */
- ]: 1,
- [
- "PROXY"
- /* PROXY */
- ]: 1,
- [
- "THROW"
- /* THROW */
- ]: 1,
- [
- "HANDLER"
- /* HANDLER */
- ]: 1,
- [
- "ID"
- /* ID */
- ]: 1
- };
- var wireValueTypeSet = new Set(
- Object.keys(wireValueTypeRecord)
- );
- var messageTypeRecord = {
- [
- "SET"
- /* SET */
- ]: 1,
- [
- "GET"
- /* GET */
- ]: 1,
- [
- "APPLY"
- /* APPLY */
- ]: 1,
- [
- "CONSTRUCT"
- /* CONSTRUCT */
- ]: 1,
- [
- "ENDPOINT"
- /* ENDPOINT */
- ]: 1,
- [
- "RELEASE"
- /* RELEASE */
- ]: 1,
- [
- "DESTROY"
- /* DESTROY */
- ]: 1
- };
- var messageTypeSet = new Set(Object.keys(messageTypeRecord));
- function requestResponseMessageInner(ep) {
- const id2 = generateUUID();
- return [
- id2,
- new Promise((resolve) => {
- ep.addEventListener("message", /* @__PURE__ */ __name(function l(ev) {
- if (!ev.data || !ev.data.id || ev.data.id !== id2) {
- return;
- }
- ep.removeEventListener("message", l);
- resolve(ev.data);
- }, "l"));
- if (ep.start) {
- ep.start();
- }
- })
- ];
- }
- __name(requestResponseMessageInner, "requestResponseMessageInner");
- function requestResponseMessage(ep, msg, transfers) {
- let [id2, promise] = requestResponseMessageInner(ep);
- ep.postMessage(__spreadValues({ id: id2 }, msg), transfers);
- return promise;
- }
- __name(requestResponseMessage, "requestResponseMessage");
- var UUID_LENGTH = 63;
- function randomSegment() {
- let result = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16);
- let pad = 15 - result.length;
- if (pad > 0) {
- result = Array.from({ length: pad }, (_) => 0).join("") + result;
- }
- return result;
- }
- __name(randomSegment, "randomSegment");
- function generateUUID() {
- let result = Array.from({ length: 4 }, randomSegment).join("-");
- if (result.length !== UUID_LENGTH) {
- throw new Error("synclink internal error: UUID has the wrong length");
- }
- return result;
- }
- __name(generateUUID, "generateUUID");
- var createEndpoint = Symbol("Synclink.endpoint");
- var releaseProxy = Symbol("Synclink.releaseProxy");
- var proxyMarker = Symbol("Synclink.proxy");
- var temp;
- if (typeof SharedArrayBuffer === "undefined") {
- temp = ArrayBuffer;
- } else {
- temp = SharedArrayBuffer;
- }
- var shared_array_buffer_default = temp;
- var decoder = new TextDecoder("utf-8");
- var encoder = new TextEncoder();
- var SZ_BUF_SIZE_IDX = 0;
- var SZ_BUF_FITS_IDX = 1;
- var SZ_BUF_DOESNT_FIT = 0;
- function sleep(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms));
- }
- __name(sleep, "sleep");
- var SynclinkTask = class {
- constructor(endpoint, msg, transfers = [], extra = () => {
- }) {
- this.endpoint = endpoint;
- this.msg = msg;
- this.extra = extra;
- this.transfers = transfers;
- this._resolved = false;
- this._promise = new Promise((resolve, reject) => {
- this._resolve = resolve;
- this._reject = reject;
- });
- }
- schedule_async() {
- if (this.mode === "async") {
- return this;
- }
- if (this.mode === "sync") {
- throw new Error("Already synchronously scheduled");
- }
- this.mode = "async";
- this.do_async().then(
- (value) => {
- this._resolved = true;
- this._result = value;
- this._resolve(value);
- },
- (reason) => {
- this._exception = reason;
- this._reject(reason);
- }
- );
- return this;
- }
- then(onfulfilled, onrejected) {
- return __async(this, null, function* () {
- this.schedule_async();
- return this._promise.then(onfulfilled, onrejected);
- });
- }
- catch(onrejected) {
- this.schedule_async();
- return this._promise.catch(onrejected);
- }
- finally(onfinally) {
- this.schedule_async();
- return this._promise.finally(onfinally);
- }
- schedule_sync() {
- if (this.mode === "sync") {
- return this;
- }
- if (this.mode === "async") {
- throw new Error("Already asynchronously scheduled");
- }
- this.mode = "sync";
- Syncifier.scheduleTask(this);
- this._sync_gen = this.do_sync();
- this._sync_gen.next();
- return this;
- }
- isResolved() {
- return this._resolved;
- }
- poll() {
- if (this.mode != "sync") {
- throw new Error("Task not synchronously scheduled");
- }
- let { done, value } = this._sync_gen.next();
- if (!done) {
- return false;
- }
- try {
- this._resolved = true;
- this._result = fromWireValue(this.endpoint, value);
- } catch (e) {
- console.warn("synclink exception:", e);
- this._exception = e;
- }
- return true;
- }
- *do_sync() {
- let { endpoint, msg, transfers } = this;
- let size_buffer = new Int32Array(new shared_array_buffer_default(8));
- let signal_buffer = this.signal_buffer;
- let taskId = this.taskId;
- let data_buffer = acquireDataBuffer(UUID_LENGTH);
- endpoint.postMessage(
- __spreadProps(__spreadValues({}, msg), {
- size_buffer,
- data_buffer,
- signal_buffer,
- taskId,
- syncify: true
- }),
- transfers
- );
- yield;
- if (Atomics.load(size_buffer, SZ_BUF_FITS_IDX) === SZ_BUF_DOESNT_FIT) {
- const id2 = decoder.decode(data_buffer.slice(0, UUID_LENGTH));
- releaseDataBuffer(data_buffer);
- const size2 = Atomics.load(size_buffer, SZ_BUF_SIZE_IDX);
- data_buffer = acquireDataBuffer(size2);
- endpoint.postMessage({ id: id2, data_buffer });
- yield;
- }
- const size = Atomics.load(size_buffer, SZ_BUF_SIZE_IDX);
- return JSON.parse(decoder.decode(data_buffer.slice(0, size)));
- }
- do_async() {
- return __async(this, null, function* () {
- let result = yield requestResponseMessage(
- this.endpoint,
- this.msg,
- this.transfers
- );
- this.extra();
- return fromWireValue(this.endpoint, result);
- });
- }
- get result() {
- if (this._exception) {
- throw this._exception;
- }
- if (this.isResolved()) {
- return this._result;
- }
- throw new Error("Not ready.");
- }
- syncify() {
- this.schedule_sync();
- Syncifier.syncifyTask(this);
- return this.result;
- }
- };
- __name(SynclinkTask, "SynclinkTask");
- function signalRequester(signal_buffer, taskId) {
- return __async(this, null, function* () {
- let index = (taskId >> 1) % 32;
- let sleepTime = 1;
- while (Atomics.compareExchange(signal_buffer, index + 1, 0, taskId) !== 0) {
- yield sleep(sleepTime);
- if (sleepTime < 32) {
- sleepTime *= 2;
- }
- }
- Atomics.or(signal_buffer, 0, 1 << index);
- Atomics.notify(signal_buffer, 0);
- });
- }
- __name(signalRequester, "signalRequester");
- function syncResponse(endpoint, msg, returnValue) {
- return __async(this, null, function* () {
- try {
- let { size_buffer, data_buffer, signal_buffer, taskId } = msg;
- let bytes = encoder.encode(JSON.stringify(returnValue));
- let fits = bytes.length <= data_buffer.length;
- Atomics.store(size_buffer, SZ_BUF_SIZE_IDX, bytes.length);
- Atomics.store(size_buffer, SZ_BUF_FITS_IDX, +fits);
- if (!fits) {
- let [uuid, data_promise] = requestResponseMessageInner(endpoint);
- data_buffer.set(encoder.encode(uuid));
- yield signalRequester(signal_buffer, taskId);
- data_buffer = (yield data_promise).data_buffer;
- }
- data_buffer.set(bytes);
- Atomics.store(size_buffer, SZ_BUF_FITS_IDX, 1);
- yield signalRequester(signal_buffer, taskId);
- } catch (e) {
- console.warn(e);
- }
- });
- }
- __name(syncResponse, "syncResponse");
- var dataBuffers = [];
- function acquireDataBuffer(size) {
- let powerof2 = Math.ceil(Math.log2(size));
- if (!dataBuffers[powerof2]) {
- dataBuffers[powerof2] = [];
- }
- let result = dataBuffers[powerof2].pop();
- if (result) {
- result.fill(0);
- return result;
- }
- return new Uint8Array(new shared_array_buffer_default(__pow(2, powerof2)));
- }
- __name(acquireDataBuffer, "acquireDataBuffer");
- function releaseDataBuffer(buffer) {
- let powerof2 = Math.ceil(Math.log2(buffer.byteLength));
- dataBuffers[powerof2].push(buffer);
- }
- __name(releaseDataBuffer, "releaseDataBuffer");
- var interrupt_buffer = new Int32Array(new shared_array_buffer_default(4));
- var handleInterrupt = /* @__PURE__ */ __name(() => {
- interrupt_buffer[0] = 0;
- throw new Error("Interrupted!");
- }, "handleInterrupt");
- function setInterruptHandler(handler) {
- handleInterrupt = handler;
- }
- __name(setInterruptHandler, "setInterruptHandler");
- var _Syncifier = class {
- constructor() {
- this.nextTaskId = new Int32Array([1]);
- this.signal_buffer = new Int32Array(new shared_array_buffer_default(32 * 4 + 4));
- this.tasks = /* @__PURE__ */ new Map();
- }
- scheduleTask(task) {
- task.taskId = this.nextTaskId[0];
- this.nextTaskId[0] += 2;
- task.signal_buffer = this.signal_buffer;
- this.tasks.set(task.taskId, task);
- }
- waitOnSignalBuffer() {
- let timeout = 50;
- while (true) {
- let status = Atomics.wait(this.signal_buffer, 0, 0, timeout);
- switch (status) {
- case "ok":
- case "not-equal":
- return;
- case "timed-out":
- if (interrupt_buffer[0] !== 0) {
- handleInterrupt();
- }
- break;
- default:
- throw new Error("Unreachable");
- }
- }
- }
- *tasksIdsToWakeup() {
- let flag = Atomics.load(this.signal_buffer, 0);
- for (let i = 0; i < 32; i++) {
- let bit = 1 << i;
- if (flag & bit) {
- Atomics.and(this.signal_buffer, 0, ~bit);
- let wokenTask = Atomics.exchange(this.signal_buffer, i + 1, 0);
- yield wokenTask;
- }
- }
- }
- pollTasks(task) {
- let result = false;
- for (let wokenTaskId of this.tasksIdsToWakeup()) {
- let wokenTask = this.tasks.get(wokenTaskId);
- if (!wokenTask) {
- throw new Error(`Assertion error: unknown taskId ${wokenTaskId}.`);
- }
- if (wokenTask.poll()) {
- this.tasks.delete(wokenTaskId);
- if (wokenTask === task) {
- result = true;
- }
- }
- }
- return result;
- }
- syncifyTask(task) {
- while (true) {
- if (this.pollTasks(task)) {
- return;
- }
- if (task.endpoint._bypass) {
- throw new Error("oops!");
- }
- this.waitOnSignalBuffer();
- }
- }
- };
- __name(_Syncifier, "_Syncifier");
- var Syncifier = new _Syncifier();
- (/* @__PURE__ */ __name(function syncifyPollLoop() {
- return __async(this, null, function* () {
- while (true) {
- Syncifier.pollTasks();
- yield sleep(20);
- }
- });
- }, "syncifyPollLoop"))();
- function innerMessageHandler(obj_arg, ep, message) {
- const { id: id2, path, store_key } = __spreadValues({
- path: [],
- store_key: void 0
- }, message);
- let obj;
- if (store_key) {
- obj = storeGetValue(ep, store_key);
- } else {
- obj = obj_arg;
- }
- if (obj_arg === void 0 && store_key === void 0) {
- console.warn(obj_arg, message);
- throw new Error("Internal synclink error!");
- }
- const argumentList = (message.argumentList || []).map((v) => {
- if (v.type === "PROXY") {
- return innerMessageHandler(obj_arg, ep, v.message);
- } else {
- return fromWireValue(ep, v);
- }
- });
- const last = path.pop();
- let parent = path.reduce((obj2, prop) => obj2[prop], obj);
- const rawValue = last ? parent[last] : obj;
- if (!last) {
- parent = void 0;
- }
- if (rawValue === void 0) {
- switch (message.type) {
- case "GET":
- case "SET":
- break;
- default:
- console.warn("Undefined", obj, path, last);
- throw new Error(`undefined!! ${obj}, ${path}, ${last}`);
- }
- }
- switch (message.type) {
- case "GET":
- {
- return rawValue;
- }
- break;
- case "SET":
- {
- parent[last] = fromWireValue(ep, message.value);
- return true;
- }
- break;
- case "APPLY":
- {
- if (last) {
- return parent[last].apply(parent, argumentList);
- } else {
- return rawValue.apply(parent, argumentList);
- }
- }
- break;
- case "CONSTRUCT":
- {
- const value = new rawValue(...argumentList);
- return proxy(value);
- }
- break;
- case "ENDPOINT":
- {
- const { port1, port2 } = new MessageChannel();
- expose(obj, port2);
- return transfer(port1, [port1]);
- }
- break;
- case "RELEASE":
- {
- return void 0;
- }
- break;
- case "DESTROY":
- {
- storeDeleteKey(ep, store_key);
- return void 0;
- }
- break;
- default:
- return void 0;
- }
- }
- __name(innerMessageHandler, "innerMessageHandler");
- function expose(obj_arg, ep = globalThis) {
- const wrap2 = false;
- exposeInner(obj_arg, ep, wrap2);
- }
- __name(expose, "expose");
- function exposeInner(obj_arg, ep = globalThis, wrap2) {
- storeCreate(ep);
- ep.addEventListener("message", /* @__PURE__ */ __name(function callback(ev) {
- return __async(this, null, function* () {
- if (!ev || !ev.data) {
- return;
- }
- if (!messageTypeSet.has(ev.data.type)) {
- if (!wireValueTypeSet.has(ev.data.type) && !ev.data.data_buffer) {
- console.warn("Internal error on message:", ev.data);
- throw new Error(
- `Synclink Internal error: Expected message.type to either be a MessageType or a WireValueType, got '${ev.data.type}'`
- );
- }
- return;
- }
- const message = ev.data;
- const { id: id2, type, store_key } = __spreadValues({ store_key: void 0 }, message);
- if (wrap2 && store_key === void 0) {
- return;
- }
- const sync = ev.data.syncify;
- let returnValue;
- try {
- returnValue = innerMessageHandler(obj_arg, ep, message);
- if (returnValue && returnValue.then) {
- if (sync && ep._bypass) {
- throw new Error("Cannot use syncify with bypass on an async method");
- }
- returnValue = yield returnValue;
- }
- } catch (value) {
- returnValue = { value, [throwMarker]: 0 };
- }
- const [wireValue, transferables] = toWireValue(ep, returnValue);
- if (sync) {
- syncResponse(ep, ev.data, wireValue);
- } else {
- ep.postMessage(__spreadProps(__spreadValues({}, wireValue), { id: id2 }), transferables);
- }
- if (type === "RELEASE") {
- ep.removeEventListener("message", callback);
- closeEndPoint(ep);
- }
- });
- }, "callback"));
- if (ep.start) {
- ep.start();
- }
- }
- __name(exposeInner, "exposeInner");
- function isMessagePort(endpoint) {
- return endpoint.constructor.name === "MessagePort";
- }
- __name(isMessagePort, "isMessagePort");
- function closeEndPoint(endpoint) {
- if (isMessagePort(endpoint))
- endpoint.close();
- }
- __name(closeEndPoint, "closeEndPoint");
- function wrap(ep, target) {
- const wrap2 = true;
- exposeInner(void 0, ep, wrap2);
- return createProxy(ep, { target });
- }
- __name(wrap, "wrap");
- function throwIfProxyReleased(isReleased) {
- if (isReleased) {
- throw new Error("Proxy has been released and is not usable");
- }
- }
- __name(throwIfProxyReleased, "throwIfProxyReleased");
- function createProxy(ep, {
- store_key = void 0,
- path = [],
- target = /* @__PURE__ */ __name(function() {
- }, "target")
- }) {
- let isProxyReleased = false;
- const proxy2 = new Proxy(target, {
- get(_target, prop) {
- throwIfProxyReleased(isProxyReleased);
- switch (prop) {
- case "$$ep":
- return ep;
- case Symbol.toStringTag:
- return "SynclinkProxy";
- case releaseProxy:
- return () => {
- return new SynclinkTask(
- ep,
- {
- type: "RELEASE",
- path: path.map((p) => p.toString())
- },
- [],
- () => {
- closeEndPoint(ep);
- isProxyReleased = true;
- }
- );
- };
- case "__destroy__":
- if (!store_key) {
- return () => {
- };
- }
- return () => {
- return new SynclinkTask(
- ep,
- {
- type: "DESTROY",
- store_key
- },
- [],
- () => {
- isProxyReleased = true;
- }
- );
- };
- case "_as_message":
- return () => {
- return {
- type: "GET",
- store_key,
- path: path.map((p) => p.toString())
- };
- };
- case "then":
- case "schedule_async":
- case "schedule_sync":
- case "syncify":
- if (path.length === 0 && prop === "then") {
- return { then: () => proxy2 };
- }
- let r = new SynclinkTask(
- ep,
- {
- type: "GET",
- store_key,
- path: path.map((p) => p.toString())
- },
- [],
- void 0
- );
- return r[prop].bind(r);
- default:
- return createProxy(ep, { store_key, path: [...path, prop] });
- }
- },
- set(_target, prop, rawValue) {
- throwIfProxyReleased(isProxyReleased);
- const [value, transferables] = toWireValue(ep, rawValue);
- return requestResponseMessage(
- ep,
- {
- type: "SET",
- store_key,
- path: [...path, prop].map((p) => p.toString()),
- value
- },
- transferables
- ).then((v) => fromWireValue(ep, v));
- },
- apply(_target, _thisArg, rawArgumentList) {
- throwIfProxyReleased(isProxyReleased);
- const last = path[path.length - 1];
- if (last === createEndpoint) {
- return requestResponseMessage(ep, {
- type: "ENDPOINT"
- /* ENDPOINT */
- }).then((v) => fromWireValue(ep, v));
- }
- if (last === "bind") {
- return createProxy(ep, { store_key, path: path.slice(0, -1) });
- }
- if (last === "apply") {
- rawArgumentList = rawArgumentList[1];
- path = path.slice(0, -1);
- }
- const [argumentList, transferables] = processArguments(
- ep,
- rawArgumentList
- );
- return new SynclinkTask(
- ep,
- {
- type: "APPLY",
- store_key,
- path: path.map((p) => p.toString()),
- argumentList
- },
- transferables,
- void 0
- );
- },
- construct(_target, rawArgumentList) {
- throwIfProxyReleased(isProxyReleased);
- const [argumentList, transferables] = processArguments(
- ep,
- rawArgumentList
- );
- return requestResponseMessage(
- ep,
- {
- type: "CONSTRUCT",
- store_key,
- path: path.map((p) => p.toString()),
- argumentList
- },
- transferables
- ).then((v) => fromWireValue(ep, v));
- },
- ownKeys(_target) {
- return [];
- }
- });
- return proxy2;
- }
- __name(createProxy, "createProxy");
- function myFlat(arr) {
- return Array.prototype.concat.apply([], arr);
- }
- __name(myFlat, "myFlat");
- function processArguments(ep, argumentList) {
- const processed = argumentList.map((v) => toWireValue(ep, v));
- return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
- }
- __name(processArguments, "processArguments");
- function windowEndpoint(w, context = self, targetOrigin = "*") {
- return {
- postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),
- addEventListener: context.addEventListener.bind(context),
- removeEventListener: context.removeEventListener.bind(context)
- };
- }
- __name(windowEndpoint, "windowEndpoint");
- var FakeMessagePort = class {
- constructor() {
- this._handlers = [];
- this._bypass = true;
- this._otherPort = this;
- }
- start() {
- }
- close() {
- }
- addEventListener(event, handler) {
- if (event === "message") {
- this._handlers.push(handler);
- }
- }
- removeEventListener(event, handler) {
- if (event !== "message") {
- return;
- }
- let idx = this._handlers.indexOf(handler);
- if (idx >= 0) {
- this._handlers.splice(idx, 1);
- }
- }
- postMessage(message, transfer2) {
- for (const h of this._otherPort._handlers) {
- h({ data: message });
- }
- }
- };
- __name(FakeMessagePort, "FakeMessagePort");
- var FakeMessageChannel = class {
- constructor() {
- this.port1 = new FakeMessagePort();
- this.port2 = new FakeMessagePort();
- this.port1._otherPort = this.port2;
- this.port2._otherPort = this.port1;
- }
- };
- __name(FakeMessageChannel, "FakeMessageChannel");
- var throwMarker = Symbol("Synclink.thrown");
- var transferCache = /* @__PURE__ */ new WeakMap();
- function transfer(obj, transfers) {
- transferCache.set(obj, transfers);
- return obj;
- }
- __name(transfer, "transfer");
- var isObject = /* @__PURE__ */ __name((val) => typeof val === "object" && val !== null || typeof val === "function", "isObject");
- var transferHandlers = /* @__PURE__ */ new Map();
- function isArrayBufferOrView(obj) {
- return ArrayBuffer.isView(obj) || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";
- }
- __name(isArrayBufferOrView, "isArrayBufferOrView");
- function isPlain(val) {
- return !val || typeof val === "string" || typeof val === "boolean" || typeof val === "number" || Array.isArray(val) || isArrayBufferOrView(val) || !val.constructor || val.constructor === Object && Object.prototype.toString.call(val) === "[object Object]";
- }
- __name(isPlain, "isPlain");
- function isSerializable(obj, transfers = []) {
- if (transfers.includes(obj)) {
- return true;
- }
- if (!isPlain(obj)) {
- return false;
- }
- for (var property in obj) {
- if (obj.hasOwnProperty(property)) {
- if (!isPlain(obj[property])) {
- return false;
- }
- if (typeof obj[property] == "object") {
- if (!isSerializable(obj[property], transfers)) {
- return false;
- }
- }
- }
- }
- return true;
- }
- __name(isSerializable, "isSerializable");
- var throwTransferHandler = {
- canHandle: (value) => isObject(value) && throwMarker in value,
- serialize({ value }) {
- let serialized;
- if (value instanceof Error) {
- serialized = {
- isError: true,
- value: {
- message: value.message,
- name: value.name,
- stack: value.stack
- }
- };
- } else {
- serialized = { isError: false, value };
- }
- return [serialized, []];
- },
- deserialize(serialized) {
- if (serialized.isError) {
- throw Object.assign(
- new Error(serialized.value.message),
- serialized.value
- );
- }
- throw serialized.value;
- }
- };
- function toWireValue(ep, value) {
- if (value && value.$$ep === ep) {
- return [
- {
- type: "PROXY",
- message: value._as_message()
- },
- []
- ];
- }
- if (value && value.constructor && value.constructor.name === "SynclinkTask") {
- return [
- {
- type: "PROXY",
- message: value.msg
- },
- []
- ];
- }
- if (ep._bypass) {
- proxyFakeMessagePort = true;
- }
- try {
- for (const [name2, handler] of transferHandlers) {
- if (handler.canHandle(value)) {
- const [serializedValue, transferables] = handler.serialize(value);
- return [
- {
- type: "HANDLER",
- name: name2,
- value: serializedValue
- },
- transferables
- ];
- }
- }
- } finally {
- proxyFakeMessagePort = false;
- }
- if (isSerializable(value, transferCache.get(value))) {
- return [
- {
- type: "RAW",
- value
- },
- transferCache.get(value) || []
- ];
- }
- let store_key = storeNewValue(ep, value);
- return [
- {
- type: "ID",
- store_key,
- endpoint_uuid: ep[endpointUUID],
- ownkeys: Object.getOwnPropertyNames(value)
- },
- []
- ];
- }
- __name(toWireValue, "toWireValue");
- function fromWireValue(ep, value) {
- switch (value.type) {
- case "HANDLER":
- return transferHandlers.get(value.name).deserialize(value.value);
- case "RAW":
- return value.value;
- case "ID":
- let this_uuid = ep[endpointUUID];
- if (this_uuid === value.endpoint_uuid) {
- return storeGetValue(ep, value.store_key);
- } else {
- return createProxy(ep, { store_key: value.store_key });
- }
- }
- }
- __name(fromWireValue, "fromWireValue");
- var proxyStore = Symbol("Synclink.proxyStore");
- var endpointUUID = Symbol("Synclink.endpointUUID");
- function storeCreate(obj) {
- if (proxyStore in obj) {
- return;
- }
- obj[proxyStore] = { objects: /* @__PURE__ */ new Map(), counter: new Uint32Array([1]) };
- obj[endpointUUID] = generateUUID();
- }
- __name(storeCreate, "storeCreate");
- function storeGetValue(obj, key) {
- return obj[proxyStore].objects.get(key);
- }
- __name(storeGetValue, "storeGetValue");
- function storeNewValue(obj, value) {
- if (!(proxyStore in obj)) {
- storeCreate(obj);
- }
- let { objects, counter } = obj[proxyStore];
- while (objects.has(counter[0])) {
- counter[0] += 2;
- }
- let key = counter[0];
- counter[0] += 2;
- objects.set(key, value);
- return key;
- }
- __name(storeNewValue, "storeNewValue");
- function storeDeleteKey(obj, key) {
- let { objects } = obj[proxyStore];
- objects.delete(key);
- console.log("deleted", key, objects);
- }
- __name(storeDeleteKey, "storeDeleteKey");
- function proxy(obj) {
- return Object.assign(obj, { [proxyMarker]: true });
- }
- __name(proxy, "proxy");
- var proxyFakeMessagePort = false;
- var proxyTransferHandler = {
- canHandle: (val) => isObject(val) && val[proxyMarker],
- serialize(obj) {
- const { port1, port2 } = proxyFakeMessagePort ? new FakeMessageChannel() : new MessageChannel();
- expose(obj, port1);
- return [port2, [port2]];
- },
- deserialize(port) {
- port.start();
- return wrap(port);
- }
- };
- transferHandlers.set("throw", throwTransferHandler);
- transferHandlers.set("proxy", proxyTransferHandler);
- transferHandlers.set("headers", {
- canHandle(value) {
- return Object.prototype.toString.call(value) === "[object Headers]";
- },
- serialize(value) {
- return [Array.from(value), []];
- },
- deserialize(value) {
- return new Headers(value);
- }
- });
-
- // src/interpreter_client.ts
- var logger2 = getLogger("pyscript/interpreter");
- var InterpreterClient = class extends Object {
- constructor(config2, stdio, remote) {
- super();
- this.config = config2;
- this._remote = remote;
- this.stdio = stdio;
- }
- /**
- * initializes the remote interpreter, which further loads the underlying
- * interface.
- */
- async initializeRemote() {
- await this._remote.loadInterpreter(this.config, proxy(this.stdio));
- this.globals = this._remote.globals;
- }
- /**
- * Run user Python code. See also the _run_pyscript docstring.
- *
- * The result is wrapped in an object to avoid accidentally awaiting a
- * Python Task or Future returned as the result of the computation.
- *
- * @param code the code to run
- * @param id The id for the default display target (or undefined if no
- * default display target).
- * @returns Either:
- * 1. An Object of the form {result: the_result} if the result is
- * serializable (or transferable), or
- * 2. a Synclink Proxy wrapping an object of this if the result is not
- * serializable.
- */
- async run(code, id2) {
- return this._remote.pyscript_internal.run_pyscript(code, id2);
- }
- /**
- * Same as run, but Python exceptions are not propagated: instead, they
- * are logged to the console.
- *
- * This is a bad API and should be killed/refactored/changed eventually,
- * but for now we have code which relies on it.
- * */
- async runButDontRaise(code) {
- let result;
- try {
- result = (await this.run(code)).result;
- } catch (error) {
- logger2.error("Error:", error);
- }
- return result;
- }
- async pyimport(mod_name) {
- return this._remote.pyimport(mod_name);
- }
- async mkdir(path) {
- await this._remote.FS.mkdir(path);
- }
- async writeFile(path, content2) {
- await this._remote.FS.writeFile(path, content2, { encoding: "utf8" });
- }
- };
-
- // src/plugin.ts
- var logger3 = getLogger("plugin");
- var Plugin = class {
- /** Validate the configuration of the plugin and handle default values.
- *
- * Individual plugins are expected to check that the config keys/sections
- * which are relevant to them contains valid values, and to raise an error
- * if they contains unknown keys.
- *
- * This is also a good place where set default values for those keys which
- * are not specified by the user.
- *
- * This hook should **NOT** contain expensive operations, else it delays
- * the download of the python interpreter which is initiated later.
- */
- configure(_config) {
- }
- /** The preliminary initialization phase is complete and we are about to
- * download and launch the Python interpreter.
- *
- * We can assume that the page is already shown to the user and that the
- * DOM content has been loaded. This is a good place where to add tags to
- * the DOM, if needed.
- *
- * This hook should **NOT** contain expensive operations, else it delays
- * the download of the python interpreter which is initiated later.
- */
- beforeLaunch(_config) {
- }
- /** The Python interpreter has been launched, the virtualenv has been
- * installed and we are ready to execute user code.
- *
- * The tags will be executed after this hook.
- */
- afterSetup(_interpreter) {
- }
- /** The source of a > tag has been fetched, and we're about
- * to evaluate that source using the provided interpreter.
- *
- * @param options.interpreter The Interpreter object that will be used to evaluate the Python source code
- * @param options.src {string} The Python source code to be evaluated
- * @param options.pyScriptTag The HTML tag that originated the evaluation
- */
- beforePyScriptExec(_options) {
- }
- /** The Python in a has just been evaluated, but control
- * has not been ceded back to the JavaScript event loop yet
- *
- * @param options.interpreter The Interpreter object that will be used to evaluate the Python source code
- * @param options.src {string} The Python source code to be evaluated
- * @param options.pyScriptTag The HTML tag that originated the evaluation
- * @param options.result The returned result of evaluating the Python (if any)
- */
- afterPyScriptExec(_options) {
- }
- /** The source of the tag has been fetched and its output-element determined;
- * we're about to evaluate the source using the provided interpreter
- *
- * @param options.interpreter The interpreter object that will be used to evaluated the Python source code
- * @param options.src {string} The Python source code to be evaluated
- * @param options.outEl The element that the result of the REPL evaluation will be output to.
- * @param options.pyReplTag The HTML tag the originated the evaluation
- */
- beforePyReplExec(options) {
- }
- /**
- *
- * @param options.interpreter The interpreter object that will be used to evaluated the Python source code
- * @param options.src {string} The Python source code to be evaluated
- * @param options.outEl The element that the result of the REPL evaluation will be output to.
- * @param options.pyReplTag The HTML tag the originated the evaluation
- * @param options.result The result of evaluating the Python (if any)
- */
- afterPyReplExec(options) {
- }
- /** Startup complete. The interpreter is initialized and ready, user
- * scripts have been executed: the main initialization logic ends here and
- * the page is ready to accept user interactions.
- */
- afterStartup(_interpreter) {
- }
- /** Called when an UserError is raised
- */
- onUserError(_error) {
- }
- };
- var PluginManager = class {
- constructor() {
- this._plugins = [];
- this._pythonPlugins = [];
- }
- add(...plugins) {
- this._plugins.push(...plugins);
- }
- addPythonPlugin(plugin) {
- this._pythonPlugins.push(plugin);
- }
- async configure(config2) {
- const fn = (p) => p.configure?.(config2);
- await Promise.all(this._plugins.map(fn));
- await Promise.all(this._pythonPlugins.map(fn));
- }
- beforeLaunch(config2) {
- for (const p of this._plugins) {
- try {
- p?.beforeLaunch?.(config2);
- } catch (e) {
- logger3.error(`Error while calling beforeLaunch hook of plugin ${p.constructor.name}`, e);
- }
- }
- }
- async afterSetup(interpreter2) {
- const promises = [];
- for (const p of this._plugins) {
- try {
- promises.push(p.afterSetup?.(interpreter2));
- } catch (e) {
- logger3.error(`Error while calling afterSetup hook of plugin ${p.constructor.name}`, e);
- }
- }
- await Promise.all(promises);
- for (const p of this._pythonPlugins)
- await p.afterSetup?.(interpreter2);
- }
- async afterStartup(interpreter2) {
- const fn = (p) => p.afterStartup?.(interpreter2);
- await Promise.all(this._plugins.map(fn));
- await Promise.all(this._pythonPlugins.map(fn));
- }
- async beforePyScriptExec(options) {
- await Promise.all(this._plugins.map((p) => p.beforePyScriptExec?.(options)));
- await Promise.all(
- this._pythonPlugins.map((p) => p.beforePyScriptExec?.(options.interpreter, options.src, options.pyScriptTag))
- );
- }
- async afterPyScriptExec(options) {
- await Promise.all(this._plugins.map((p) => p.afterPyScriptExec?.(options)));
- await Promise.all(
- this._pythonPlugins.map(
- (p) => p.afterPyScriptExec?.(options.interpreter, options.src, options.pyScriptTag, options.result)
- )
- );
- }
- async beforePyReplExec(options) {
- await Promise.all(this._plugins.map((p) => p.beforePyReplExec?.(options)));
- await Promise.all(
- this._pythonPlugins.map(
- (p) => p.beforePyReplExec?.(options.interpreter, options.src, options.outEl, options.pyReplTag)
- )
- );
- }
- async afterPyReplExec(options) {
- await Promise.all(this._plugins.map((p) => p.afterPyReplExec?.(options)));
- await Promise.all(
- this._pythonPlugins.map(
- (p) => p.afterPyReplExec?.(
- options.interpreter,
- options.src,
- options.outEl,
- options.pyReplTag,
- options.result
- )
- )
- );
- }
- async onUserError(error) {
- const fn = (p) => p.onUserError?.(error);
- await Promise.all(this._plugins.map(fn));
- await Promise.all(this._pythonPlugins.map(fn));
- }
- };
- function define_custom_element(tag, pyElementClass) {
- logger3.info(`creating plugin: ${tag}`);
- class ProxyCustomElement extends HTMLElement {
- constructor() {
- logger3.debug(`creating ${tag} plugin instance`);
- super();
- this.wrapper = document.createElement("slot");
- this.attachShadow({ mode: "open" }).appendChild(this.wrapper);
- this.originalInnerHTML = this.innerHTML;
- this.pyElementInstance = pyElementClass(this);
- }
- connectedCallback() {
- const innerHTML = this.pyElementInstance.connect();
- if (typeof innerHTML === "string")
- this.innerHTML = innerHTML;
- }
- }
- customElements.define(tag, ProxyCustomElement);
- }
- function validateConfigParameter(options) {
- if (!options.validator(options.defaultValue)) {
- throw Error(
- `Default value ${JSON.stringify(options.defaultValue)} for ${options.name} is not a valid argument, according to the provided validator function. ${options.hintMessage ? options.hintMessage : ""}`
- );
- }
- const value = options.config[options.name];
- if (value !== void 0 && !options.validator(value)) {
- const hintOutput = `Invalid value ${JSON.stringify(value)} for config.${options.name}. ${options.hintMessage ? options.hintMessage : ""}`;
- throw new UserError("PY1000" /* BAD_CONFIG */, hintOutput);
- }
- if (value === void 0) {
- options.config[options.name] = options.defaultValue;
- }
- }
- function validateConfigParameterFromArray(options) {
- const validator = (b) => options.possibleValues.includes(b);
- const hint = `The only accepted values are: [${options.possibleValues.map((item) => JSON.stringify(item)).join(", ")}]`;
- validateConfigParameter({
- config: options.config,
- name: options.name,
- validator,
- defaultValue: options.defaultValue,
- hintMessage: hint
- });
- }
-
- // node_modules/not-so-weak/esm/index.js
- var { iterator, species } = Symbol;
- var refs = /* @__PURE__ */ new WeakMap();
- var set = (value) => {
- const ref = new WeakRef(value);
- refs.set(value, ref);
- return ref;
- };
- var get = (value) => refs.get(value) || set(value);
- var WSet = class extends Set {
- //
- #registry = new FinalizationRegistry((ref) => super.delete(ref));
- #drop(ref) {
- const had = super.delete(ref);
- if (had)
- this.#registry.unregister(ref);
- return had;
- }
- get size() {
- return [...this].length;
- }
- delete(value) {
- return this.#drop(refs.get(value));
- }
- has(value) {
- return super.has(refs.get(value));
- }
- //
- constructor(entries = []) {
- super();
- for (const value of entries)
- this.add(value);
- }
- clear() {
- for (const ref of super[iterator]())
- this.#registry.unregister(ref);
- super.clear();
- }
- add(value) {
- const ref = get(value);
- if (!super.has(ref)) {
- this.#registry.register(value, ref, ref);
- super.add(ref);
- }
- return this;
- }
- forEach(callback, thisArg) {
- for (const value of [...this])
- callback.call(thisArg, value, value, this);
- }
- *[iterator]() {
- for (const ref of super[iterator]()) {
- const value = ref.deref();
- if (value)
- yield value;
- else
- this.#drop(ref);
- }
- }
- *entries() {
- for (const value of this)
- yield [value, value];
- }
- *keys() {
- yield* this[iterator]();
- }
- *values() {
- yield* this[iterator]();
- }
- };
- var WKey = class extends Map {
- //
- #registry = new FinalizationRegistry((ref) => super.delete(ref));
- #drop(ref) {
- const had = super.delete(ref);
- if (had)
- this.#registry.unregister(ref);
- return had;
- }
- get size() {
- return [...this].length;
- }
- delete(key) {
- return this.#drop(refs.get(key));
- }
- has(key) {
- return super.has(refs.get(key));
- }
- //
- constructor(entries = []) {
- super();
- for (const [key, value] of entries)
- this.set(key, value);
- }
- clear() {
- for (const ref of super.keys())
- this.#registry.unregister(ref);
- super.clear();
- }
- forEach(callback, thisArg) {
- for (const [key, value] of [...this])
- callback.call(thisArg, value, key, this);
- }
- get(key) {
- return super.get(refs.get(key));
- }
- set(key, value) {
- const ref = get(key);
- if (!super.has(ref))
- this.#registry.register(key, ref, ref);
- return super.set(ref, value);
- }
- *[iterator]() {
- for (const [ref, value] of super[iterator]()) {
- const key = ref.deref();
- if (key)
- yield [key, value];
- else
- this.#drop(ref);
- }
- }
- *entries() {
- yield* this[iterator]();
- }
- *keys() {
- for (const [key] of this)
- yield key;
- }
- *values() {
- for (const [_, value] of this)
- yield value;
- }
- };
- var WValue = class extends Map {
- #registry = new FinalizationRegistry((key) => super.delete(key));
- get size() {
- return [...this].length;
- }
- #drop(key, ref) {
- const had = super.delete(key);
- if (had)
- this.#registry.unregister(ref);
- return had;
- }
- constructor(entries = []) {
- super();
- for (const [key, value] of entries)
- this.set(key, value);
- }
- clear() {
- for (const ref of super.values())
- this.#registry.unregister(ref);
- super.clear();
- }
- delete(key) {
- return this.#drop(key, super.get(key));
- }
- forEach(callback, thisArg) {
- for (const [key, value] of [...this])
- callback.call(thisArg, value, key, this);
- }
- get(key) {
- return super.get(key)?.deref();
- }
- set(key, value) {
- let ref = super.get(key);
- if (ref)
- this.#registry.unregister(ref);
- ref = get(value);
- this.#registry.register(value, key, ref);
- return super.set(key, ref);
- }
- *[iterator]() {
- for (const [key, ref] of super[iterator]()) {
- const value = ref.deref();
- if (value)
- yield [key, value];
- else
- this.#drop(key, ref);
- }
- }
- *entries() {
- yield* this[iterator]();
- }
- *keys() {
- for (const [key] of this)
- yield key;
- }
- *values() {
- for (const [_, value] of this)
- yield value;
- }
- };
-
- // src/shadow_roots.ts
- var shadowRoots = new WSet();
- var findInShadowRoots = (selector) => {
- for (const shadowRoot of shadowRoots) {
- const element = $(selector, shadowRoot);
- if (element)
- return element;
- }
- return null;
- };
- var deepQuerySelector = (selector) => $(selector, document) || findInShadowRoots(selector);
-
- // src/pyexec.ts
- var logger4 = getLogger("pyexec");
- async function pyExec(interpreter2, pysrc, outElem) {
- ensureUniqueId(outElem);
- if (await interpreter2._remote.pyscript_internal.uses_top_level_await(pysrc)) {
- const err = new UserError(
- "PY9000" /* TOP_LEVEL_AWAIT */,
- 'The use of top-level "await", "async for", and "async with" has been removed.\nPlease write a coroutine containing your code and schedule it using asyncio.ensure_future() or similar.\nSee https://docs.pyscript.net/latest/guides/asyncio.html for more information.'
- );
- displayPyException(err, outElem);
- !outElem.classList.contains("error") && outElem.classList.add("error");
- return { result: void 0 };
- } else {
- outElem.classList.contains("error") && outElem.classList.remove("error");
- }
- try {
- outElem.classList.contains("error") && outElem.classList.remove("error");
- return await interpreter2.run(pysrc, outElem.id);
- } catch (e) {
- const err = e;
- displayPyException(err, outElem);
- !outElem.classList.contains("error") && outElem.classList.add("error");
- return { result: void 0 };
- }
- }
- async function pyDisplay(interpreter2, obj, kwargs = {}) {
- const display = await interpreter2.globals.get("display");
- try {
- await display.callKwargs(obj, kwargs);
- } finally {
- display.destroy();
- }
- }
- function displayPyException(err, errElem) {
- const pre = document.createElement("pre");
- pre.className = "py-error";
- if (err.name === "PythonError") {
- logger4.error("Python exception:\n" + err.message);
- pre.innerText = err.message;
- } else {
- logger4.error("Non-python exception:\n" + err.toString());
- pre.innerText = err.toString();
- }
- errElem.appendChild(pre);
- }
-
- // src/fetch.ts
- async function robustFetch(url, options) {
- let response;
- try {
- response = await fetch(url, options);
- } catch (err) {
- const error = err;
- let errMsg;
- if (url.startsWith("http")) {
- errMsg = `Fetching from URL ${url} failed with error '${error.message}'. Are your filename and path correct?`;
- } else {
- errMsg = `PyScript: Access to local files
- (using [[fetch]] configurations in <py-config>)
- is not available when directly opening a HTML file;
- you must use a webserver to serve the additional files.
- See this reference
- on starting a simple webserver with Python.
- `;
- }
- throw new FetchError("PY0001" /* FETCH_ERROR */, errMsg);
- }
- if (!response.ok) {
- const errorMsg = `Fetching from URL ${url} failed with error ${response.status} (${response.statusText}). Are your filename and path correct?`;
- switch (response.status) {
- case 404:
- throw new FetchError("PY0404" /* FETCH_NOT_FOUND_ERROR */, errorMsg);
- case 401:
- throw new FetchError("PY0401" /* FETCH_UNAUTHORIZED_ERROR */, errorMsg);
- case 403:
- throw new FetchError("PY0403" /* FETCH_FORBIDDEN_ERROR */, errorMsg);
- case 500:
- throw new FetchError("PY0500" /* FETCH_SERVER_ERROR */, errorMsg);
- case 503:
- throw new FetchError("PY0503" /* FETCH_UNAVAILABLE_ERROR */, errorMsg);
- default:
- throw new FetchError("PY0001" /* FETCH_ERROR */, errorMsg);
- }
- }
- return response;
- }
-
- // src/components/pyscript.ts
- var logger5 = getLogger("py-script");
- var knownPyScriptTags = /* @__PURE__ */ new WeakSet();
- function make_PyScript(interpreter2, app) {
- const init = async (pyScriptTag, fallback) => {
- app.incrementPendingTags();
- let releaseLock;
- try {
- releaseLock = await app.tagExecutionLock();
- ensureUniqueId(pyScriptTag);
- const src = await fetchSource(pyScriptTag, fallback);
- await app.plugins.beforePyScriptExec({ interpreter: interpreter2, src, pyScriptTag });
- const { result } = await pyExec(interpreter2, src, pyScriptTag);
- await app.plugins.afterPyScriptExec({ interpreter: interpreter2, src, pyScriptTag, result });
- await interpreter2._remote.destroyIfProxy(result);
- } finally {
- releaseLock();
- app.decrementPendingTags();
- }
- };
- const fetchSource = async (tag, fallback) => {
- if (tag.hasAttribute("src")) {
- try {
- const response = await robustFetch(tag.getAttribute("src"));
- return await response.text();
- } catch (err) {
- const e = err;
- _createAlertBanner(e.message);
- throw e;
- }
- }
- return fallback();
- };
- class PyScript extends HTMLElement {
- constructor() {
- super(...arguments);
- this._fetchSourceFallback = () => htmlDecode(this.srcCode);
- }
- async connectedCallback() {
- if (knownPyScriptTags.has(this))
- return;
- knownPyScriptTags.add(this);
- this.srcCode = this.innerHTML;
- this.innerHTML = "";
- await init(this, this._fetchSourceFallback);
- }
- getPySrc() {
- return fetchSource(this, this._fetchSourceFallback);
- }
- }
- if (!customElements.get("py-script")) {
- const pyScriptCSS = 'script[type="py"],script[type="pyscript"],script[type="py-script"]';
- const bootstrap = (script) => {
- if (knownPyScriptTags.has(script))
- return;
- knownPyScriptTags.add(script);
- const pyScriptTag = document.createElement("py-script-tag");
- for (const name2 of ["output", "src", "stderr"]) {
- const value = script.getAttribute(name2);
- if (value) {
- pyScriptTag.setAttribute(name2, value);
- }
- }
- script.after(pyScriptTag);
- init(pyScriptTag, () => ltrim(script.textContent.replace(/^[\r\n]+/, ""))).catch(
- () => pyScriptTag.remove()
- );
- };
- const bootstrapScripts = (root) => {
- for (const node of $$(pyScriptCSS, root)) {
- bootstrap(node);
- }
- };
- const pyScriptMO = new MutationObserver((records) => {
- for (const { type, target, attributeName, addedNodes } of records) {
- if (type === "attributes") {
- if (attributeName.startsWith("py-")) {
- if (target.hasAttribute(attributeName)) {
- addPyScriptEventListener(
- getInterpreter(target),
- target,
- attributeName.slice(3)
- );
- } else {
- target.removeEventListener(attributeName.slice(3), pyScriptListener);
- }
- }
- continue;
- }
- for (const node of addedNodes) {
- if (node.nodeType === Node.ELEMENT_NODE) {
- if (node.matches(pyScriptCSS)) {
- bootstrap(node);
- } else {
- addAllPyScriptEventListeners(node);
- bootstrapScripts(node);
- }
- }
- }
- }
- });
- const observe = (root) => {
- pyScriptMO.observe(root, { childList: true, subtree: true, attributes: true });
- return root;
- };
- const { attachShadow } = Element.prototype;
- Object.assign(Element.prototype, {
- attachShadow(init2) {
- const shadowRoot = observe(attachShadow.call(this, init2));
- shadowRoots.add(shadowRoot);
- return shadowRoot;
- }
- });
- bootstrapScripts(document);
- observe(document);
- }
- return PyScript;
- }
- var elementInterpreter = /* @__PURE__ */ new WeakMap();
- var getInterpreter = (el) => elementInterpreter.get(el) || lastInterpreter;
- var lastInterpreter;
- var addAllPyScriptEventListeners = (root) => {
- const attributes = $x('.//@*[starts-with(name(), "py-")]', root);
- for (const { name: name2, ownerElement: el } of attributes) {
- addPyScriptEventListener(getInterpreter(el), el, name2.slice(3));
- }
- };
- function initHandlers(interpreter2) {
- logger5.debug("Initializing py-* event handlers...");
- lastInterpreter = interpreter2;
- addAllPyScriptEventListeners(document);
- }
- var pyScriptListener = async ({ type, currentTarget: el }) => {
- try {
- const interpreter2 = getInterpreter(el);
- await interpreter2.run(el.getAttribute(`py-${type}`));
- } catch (e) {
- const err = e;
- displayPyException(err, el.parentElement);
- }
- };
- function addPyScriptEventListener(interpreter2, el, type) {
- if (el.id.length === 0) {
- ensureUniqueId(el);
- }
- elementInterpreter.set(el, interpreter2);
- el.addEventListener(type, pyScriptListener);
- }
- async function mountElements(interpreter2) {
- const matches = $$("[py-mount]", document);
- logger5.info(`py-mount: found ${matches.length} elements`);
- if (matches.length > 0) {
- const deprecationMessage = 'The "py-mount" attribute is deprecated. Please add references to HTML Elements manually in your script.';
- createDeprecationWarning(deprecationMessage, "py-mount");
- }
- let source = "";
- for (const el of matches) {
- const mountName = el.getAttribute("py-mount") || el.id.split("-").join("_");
- source += `
-${mountName} = Element("${el.id}")`;
- }
- await interpreter2.run(source);
- }
-
- // src/plugins/calculateFetchPaths.ts
- function calculateFetchPaths(fetch_cfg) {
- for (const { files, to_file, from = "" } of fetch_cfg) {
- if (files !== void 0 && to_file !== void 0) {
- throw new UserError("PY1000" /* BAD_CONFIG */, `Cannot use 'to_file' and 'files' parameters together!`);
- }
- if (files === void 0 && to_file === void 0 && from.endsWith("/")) {
- throw new UserError(
- "PY1000" /* BAD_CONFIG */,
- `Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`
- );
- }
- }
- return fetch_cfg.flatMap(function({ from = "", to_folder = ".", to_file, files }) {
- if (files !== void 0) {
- return files.map((file) => ({ url: joinPaths([from, file]), path: joinPaths([to_folder, file]) }));
- }
- const filename = to_file || from.slice(1 + from.lastIndexOf("/"));
- const to_path = joinPaths([to_folder, filename]);
- return [{ url: from, path: to_path }];
- });
- }
-
- // node_modules/@codemirror/state/dist/index.js
- var Text = class {
- /**
- @internal
- */
- constructor() {
- }
- /**
- Get the line description around the given position.
- */
- lineAt(pos) {
- if (pos < 0 || pos > this.length)
- throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
- return this.lineInner(pos, false, 1, 0);
- }
- /**
- Get the description for the given (1-based) line number.
- */
- line(n) {
- if (n < 1 || n > this.lines)
- throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
- return this.lineInner(n, true, 1, 0);
- }
- /**
- Replace a range of the text with the given content.
- */
- replace(from, to, text) {
- let parts = [];
- this.decompose(
- 0,
- from,
- parts,
- 2
- /* Open.To */
- );
- if (text.length)
- text.decompose(
- 0,
- text.length,
- parts,
- 1 | 2
- /* Open.To */
- );
- this.decompose(
- to,
- this.length,
- parts,
- 1
- /* Open.From */
- );
- return TextNode.from(parts, this.length - (to - from) + text.length);
- }
- /**
- Append another document to this one.
- */
- append(other) {
- return this.replace(this.length, this.length, other);
- }
- /**
- Retrieve the text between the given points.
- */
- slice(from, to = this.length) {
- let parts = [];
- this.decompose(from, to, parts, 0);
- return TextNode.from(parts, to - from);
- }
- /**
- Test whether this text is equal to another instance.
- */
- eq(other) {
- if (other == this)
- return true;
- if (other.length != this.length || other.lines != this.lines)
- return false;
- let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
- let a = new RawTextCursor(this), b = new RawTextCursor(other);
- for (let skip = start, pos = start; ; ) {
- a.next(skip);
- b.next(skip);
- skip = 0;
- if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
- return false;
- pos += a.value.length;
- if (a.done || pos >= end)
- return true;
- }
- }
- /**
- Iterate over the text. When `dir` is `-1`, iteration happens
- from end to start. This will return lines and the breaks between
- them as separate strings.
- */
- iter(dir = 1) {
- return new RawTextCursor(this, dir);
- }
- /**
- Iterate over a range of the text. When `from` > `to`, the
- iterator will run in reverse.
- */
- iterRange(from, to = this.length) {
- return new PartialTextCursor(this, from, to);
- }
- /**
- Return a cursor that iterates over the given range of lines,
- _without_ returning the line breaks between, and yielding empty
- strings for empty lines.
-
- When `from` and `to` are given, they should be 1-based line numbers.
- */
- iterLines(from, to) {
- let inner;
- if (from == null) {
- inner = this.iter();
- } else {
- if (to == null)
- to = this.lines + 1;
- let start = this.line(from).from;
- inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
- }
- return new LineCursor(inner);
- }
- /**
- @internal
- */
- toString() {
- return this.sliceString(0);
- }
- /**
- Convert the document to an array of lines (which can be
- deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
- */
- toJSON() {
- let lines = [];
- this.flatten(lines);
- return lines;
- }
- /**
- Create a `Text` instance for the given array of lines.
- */
- static of(text) {
- if (text.length == 0)
- throw new RangeError("A document must have at least one line");
- if (text.length == 1 && !text[0])
- return Text.empty;
- return text.length <= 32 ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
- }
- };
- var TextLeaf = class extends Text {
- constructor(text, length = textLength(text)) {
- super();
- this.text = text;
- this.length = length;
- }
- get lines() {
- return this.text.length;
- }
- get children() {
- return null;
- }
- lineInner(target, isLine, line, offset) {
- for (let i = 0; ; i++) {
- let string2 = this.text[i], end = offset + string2.length;
- if ((isLine ? line : end) >= target)
- return new Line(offset, end, line, string2);
- offset = end + 1;
- line++;
- }
- }
- decompose(from, to, target, open) {
- let text = from <= 0 && to >= this.length ? this : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
- if (open & 1) {
- let prev = target.pop();
- let joined = appendText(text.text, prev.text.slice(), 0, text.length);
- if (joined.length <= 32) {
- target.push(new TextLeaf(joined, prev.length + text.length));
- } else {
- let mid = joined.length >> 1;
- target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
- }
- } else {
- target.push(text);
- }
- }
- replace(from, to, text) {
- if (!(text instanceof TextLeaf))
- return super.replace(from, to, text);
- let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
- let newLen = this.length + text.length - (to - from);
- if (lines.length <= 32)
- return new TextLeaf(lines, newLen);
- return TextNode.from(TextLeaf.split(lines, []), newLen);
- }
- sliceString(from, to = this.length, lineSep = "\n") {
- let result = "";
- for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
- let line = this.text[i], end = pos + line.length;
- if (pos > from && i)
- result += lineSep;
- if (from < end && to > pos)
- result += line.slice(Math.max(0, from - pos), to - pos);
- pos = end + 1;
- }
- return result;
- }
- flatten(target) {
- for (let line of this.text)
- target.push(line);
- }
- scanIdentical() {
- return 0;
- }
- static split(text, target) {
- let part = [], len = -1;
- for (let line of text) {
- part.push(line);
- len += line.length + 1;
- if (part.length == 32) {
- target.push(new TextLeaf(part, len));
- part = [];
- len = -1;
- }
- }
- if (len > -1)
- target.push(new TextLeaf(part, len));
- return target;
- }
- };
- var TextNode = class extends Text {
- constructor(children, length) {
- super();
- this.children = children;
- this.length = length;
- this.lines = 0;
- for (let child of children)
- this.lines += child.lines;
- }
- lineInner(target, isLine, line, offset) {
- for (let i = 0; ; i++) {
- let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
- if ((isLine ? endLine : end) >= target)
- return child.lineInner(target, isLine, line, offset);
- offset = end + 1;
- line = endLine + 1;
- }
- }
- decompose(from, to, target, open) {
- for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
- let child = this.children[i], end = pos + child.length;
- if (from <= end && to >= pos) {
- let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0));
- if (pos >= from && end <= to && !childOpen)
- target.push(child);
- else
- child.decompose(from - pos, to - pos, target, childOpen);
- }
- pos = end + 1;
- }
- }
- replace(from, to, text) {
- if (text.lines < this.lines)
- for (let i = 0, pos = 0; i < this.children.length; i++) {
- let child = this.children[i], end = pos + child.length;
- if (from >= pos && to <= end) {
- let updated = child.replace(from - pos, to - pos, text);
- let totalLines = this.lines - child.lines + updated.lines;
- if (updated.lines < totalLines >> 5 - 1 && updated.lines > totalLines >> 5 + 1) {
- let copy = this.children.slice();
- copy[i] = updated;
- return new TextNode(copy, this.length - (to - from) + text.length);
- }
- return super.replace(pos, end, updated);
- }
- pos = end + 1;
- }
- return super.replace(from, to, text);
- }
- sliceString(from, to = this.length, lineSep = "\n") {
- let result = "";
- for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
- let child = this.children[i], end = pos + child.length;
- if (pos > from && i)
- result += lineSep;
- if (from < end && to > pos)
- result += child.sliceString(from - pos, to - pos, lineSep);
- pos = end + 1;
- }
- return result;
- }
- flatten(target) {
- for (let child of this.children)
- child.flatten(target);
- }
- scanIdentical(other, dir) {
- if (!(other instanceof TextNode))
- return 0;
- let length = 0;
- let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1];
- for (; ; iA += dir, iB += dir) {
- if (iA == eA || iB == eB)
- return length;
- let chA = this.children[iA], chB = other.children[iB];
- if (chA != chB)
- return length + chA.scanIdentical(chB, dir);
- length += chA.length + 1;
- }
- }
- static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
- let lines = 0;
- for (let ch of children)
- lines += ch.lines;
- if (lines < 32) {
- let flat = [];
- for (let ch of children)
- ch.flatten(flat);
- return new TextLeaf(flat, length);
- }
- let chunk = Math.max(
- 32,
- lines >> 5
- /* Tree.BranchShift */
- ), maxChunk = chunk << 1, minChunk = chunk >> 1;
- let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
- function add2(child) {
- let last;
- if (child.lines > maxChunk && child instanceof TextNode) {
- for (let node of child.children)
- add2(node);
- } else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
- flush();
- chunked.push(child);
- } else if (child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= 32) {
- currentLines += child.lines;
- currentLen += child.length + 1;
- currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
- } else {
- if (currentLines + child.lines > chunk)
- flush();
- currentLines += child.lines;
- currentLen += child.length + 1;
- currentChunk.push(child);
- }
- }
- function flush() {
- if (currentLines == 0)
- return;
- chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
- currentLen = -1;
- currentLines = currentChunk.length = 0;
- }
- for (let child of children)
- add2(child);
- flush();
- return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
- }
- };
- Text.empty = /* @__PURE__ */ new TextLeaf([""], 0);
- function textLength(text) {
- let length = -1;
- for (let line of text)
- length += line.length + 1;
- return length;
- }
- function appendText(text, target, from = 0, to = 1e9) {
- for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
- let line = text[i], end = pos + line.length;
- if (end >= from) {
- if (end > to)
- line = line.slice(0, to - pos);
- if (pos < from)
- line = line.slice(from - pos);
- if (first) {
- target[target.length - 1] += line;
- first = false;
- } else
- target.push(line);
- }
- pos = end + 1;
- }
- return target;
- }
- function sliceText(text, from, to) {
- return appendText(text, [""], from, to);
- }
- var RawTextCursor = class {
- constructor(text, dir = 1) {
- this.dir = dir;
- this.done = false;
- this.lineBreak = false;
- this.value = "";
- this.nodes = [text];
- this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
- }
- nextInner(skip, dir) {
- this.done = this.lineBreak = false;
- for (; ; ) {
- let last = this.nodes.length - 1;
- let top2 = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
- let size = top2 instanceof TextLeaf ? top2.text.length : top2.children.length;
- if (offset == (dir > 0 ? size : 0)) {
- if (last == 0) {
- this.done = true;
- this.value = "";
- return this;
- }
- if (dir > 0)
- this.offsets[last - 1]++;
- this.nodes.pop();
- this.offsets.pop();
- } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
- this.offsets[last] += dir;
- if (skip == 0) {
- this.lineBreak = true;
- this.value = "\n";
- return this;
- }
- skip--;
- } else if (top2 instanceof TextLeaf) {
- let next = top2.text[offset + (dir < 0 ? -1 : 0)];
- this.offsets[last] += dir;
- if (next.length > Math.max(0, skip)) {
- this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
- return this;
- }
- skip -= next.length;
- } else {
- let next = top2.children[offset + (dir < 0 ? -1 : 0)];
- if (skip > next.length) {
- skip -= next.length;
- this.offsets[last] += dir;
- } else {
- if (dir < 0)
- this.offsets[last]--;
- this.nodes.push(next);
- this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
- }
- }
- }
- }
- next(skip = 0) {
- if (skip < 0) {
- this.nextInner(-skip, -this.dir);
- skip = this.value.length;
- }
- return this.nextInner(skip, this.dir);
- }
- };
- var PartialTextCursor = class {
- constructor(text, start, end) {
- this.value = "";
- this.done = false;
- this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
- this.pos = start > end ? text.length : 0;
- this.from = Math.min(start, end);
- this.to = Math.max(start, end);
- }
- nextInner(skip, dir) {
- if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
- this.value = "";
- this.done = true;
- return this;
- }
- skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
- let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
- if (skip > limit)
- skip = limit;
- limit -= skip;
- let { value } = this.cursor.next(skip);
- this.pos += (value.length + skip) * dir;
- this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
- this.done = !this.value;
- return this;
- }
- next(skip = 0) {
- if (skip < 0)
- skip = Math.max(skip, this.from - this.pos);
- else if (skip > 0)
- skip = Math.min(skip, this.to - this.pos);
- return this.nextInner(skip, this.cursor.dir);
- }
- get lineBreak() {
- return this.cursor.lineBreak && this.value != "";
- }
- };
- var LineCursor = class {
- constructor(inner) {
- this.inner = inner;
- this.afterBreak = true;
- this.value = "";
- this.done = false;
- }
- next(skip = 0) {
- let { done, lineBreak, value } = this.inner.next(skip);
- if (done) {
- this.done = true;
- this.value = "";
- } else if (lineBreak) {
- if (this.afterBreak) {
- this.value = "";
- } else {
- this.afterBreak = true;
- this.next();
- }
- } else {
- this.value = value;
- this.afterBreak = false;
- }
- return this;
- }
- get lineBreak() {
- return false;
- }
- };
- if (typeof Symbol != "undefined") {
- Text.prototype[Symbol.iterator] = function() {
- return this.iter();
- };
- RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function() {
- return this;
- };
- }
- var Line = class {
- /**
- @internal
- */
- constructor(from, to, number2, text) {
- this.from = from;
- this.to = to;
- this.number = number2;
- this.text = text;
- }
- /**
- The length of the line (not including any line break after it).
- */
- get length() {
- return this.to - this.from;
- }
- };
- var extend = /* @__PURE__ */ "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((s) => s ? parseInt(s, 36) : 1);
- for (let i = 1; i < extend.length; i++)
- extend[i] += extend[i - 1];
- function isExtendingChar(code) {
- for (let i = 1; i < extend.length; i += 2)
- if (extend[i] > code)
- return extend[i - 1] <= code;
- return false;
- }
- function isRegionalIndicator(code) {
- return code >= 127462 && code <= 127487;
- }
- var ZWJ = 8205;
- function findClusterBreak(str, pos, forward = true, includeExtending = true) {
- return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
- }
- function nextClusterBreak(str, pos, includeExtending) {
- if (pos == str.length)
- return pos;
- if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))
- pos--;
- let prev = codePointAt(str, pos);
- pos += codePointSize(prev);
- while (pos < str.length) {
- let next = codePointAt(str, pos);
- if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
- pos += codePointSize(next);
- prev = next;
- } else if (isRegionalIndicator(next)) {
- let countBefore = 0, i = pos - 2;
- while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {
- countBefore++;
- i -= 2;
- }
- if (countBefore % 2 == 0)
- break;
- else
- pos += 2;
- } else {
- break;
- }
- }
- return pos;
- }
- function prevClusterBreak(str, pos, includeExtending) {
- while (pos > 0) {
- let found = nextClusterBreak(str, pos - 2, includeExtending);
- if (found < pos)
- return found;
- pos--;
- }
- return 0;
- }
- function surrogateLow(ch) {
- return ch >= 56320 && ch < 57344;
- }
- function surrogateHigh(ch) {
- return ch >= 55296 && ch < 56320;
- }
- function codePointAt(str, pos) {
- let code0 = str.charCodeAt(pos);
- if (!surrogateHigh(code0) || pos + 1 == str.length)
- return code0;
- let code1 = str.charCodeAt(pos + 1);
- if (!surrogateLow(code1))
- return code0;
- return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
- }
- function fromCodePoint(code) {
- if (code <= 65535)
- return String.fromCharCode(code);
- code -= 65536;
- return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
- }
- function codePointSize(code) {
- return code < 65536 ? 1 : 2;
- }
- var DefaultSplit = /\r\n?|\n/;
- var MapMode = /* @__PURE__ */ function(MapMode2) {
- MapMode2[MapMode2["Simple"] = 0] = "Simple";
- MapMode2[MapMode2["TrackDel"] = 1] = "TrackDel";
- MapMode2[MapMode2["TrackBefore"] = 2] = "TrackBefore";
- MapMode2[MapMode2["TrackAfter"] = 3] = "TrackAfter";
- return MapMode2;
- }(MapMode || (MapMode = {}));
- var ChangeDesc = class {
- // Sections are encoded as pairs of integers. The first is the
- // length in the current document, and the second is -1 for
- // unaffected sections, and the length of the replacement content
- // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
- // 0), and a replacement two positive numbers.
- /**
- @internal
- */
- constructor(sections) {
- this.sections = sections;
- }
- /**
- The length of the document before the change.
- */
- get length() {
- let result = 0;
- for (let i = 0; i < this.sections.length; i += 2)
- result += this.sections[i];
- return result;
- }
- /**
- The length of the document after the change.
- */
- get newLength() {
- let result = 0;
- for (let i = 0; i < this.sections.length; i += 2) {
- let ins = this.sections[i + 1];
- result += ins < 0 ? this.sections[i] : ins;
- }
- return result;
- }
- /**
- False when there are actual changes in this set.
- */
- get empty() {
- return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
- }
- /**
- Iterate over the unchanged parts left by these changes. `posA`
- provides the position of the range in the old document, `posB`
- the new position in the changed document.
- */
- iterGaps(f) {
- for (let i = 0, posA = 0, posB = 0; i < this.sections.length; ) {
- let len = this.sections[i++], ins = this.sections[i++];
- if (ins < 0) {
- f(posA, posB, len);
- posB += len;
- } else {
- posB += ins;
- }
- posA += len;
- }
- }
- /**
- Iterate over the ranges changed by these changes. (See
- [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
- variant that also provides you with the inserted text.)
- `fromA`/`toA` provides the extent of the change in the starting
- document, `fromB`/`toB` the extent of the replacement in the
- changed document.
-
- When `individual` is true, adjacent changes (which are kept
- separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
- reported separately.
- */
- iterChangedRanges(f, individual = false) {
- iterChanges(this, f, individual);
- }
- /**
- Get a description of the inverted form of these changes.
- */
- get invertedDesc() {
- let sections = [];
- for (let i = 0; i < this.sections.length; ) {
- let len = this.sections[i++], ins = this.sections[i++];
- if (ins < 0)
- sections.push(len, ins);
- else
- sections.push(ins, len);
- }
- return new ChangeDesc(sections);
- }
- /**
- Compute the combined effect of applying another set of changes
- after this one. The length of the document after this set should
- match the length before `other`.
- */
- composeDesc(other) {
- return this.empty ? other : other.empty ? this : composeSets(this, other);
- }
- /**
- Map this description, which should start with the same document
- as `other`, over another set of changes, so that it can be
- applied after it. When `before` is true, map as if the changes
- in `other` happened before the ones in `this`.
- */
- mapDesc(other, before = false) {
- return other.empty ? this : mapSet(this, other, before);
- }
- mapPos(pos, assoc = -1, mode = MapMode.Simple) {
- let posA = 0, posB = 0;
- for (let i = 0; i < this.sections.length; ) {
- let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
- if (ins < 0) {
- if (endA > pos)
- return posB + (pos - posA);
- posB += len;
- } else {
- if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos))
- return null;
- if (endA > pos || endA == pos && assoc < 0 && !len)
- return pos == posA || assoc < 0 ? posB : posB + ins;
- posB += ins;
- }
- posA = endA;
- }
- if (pos > posA)
- throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
- return posB;
- }
- /**
- Check whether these changes touch a given range. When one of the
- changes entirely covers the range, the string `"cover"` is
- returned.
- */
- touchesRange(from, to = from) {
- for (let i = 0, pos = 0; i < this.sections.length && pos <= to; ) {
- let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
- if (ins >= 0 && pos <= to && end >= from)
- return pos < from && end > to ? "cover" : true;
- pos = end;
- }
- return false;
- }
- /**
- @internal
- */
- toString() {
- let result = "";
- for (let i = 0; i < this.sections.length; ) {
- let len = this.sections[i++], ins = this.sections[i++];
- result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
- }
- return result;
- }
- /**
- Serialize this change desc to a JSON-representable value.
- */
- toJSON() {
- return this.sections;
- }
- /**
- Create a change desc from its JSON representation (as produced
- by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
- */
- static fromJSON(json) {
- if (!Array.isArray(json) || json.length % 2 || json.some((a) => typeof a != "number"))
- throw new RangeError("Invalid JSON representation of ChangeDesc");
- return new ChangeDesc(json);
- }
- /**
- @internal
- */
- static create(sections) {
- return new ChangeDesc(sections);
- }
- };
- var ChangeSet = class extends ChangeDesc {
- constructor(sections, inserted) {
- super(sections);
- this.inserted = inserted;
- }
- /**
- Apply the changes to a document, returning the modified
- document.
- */
- apply(doc2) {
- if (this.length != doc2.length)
- throw new RangeError("Applying change set to a document with the wrong length");
- iterChanges(this, (fromA, toA, fromB, _toB, text) => doc2 = doc2.replace(fromB, fromB + (toA - fromA), text), false);
- return doc2;
- }
- mapDesc(other, before = false) {
- return mapSet(this, other, before, true);
- }
- /**
- Given the document as it existed _before_ the changes, return a
- change set that represents the inverse of this set, which could
- be used to go from the document created by the changes back to
- the document as it existed before the changes.
- */
- invert(doc2) {
- let sections = this.sections.slice(), inserted = [];
- for (let i = 0, pos = 0; i < sections.length; i += 2) {
- let len = sections[i], ins = sections[i + 1];
- if (ins >= 0) {
- sections[i] = ins;
- sections[i + 1] = len;
- let index = i >> 1;
- while (inserted.length < index)
- inserted.push(Text.empty);
- inserted.push(len ? doc2.slice(pos, pos + len) : Text.empty);
- }
- pos += len;
- }
- return new ChangeSet(sections, inserted);
- }
- /**
- Combine two subsequent change sets into a single set. `other`
- must start in the document produced by `this`. If `this` goes
- `docA` �� `docB` and `other` represents `docB` �� `docC`, the
- returned value will represent the change `docA` �� `docC`.
- */
- compose(other) {
- return this.empty ? other : other.empty ? this : composeSets(this, other, true);
- }
- /**
- Given another change set starting in the same document, maps this
- change set over the other, producing a new change set that can be
- applied to the document produced by applying `other`. When
- `before` is `true`, order changes as if `this` comes before
- `other`, otherwise (the default) treat `other` as coming first.
-
- Given two changes `A` and `B`, `A.compose(B.map(A))` and
- `B.compose(A.map(B, true))` will produce the same document. This
- provides a basic form of [operational
- transformation](https://en.wikipedia.org/wiki/Operational_transformation),
- and can be used for collaborative editing.
- */
- map(other, before = false) {
- return other.empty ? this : mapSet(this, other, before, true);
- }
- /**
- Iterate over the changed ranges in the document, calling `f` for
- each, with the range in the original document (`fromA`-`toA`)
- and the range that replaces it in the new document
- (`fromB`-`toB`).
-
- When `individual` is true, adjacent changes are reported
- separately.
- */
- iterChanges(f, individual = false) {
- iterChanges(this, f, individual);
- }
- /**
- Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
- set.
- */
- get desc() {
- return ChangeDesc.create(this.sections);
- }
- /**
- @internal
- */
- filter(ranges) {
- let resultSections = [], resultInserted = [], filteredSections = [];
- let iter = new SectionIter(this);
- done:
- for (let i = 0, pos = 0; ; ) {
- let next = i == ranges.length ? 1e9 : ranges[i++];
- while (pos < next || pos == next && iter.len == 0) {
- if (iter.done)
- break done;
- let len = Math.min(iter.len, next - pos);
- addSection(filteredSections, len, -1);
- let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
- addSection(resultSections, len, ins);
- if (ins > 0)
- addInsert(resultInserted, resultSections, iter.text);
- iter.forward(len);
- pos += len;
- }
- let end = ranges[i++];
- while (pos < end) {
- if (iter.done)
- break done;
- let len = Math.min(iter.len, end - pos);
- addSection(resultSections, len, -1);
- addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
- iter.forward(len);
- pos += len;
- }
- }
- return {
- changes: new ChangeSet(resultSections, resultInserted),
- filtered: ChangeDesc.create(filteredSections)
- };
- }
- /**
- Serialize this change set to a JSON-representable value.
- */
- toJSON() {
- let parts = [];
- for (let i = 0; i < this.sections.length; i += 2) {
- let len = this.sections[i], ins = this.sections[i + 1];
- if (ins < 0)
- parts.push(len);
- else if (ins == 0)
- parts.push([len]);
- else
- parts.push([len].concat(this.inserted[i >> 1].toJSON()));
- }
- return parts;
- }
- /**
- Create a change set for the given changes, for a document of the
- given length, using `lineSep` as line separator.
- */
- static of(changes, length, lineSep) {
- let sections = [], inserted = [], pos = 0;
- let total = null;
- function flush(force = false) {
- if (!force && !sections.length)
- return;
- if (pos < length)
- addSection(sections, length - pos, -1);
- let set2 = new ChangeSet(sections, inserted);
- total = total ? total.compose(set2.map(total)) : set2;
- sections = [];
- inserted = [];
- pos = 0;
- }
- function process2(spec) {
- if (Array.isArray(spec)) {
- for (let sub of spec)
- process2(sub);
- } else if (spec instanceof ChangeSet) {
- if (spec.length != length)
- throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
- flush();
- total = total ? total.compose(spec.map(total)) : spec;
- } else {
- let { from, to = from, insert: insert2 } = spec;
- if (from > to || from < 0 || to > length)
- throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
- let insText = !insert2 ? Text.empty : typeof insert2 == "string" ? Text.of(insert2.split(lineSep || DefaultSplit)) : insert2;
- let insLen = insText.length;
- if (from == to && insLen == 0)
- return;
- if (from < pos)
- flush();
- if (from > pos)
- addSection(sections, from - pos, -1);
- addSection(sections, to - from, insLen);
- addInsert(inserted, sections, insText);
- pos = to;
- }
- }
- process2(changes);
- flush(!total);
- return total;
- }
- /**
- Create an empty changeset of the given length.
- */
- static empty(length) {
- return new ChangeSet(length ? [length, -1] : [], []);
- }
- /**
- Create a changeset from its JSON representation (as produced by
- [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
- */
- static fromJSON(json) {
- if (!Array.isArray(json))
- throw new RangeError("Invalid JSON representation of ChangeSet");
- let sections = [], inserted = [];
- for (let i = 0; i < json.length; i++) {
- let part = json[i];
- if (typeof part == "number") {
- sections.push(part, -1);
- } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i2) => i2 && typeof e != "string")) {
- throw new RangeError("Invalid JSON representation of ChangeSet");
- } else if (part.length == 1) {
- sections.push(part[0], 0);
- } else {
- while (inserted.length < i)
- inserted.push(Text.empty);
- inserted[i] = Text.of(part.slice(1));
- sections.push(part[0], inserted[i].length);
- }
- }
- return new ChangeSet(sections, inserted);
- }
- /**
- @internal
- */
- static createSet(sections, inserted) {
- return new ChangeSet(sections, inserted);
- }
- };
- function addSection(sections, len, ins, forceJoin = false) {
- if (len == 0 && ins <= 0)
- return;
- let last = sections.length - 2;
- if (last >= 0 && ins <= 0 && ins == sections[last + 1])
- sections[last] += len;
- else if (len == 0 && sections[last] == 0)
- sections[last + 1] += ins;
- else if (forceJoin) {
- sections[last] += len;
- sections[last + 1] += ins;
- } else
- sections.push(len, ins);
- }
- function addInsert(values, sections, value) {
- if (value.length == 0)
- return;
- let index = sections.length - 2 >> 1;
- if (index < values.length) {
- values[values.length - 1] = values[values.length - 1].append(value);
- } else {
- while (values.length < index)
- values.push(Text.empty);
- values.push(value);
- }
- }
- function iterChanges(desc, f, individual) {
- let inserted = desc.inserted;
- for (let posA = 0, posB = 0, i = 0; i < desc.sections.length; ) {
- let len = desc.sections[i++], ins = desc.sections[i++];
- if (ins < 0) {
- posA += len;
- posB += len;
- } else {
- let endA = posA, endB = posB, text = Text.empty;
- for (; ; ) {
- endA += len;
- endB += ins;
- if (ins && inserted)
- text = text.append(inserted[i - 2 >> 1]);
- if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
- break;
- len = desc.sections[i++];
- ins = desc.sections[i++];
- }
- f(posA, endA, posB, endB, text);
- posA = endA;
- posB = endB;
- }
- }
- }
- function mapSet(setA, setB, before, mkSet = false) {
- let sections = [], insert2 = mkSet ? [] : null;
- let a = new SectionIter(setA), b = new SectionIter(setB);
- for (let inserted = -1; ; ) {
- if (a.ins == -1 && b.ins == -1) {
- let len = Math.min(a.len, b.len);
- addSection(sections, len, -1);
- a.forward(len);
- b.forward(len);
- } else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
- let len = b.len;
- addSection(sections, b.ins, -1);
- while (len) {
- let piece = Math.min(a.len, len);
- if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
- addSection(sections, 0, a.ins);
- if (insert2)
- addInsert(insert2, sections, a.text);
- inserted = a.i;
- }
- a.forward(piece);
- len -= piece;
- }
- b.next();
- } else if (a.ins >= 0) {
- let len = 0, left = a.len;
- while (left) {
- if (b.ins == -1) {
- let piece = Math.min(left, b.len);
- len += piece;
- left -= piece;
- b.forward(piece);
- } else if (b.ins == 0 && b.len < left) {
- left -= b.len;
- b.next();
- } else {
- break;
- }
- }
- addSection(sections, len, inserted < a.i ? a.ins : 0);
- if (insert2 && inserted < a.i)
- addInsert(insert2, sections, a.text);
- inserted = a.i;
- a.forward(a.len - left);
- } else if (a.done && b.done) {
- return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections);
- } else {
- throw new Error("Mismatched change set lengths");
- }
- }
- }
- function composeSets(setA, setB, mkSet = false) {
- let sections = [];
- let insert2 = mkSet ? [] : null;
- let a = new SectionIter(setA), b = new SectionIter(setB);
- for (let open = false; ; ) {
- if (a.done && b.done) {
- return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections);
- } else if (a.ins == 0) {
- addSection(sections, a.len, 0, open);
- a.next();
- } else if (b.len == 0 && !b.done) {
- addSection(sections, 0, b.ins, open);
- if (insert2)
- addInsert(insert2, sections, b.text);
- b.next();
- } else if (a.done || b.done) {
- throw new Error("Mismatched change set lengths");
- } else {
- let len = Math.min(a.len2, b.len), sectionLen = sections.length;
- if (a.ins == -1) {
- let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
- addSection(sections, len, insB, open);
- if (insert2 && insB)
- addInsert(insert2, sections, b.text);
- } else if (b.ins == -1) {
- addSection(sections, a.off ? 0 : a.len, len, open);
- if (insert2)
- addInsert(insert2, sections, a.textBit(len));
- } else {
- addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
- if (insert2 && !b.off)
- addInsert(insert2, sections, b.text);
- }
- open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
- a.forward2(len);
- b.forward(len);
- }
- }
- }
- var SectionIter = class {
- constructor(set2) {
- this.set = set2;
- this.i = 0;
- this.next();
- }
- next() {
- let { sections } = this.set;
- if (this.i < sections.length) {
- this.len = sections[this.i++];
- this.ins = sections[this.i++];
- } else {
- this.len = 0;
- this.ins = -2;
- }
- this.off = 0;
- }
- get done() {
- return this.ins == -2;
- }
- get len2() {
- return this.ins < 0 ? this.len : this.ins;
- }
- get text() {
- let { inserted } = this.set, index = this.i - 2 >> 1;
- return index >= inserted.length ? Text.empty : inserted[index];
- }
- textBit(len) {
- let { inserted } = this.set, index = this.i - 2 >> 1;
- return index >= inserted.length && !len ? Text.empty : inserted[index].slice(this.off, len == null ? void 0 : this.off + len);
- }
- forward(len) {
- if (len == this.len)
- this.next();
- else {
- this.len -= len;
- this.off += len;
- }
- }
- forward2(len) {
- if (this.ins == -1)
- this.forward(len);
- else if (len == this.ins)
- this.next();
- else {
- this.ins -= len;
- this.off += len;
- }
- }
- };
- var SelectionRange = class {
- constructor(from, to, flags) {
- this.from = from;
- this.to = to;
- this.flags = flags;
- }
- /**
- The anchor of the range�봳he side that doesn't move when you
- extend it.
- */
- get anchor() {
- return this.flags & 16 ? this.to : this.from;
- }
- /**
- The head of the range, which is moved when the range is
- [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
- */
- get head() {
- return this.flags & 16 ? this.from : this.to;
- }
- /**
- True when `anchor` and `head` are at the same position.
- */
- get empty() {
- return this.from == this.to;
- }
- /**
- If this is a cursor that is explicitly associated with the
- character on one of its sides, this returns the side. -1 means
- the character before its position, 1 the character after, and 0
- means no association.
- */
- get assoc() {
- return this.flags & 4 ? -1 : this.flags & 8 ? 1 : 0;
- }
- /**
- The bidirectional text level associated with this cursor, if
- any.
- */
- get bidiLevel() {
- let level = this.flags & 3;
- return level == 3 ? null : level;
- }
- /**
- The goal column (stored vertical offset) associated with a
- cursor. This is used to preserve the vertical position when
- [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
- lines of different length.
- */
- get goalColumn() {
- let value = this.flags >> 5;
- return value == 33554431 ? void 0 : value;
- }
- /**
- Map this range through a change, producing a valid range in the
- updated document.
- */
- map(change, assoc = -1) {
- let from, to;
- if (this.empty) {
- from = to = change.mapPos(this.from, assoc);
- } else {
- from = change.mapPos(this.from, 1);
- to = change.mapPos(this.to, -1);
- }
- return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
- }
- /**
- Extend this range to cover at least `from` to `to`.
- */
- extend(from, to = from) {
- if (from <= this.anchor && to >= this.anchor)
- return EditorSelection.range(from, to);
- let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
- return EditorSelection.range(this.anchor, head);
- }
- /**
- Compare this range to another range.
- */
- eq(other) {
- return this.anchor == other.anchor && this.head == other.head;
- }
- /**
- Return a JSON-serializable object representing the range.
- */
- toJSON() {
- return { anchor: this.anchor, head: this.head };
- }
- /**
- Convert a JSON representation of a range to a `SelectionRange`
- instance.
- */
- static fromJSON(json) {
- if (!json || typeof json.anchor != "number" || typeof json.head != "number")
- throw new RangeError("Invalid JSON representation for SelectionRange");
- return EditorSelection.range(json.anchor, json.head);
- }
- /**
- @internal
- */
- static create(from, to, flags) {
- return new SelectionRange(from, to, flags);
- }
- };
- var EditorSelection = class {
- constructor(ranges, mainIndex) {
- this.ranges = ranges;
- this.mainIndex = mainIndex;
- }
- /**
- Map a selection through a change. Used to adjust the selection
- position for changes.
- */
- map(change, assoc = -1) {
- if (change.empty)
- return this;
- return EditorSelection.create(this.ranges.map((r) => r.map(change, assoc)), this.mainIndex);
- }
- /**
- Compare this selection to another selection.
- */
- eq(other) {
- if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex)
- return false;
- for (let i = 0; i < this.ranges.length; i++)
- if (!this.ranges[i].eq(other.ranges[i]))
- return false;
- return true;
- }
- /**
- Get the primary selection range. Usually, you should make sure
- your code applies to _all_ ranges, by using methods like
- [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
- */
- get main() {
- return this.ranges[this.mainIndex];
- }
- /**
- Make sure the selection only has one range. Returns a selection
- holding only the main range from this selection.
- */
- asSingle() {
- return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
- }
- /**
- Extend this selection with an extra range.
- */
- addRange(range, main = true) {
- return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
- }
- /**
- Replace a given range with another range, and then normalize the
- selection to merge and sort ranges if necessary.
- */
- replaceRange(range, which = this.mainIndex) {
- let ranges = this.ranges.slice();
- ranges[which] = range;
- return EditorSelection.create(ranges, this.mainIndex);
- }
- /**
- Convert this selection to an object that can be serialized to
- JSON.
- */
- toJSON() {
- return { ranges: this.ranges.map((r) => r.toJSON()), main: this.mainIndex };
- }
- /**
- Create a selection from a JSON representation.
- */
- static fromJSON(json) {
- if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
- throw new RangeError("Invalid JSON representation for EditorSelection");
- return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
- }
- /**
- Create a selection holding a single range.
- */
- static single(anchor, head = anchor) {
- return new EditorSelection([EditorSelection.range(anchor, head)], 0);
- }
- /**
- Sort and merge the given set of ranges, creating a valid
- selection.
- */
- static create(ranges, mainIndex = 0) {
- if (ranges.length == 0)
- throw new RangeError("A selection needs at least one range");
- for (let pos = 0, i = 0; i < ranges.length; i++) {
- let range = ranges[i];
- if (range.empty ? range.from <= pos : range.from < pos)
- return EditorSelection.normalized(ranges.slice(), mainIndex);
- pos = range.to;
- }
- return new EditorSelection(ranges, mainIndex);
- }
- /**
- Create a cursor selection range at the given position. You can
- safely ignore the optional arguments in most situations.
- */
- static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
- return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 : 8) | (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431) << 5);
- }
- /**
- Create a selection range.
- */
- static range(anchor, head, goalColumn, bidiLevel) {
- let flags = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431) << 5 | (bidiLevel == null ? 3 : Math.min(2, bidiLevel));
- return head < anchor ? SelectionRange.create(head, anchor, 16 | 8 | flags) : SelectionRange.create(anchor, head, (head > anchor ? 4 : 0) | flags);
- }
- /**
- @internal
- */
- static normalized(ranges, mainIndex = 0) {
- let main = ranges[mainIndex];
- ranges.sort((a, b) => a.from - b.from);
- mainIndex = ranges.indexOf(main);
- for (let i = 1; i < ranges.length; i++) {
- let range = ranges[i], prev = ranges[i - 1];
- if (range.empty ? range.from <= prev.to : range.from < prev.to) {
- let from = prev.from, to = Math.max(range.to, prev.to);
- if (i <= mainIndex)
- mainIndex--;
- ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
- }
- }
- return new EditorSelection(ranges, mainIndex);
- }
- };
- function checkSelection(selection2, docLength) {
- for (let range of selection2.ranges)
- if (range.to > docLength)
- throw new RangeError("Selection points outside of document");
- }
- var nextID = 0;
- var Facet = class {
- constructor(combine, compareInput, compare2, isStatic, enables) {
- this.combine = combine;
- this.compareInput = compareInput;
- this.compare = compare2;
- this.isStatic = isStatic;
- this.id = nextID++;
- this.default = combine([]);
- this.extensions = typeof enables == "function" ? enables(this) : enables;
- }
- /**
- Define a new facet.
- */
- static define(config2 = {}) {
- return new Facet(config2.combine || ((a) => a), config2.compareInput || ((a, b) => a === b), config2.compare || (!config2.combine ? sameArray : (a, b) => a === b), !!config2.static, config2.enables);
- }
- /**
- Returns an extension that adds the given value to this facet.
- */
- of(value) {
- return new FacetProvider([], this, 0, value);
- }
- /**
- Create an extension that computes a value for the facet from a
- state. You must take care to declare the parts of the state that
- this value depends on, since your function is only called again
- for a new state when one of those parts changed.
-
- In cases where your value depends only on a single field, you'll
- want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
- */
- compute(deps, get2) {
- if (this.isStatic)
- throw new Error("Can't compute a static facet");
- return new FacetProvider(deps, this, 1, get2);
- }
- /**
- Create an extension that computes zero or more values for this
- facet from a state.
- */
- computeN(deps, get2) {
- if (this.isStatic)
- throw new Error("Can't compute a static facet");
- return new FacetProvider(deps, this, 2, get2);
- }
- from(field, get2) {
- if (!get2)
- get2 = (x) => x;
- return this.compute([field], (state) => get2(state.field(field)));
- }
- };
- function sameArray(a, b) {
- return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
- }
- var FacetProvider = class {
- constructor(dependencies, facet, type, value) {
- this.dependencies = dependencies;
- this.facet = facet;
- this.type = type;
- this.value = value;
- this.id = nextID++;
- }
- dynamicSlot(addresses) {
- var _a2;
- let getter = this.value;
- let compare2 = this.facet.compareInput;
- let id2 = this.id, idx = addresses[id2] >> 1, multi = this.type == 2;
- let depDoc = false, depSel = false, depAddrs = [];
- for (let dep of this.dependencies) {
- if (dep == "doc")
- depDoc = true;
- else if (dep == "selection")
- depSel = true;
- else if ((((_a2 = addresses[dep.id]) !== null && _a2 !== void 0 ? _a2 : 1) & 1) == 0)
- depAddrs.push(addresses[dep.id]);
- }
- return {
- create(state) {
- state.values[idx] = getter(state);
- return 1;
- },
- update(state, tr) {
- if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state, depAddrs)) {
- let newVal = getter(state);
- if (multi ? !compareArray(newVal, state.values[idx], compare2) : !compare2(newVal, state.values[idx])) {
- state.values[idx] = newVal;
- return 1;
- }
- }
- return 0;
- },
- reconfigure: (state, oldState) => {
- let newVal, oldAddr = oldState.config.address[id2];
- if (oldAddr != null) {
- let oldVal = getAddr(oldState, oldAddr);
- if (this.dependencies.every((dep) => {
- return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
- }) || (multi ? compareArray(newVal = getter(state), oldVal, compare2) : compare2(newVal = getter(state), oldVal))) {
- state.values[idx] = oldVal;
- return 0;
- }
- } else {
- newVal = getter(state);
- }
- state.values[idx] = newVal;
- return 1;
- }
- };
- }
- };
- function compareArray(a, b, compare2) {
- if (a.length != b.length)
- return false;
- for (let i = 0; i < a.length; i++)
- if (!compare2(a[i], b[i]))
- return false;
- return true;
- }
- function ensureAll(state, addrs) {
- let changed = false;
- for (let addr of addrs)
- if (ensureAddr(state, addr) & 1)
- changed = true;
- return changed;
- }
- function dynamicFacetSlot(addresses, facet, providers) {
- let providerAddrs = providers.map((p) => addresses[p.id]);
- let providerTypes = providers.map((p) => p.type);
- let dynamic = providerAddrs.filter((p) => !(p & 1));
- let idx = addresses[facet.id] >> 1;
- function get2(state) {
- let values = [];
- for (let i = 0; i < providerAddrs.length; i++) {
- let value = getAddr(state, providerAddrs[i]);
- if (providerTypes[i] == 2)
- for (let val of value)
- values.push(val);
- else
- values.push(value);
- }
- return facet.combine(values);
- }
- return {
- create(state) {
- for (let addr of providerAddrs)
- ensureAddr(state, addr);
- state.values[idx] = get2(state);
- return 1;
- },
- update(state, tr) {
- if (!ensureAll(state, dynamic))
- return 0;
- let value = get2(state);
- if (facet.compare(value, state.values[idx]))
- return 0;
- state.values[idx] = value;
- return 1;
- },
- reconfigure(state, oldState) {
- let depChanged = ensureAll(state, providerAddrs);
- let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
- if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
- state.values[idx] = oldValue;
- return 0;
- }
- let value = get2(state);
- if (facet.compare(value, oldValue)) {
- state.values[idx] = oldValue;
- return 0;
- }
- state.values[idx] = value;
- return 1;
- }
- };
- }
- var initField = /* @__PURE__ */ Facet.define({ static: true });
- var StateField = class {
- constructor(id2, createF, updateF, compareF, spec) {
- this.id = id2;
- this.createF = createF;
- this.updateF = updateF;
- this.compareF = compareF;
- this.spec = spec;
- this.provides = void 0;
- }
- /**
- Define a state field.
- */
- static define(config2) {
- let field = new StateField(nextID++, config2.create, config2.update, config2.compare || ((a, b) => a === b), config2);
- if (config2.provide)
- field.provides = config2.provide(field);
- return field;
- }
- create(state) {
- let init = state.facet(initField).find((i) => i.field == this);
- return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
- }
- /**
- @internal
- */
- slot(addresses) {
- let idx = addresses[this.id] >> 1;
- return {
- create: (state) => {
- state.values[idx] = this.create(state);
- return 1;
- },
- update: (state, tr) => {
- let oldVal = state.values[idx];
- let value = this.updateF(oldVal, tr);
- if (this.compareF(oldVal, value))
- return 0;
- state.values[idx] = value;
- return 1;
- },
- reconfigure: (state, oldState) => {
- if (oldState.config.address[this.id] != null) {
- state.values[idx] = oldState.field(this);
- return 0;
- }
- state.values[idx] = this.create(state);
- return 1;
- }
- };
- }
- /**
- Returns an extension that enables this field and overrides the
- way it is initialized. Can be useful when you need to provide a
- non-default starting value for the field.
- */
- init(create) {
- return [this, initField.of({ field: this, create })];
- }
- /**
- State field instances can be used as
- [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
- given state.
- */
- get extension() {
- return this;
- }
- };
- var Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
- function prec(value) {
- return (ext) => new PrecExtension(ext, value);
- }
- var Prec = {
- /**
- The highest precedence level, for extensions that should end up
- near the start of the precedence ordering.
- */
- highest: /* @__PURE__ */ prec(Prec_.highest),
- /**
- A higher-than-default precedence, for extensions that should
- come before those with default precedence.
- */
- high: /* @__PURE__ */ prec(Prec_.high),
- /**
- The default precedence, which is also used for extensions
- without an explicit precedence.
- */
- default: /* @__PURE__ */ prec(Prec_.default),
- /**
- A lower-than-default precedence.
- */
- low: /* @__PURE__ */ prec(Prec_.low),
- /**
- The lowest precedence level. Meant for things that should end up
- near the end of the extension order.
- */
- lowest: /* @__PURE__ */ prec(Prec_.lowest)
- };
- var PrecExtension = class {
- constructor(inner, prec2) {
- this.inner = inner;
- this.prec = prec2;
- }
- };
- var Compartment = class {
- /**
- Create an instance of this compartment to add to your [state
- configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
- */
- of(ext) {
- return new CompartmentInstance(this, ext);
- }
- /**
- Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
- reconfigures this compartment.
- */
- reconfigure(content2) {
- return Compartment.reconfigure.of({ compartment: this, extension: content2 });
- }
- /**
- Get the current content of the compartment in the state, or
- `undefined` if it isn't present.
- */
- get(state) {
- return state.config.compartments.get(this);
- }
- };
- var CompartmentInstance = class {
- constructor(compartment, inner) {
- this.compartment = compartment;
- this.inner = inner;
- }
- };
- var Configuration = class {
- constructor(base2, compartments, dynamicSlots, address, staticValues, facets) {
- this.base = base2;
- this.compartments = compartments;
- this.dynamicSlots = dynamicSlots;
- this.address = address;
- this.staticValues = staticValues;
- this.facets = facets;
- this.statusTemplate = [];
- while (this.statusTemplate.length < dynamicSlots.length)
- this.statusTemplate.push(
- 0
- /* SlotStatus.Unresolved */
- );
- }
- staticFacet(facet) {
- let addr = this.address[facet.id];
- return addr == null ? facet.default : this.staticValues[addr >> 1];
- }
- static resolve(base2, compartments, oldState) {
- let fields = [];
- let facets = /* @__PURE__ */ Object.create(null);
- let newCompartments = /* @__PURE__ */ new Map();
- for (let ext of flatten(base2, compartments, newCompartments)) {
- if (ext instanceof StateField)
- fields.push(ext);
- else
- (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
- }
- let address = /* @__PURE__ */ Object.create(null);
- let staticValues = [];
- let dynamicSlots = [];
- for (let field of fields) {
- address[field.id] = dynamicSlots.length << 1;
- dynamicSlots.push((a) => field.slot(a));
- }
- let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
- for (let id2 in facets) {
- let providers = facets[id2], facet = providers[0].facet;
- let oldProviders = oldFacets && oldFacets[id2] || [];
- if (providers.every(
- (p) => p.type == 0
- /* Provider.Static */
- )) {
- address[facet.id] = staticValues.length << 1 | 1;
- if (sameArray(oldProviders, providers)) {
- staticValues.push(oldState.facet(facet));
- } else {
- let value = facet.combine(providers.map((p) => p.value));
- staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
- }
- } else {
- for (let p of providers) {
- if (p.type == 0) {
- address[p.id] = staticValues.length << 1 | 1;
- staticValues.push(p.value);
- } else {
- address[p.id] = dynamicSlots.length << 1;
- dynamicSlots.push((a) => p.dynamicSlot(a));
- }
- }
- address[facet.id] = dynamicSlots.length << 1;
- dynamicSlots.push((a) => dynamicFacetSlot(a, facet, providers));
- }
- }
- let dynamic = dynamicSlots.map((f) => f(address));
- return new Configuration(base2, newCompartments, dynamic, address, staticValues, facets);
- }
- };
- function flatten(extension, compartments, newCompartments) {
- let result = [[], [], [], [], []];
- let seen = /* @__PURE__ */ new Map();
- function inner(ext, prec2) {
- let known = seen.get(ext);
- if (known != null) {
- if (known <= prec2)
- return;
- let found = result[known].indexOf(ext);
- if (found > -1)
- result[known].splice(found, 1);
- if (ext instanceof CompartmentInstance)
- newCompartments.delete(ext.compartment);
- }
- seen.set(ext, prec2);
- if (Array.isArray(ext)) {
- for (let e of ext)
- inner(e, prec2);
- } else if (ext instanceof CompartmentInstance) {
- if (newCompartments.has(ext.compartment))
- throw new RangeError(`Duplicate use of compartment in extensions`);
- let content2 = compartments.get(ext.compartment) || ext.inner;
- newCompartments.set(ext.compartment, content2);
- inner(content2, prec2);
- } else if (ext instanceof PrecExtension) {
- inner(ext.inner, ext.prec);
- } else if (ext instanceof StateField) {
- result[prec2].push(ext);
- if (ext.provides)
- inner(ext.provides, prec2);
- } else if (ext instanceof FacetProvider) {
- result[prec2].push(ext);
- if (ext.facet.extensions)
- inner(ext.facet.extensions, Prec_.default);
- } else {
- let content2 = ext.extension;
- if (!content2)
- throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
- inner(content2, prec2);
- }
- }
- inner(extension, Prec_.default);
- return result.reduce((a, b) => a.concat(b));
- }
- function ensureAddr(state, addr) {
- if (addr & 1)
- return 2;
- let idx = addr >> 1;
- let status = state.status[idx];
- if (status == 4)
- throw new Error("Cyclic dependency between fields and/or facets");
- if (status & 2)
- return status;
- state.status[idx] = 4;
- let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
- return state.status[idx] = 2 | changed;
- }
- function getAddr(state, addr) {
- return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
- }
- var languageData = /* @__PURE__ */ Facet.define();
- var allowMultipleSelections = /* @__PURE__ */ Facet.define({
- combine: (values) => values.some((v) => v),
- static: true
- });
- var lineSeparator = /* @__PURE__ */ Facet.define({
- combine: (values) => values.length ? values[0] : void 0,
- static: true
- });
- var changeFilter = /* @__PURE__ */ Facet.define();
- var transactionFilter = /* @__PURE__ */ Facet.define();
- var transactionExtender = /* @__PURE__ */ Facet.define();
- var readOnly = /* @__PURE__ */ Facet.define({
- combine: (values) => values.length ? values[0] : false
- });
- var Annotation = class {
- /**
- @internal
- */
- constructor(type, value) {
- this.type = type;
- this.value = value;
- }
- /**
- Define a new type of annotation.
- */
- static define() {
- return new AnnotationType();
- }
- };
- var AnnotationType = class {
- /**
- Create an instance of this annotation.
- */
- of(value) {
- return new Annotation(this, value);
- }
- };
- var StateEffectType = class {
- /**
- @internal
- */
- constructor(map) {
- this.map = map;
- }
- /**
- Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
- type.
- */
- of(value) {
- return new StateEffect(this, value);
- }
- };
- var StateEffect = class {
- /**
- @internal
- */
- constructor(type, value) {
- this.type = type;
- this.value = value;
- }
- /**
- Map this effect through a position mapping. Will return
- `undefined` when that ends up deleting the effect.
- */
- map(mapping) {
- let mapped = this.type.map(this.value, mapping);
- return mapped === void 0 ? void 0 : mapped == this.value ? this : new StateEffect(this.type, mapped);
- }
- /**
- Tells you whether this effect object is of a given
- [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
- */
- is(type) {
- return this.type == type;
- }
- /**
- Define a new effect type. The type parameter indicates the type
- of values that his effect holds.
- */
- static define(spec = {}) {
- return new StateEffectType(spec.map || ((v) => v));
- }
- /**
- Map an array of effects through a change set.
- */
- static mapEffects(effects, mapping) {
- if (!effects.length)
- return effects;
- let result = [];
- for (let effect of effects) {
- let mapped = effect.map(mapping);
- if (mapped)
- result.push(mapped);
- }
- return result;
- }
- };
- StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define();
- StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define();
- var Transaction = class {
- constructor(startState, changes, selection2, effects, annotations, scrollIntoView3) {
- this.startState = startState;
- this.changes = changes;
- this.selection = selection2;
- this.effects = effects;
- this.annotations = annotations;
- this.scrollIntoView = scrollIntoView3;
- this._doc = null;
- this._state = null;
- if (selection2)
- checkSelection(selection2, changes.newLength);
- if (!annotations.some((a) => a.type == Transaction.time))
- this.annotations = annotations.concat(Transaction.time.of(Date.now()));
- }
- /**
- @internal
- */
- static create(startState, changes, selection2, effects, annotations, scrollIntoView3) {
- return new Transaction(startState, changes, selection2, effects, annotations, scrollIntoView3);
- }
- /**
- The new document produced by the transaction. Contrary to
- [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
- force the entire new state to be computed right away, so it is
- recommended that [transaction
- filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
- when they need to look at the new document.
- */
- get newDoc() {
- return this._doc || (this._doc = this.changes.apply(this.startState.doc));
- }
- /**
- The new selection produced by the transaction. If
- [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
- this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
- current selection through the changes made by the transaction.
- */
- get newSelection() {
- return this.selection || this.startState.selection.map(this.changes);
- }
- /**
- The new state created by the transaction. Computed on demand
- (but retained for subsequent access), so it is recommended not to
- access it in [transaction
- filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
- */
- get state() {
- if (!this._state)
- this.startState.applyTransaction(this);
- return this._state;
- }
- /**
- Get the value of the given annotation type, if any.
- */
- annotation(type) {
- for (let ann of this.annotations)
- if (ann.type == type)
- return ann.value;
- return void 0;
- }
- /**
- Indicates whether the transaction changed the document.
- */
- get docChanged() {
- return !this.changes.empty;
- }
- /**
- Indicates whether this transaction reconfigures the state
- (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
- with a top-level configuration
- [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
- */
- get reconfigured() {
- return this.startState.config != this.state.config;
- }
- /**
- Returns true if the transaction has a [user
- event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
- or more specific than `event`. For example, if the transaction
- has `"select.pointer"` as user event, `"select"` and
- `"select.pointer"` will match it.
- */
- isUserEvent(event) {
- let e = this.annotation(Transaction.userEvent);
- return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
- }
- };
- Transaction.time = /* @__PURE__ */ Annotation.define();
- Transaction.userEvent = /* @__PURE__ */ Annotation.define();
- Transaction.addToHistory = /* @__PURE__ */ Annotation.define();
- Transaction.remote = /* @__PURE__ */ Annotation.define();
- function joinRanges(a, b) {
- let result = [];
- for (let iA = 0, iB = 0; ; ) {
- let from, to;
- if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
- from = a[iA++];
- to = a[iA++];
- } else if (iB < b.length) {
- from = b[iB++];
- to = b[iB++];
- } else
- return result;
- if (!result.length || result[result.length - 1] < from)
- result.push(from, to);
- else if (result[result.length - 1] < to)
- result[result.length - 1] = to;
- }
- }
- function mergeTransaction(a, b, sequential) {
- var _a2;
- let mapForA, mapForB, changes;
- if (sequential) {
- mapForA = b.changes;
- mapForB = ChangeSet.empty(b.changes.length);
- changes = a.changes.compose(b.changes);
- } else {
- mapForA = b.changes.map(a.changes);
- mapForB = a.changes.mapDesc(b.changes, true);
- changes = a.changes.compose(mapForA);
- }
- return {
- changes,
- selection: b.selection ? b.selection.map(mapForB) : (_a2 = a.selection) === null || _a2 === void 0 ? void 0 : _a2.map(mapForA),
- effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
- annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
- scrollIntoView: a.scrollIntoView || b.scrollIntoView
- };
- }
- function resolveTransactionInner(state, spec, docSize) {
- let sel = spec.selection, annotations = asArray(spec.annotations);
- if (spec.userEvent)
- annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
- return {
- changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
- selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
- effects: asArray(spec.effects),
- annotations,
- scrollIntoView: !!spec.scrollIntoView
- };
- }
- function resolveTransaction(state, specs, filter) {
- let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
- if (specs.length && specs[0].filter === false)
- filter = false;
- for (let i = 1; i < specs.length; i++) {
- if (specs[i].filter === false)
- filter = false;
- let seq = !!specs[i].sequential;
- s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
- }
- let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
- return extendTransaction(filter ? filterTransaction(tr) : tr);
- }
- function filterTransaction(tr) {
- let state = tr.startState;
- let result = true;
- for (let filter of state.facet(changeFilter)) {
- let value = filter(tr);
- if (value === false) {
- result = false;
- break;
- }
- if (Array.isArray(value))
- result = result === true ? value : joinRanges(result, value);
- }
- if (result !== true) {
- let changes, back;
- if (result === false) {
- back = tr.changes.invertedDesc;
- changes = ChangeSet.empty(state.doc.length);
- } else {
- let filtered = tr.changes.filter(result);
- changes = filtered.changes;
- back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
- }
- tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
- }
- let filters = state.facet(transactionFilter);
- for (let i = filters.length - 1; i >= 0; i--) {
- let filtered = filters[i](tr);
- if (filtered instanceof Transaction)
- tr = filtered;
- else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
- tr = filtered[0];
- else
- tr = resolveTransaction(state, asArray(filtered), false);
- }
- return tr;
- }
- function extendTransaction(tr) {
- let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
- for (let i = extenders.length - 1; i >= 0; i--) {
- let extension = extenders[i](tr);
- if (extension && Object.keys(extension).length)
- spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
- }
- return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
- }
- var none = [];
- function asArray(value) {
- return value == null ? none : Array.isArray(value) ? value : [value];
- }
- var CharCategory = /* @__PURE__ */ function(CharCategory2) {
- CharCategory2[CharCategory2["Word"] = 0] = "Word";
- CharCategory2[CharCategory2["Space"] = 1] = "Space";
- CharCategory2[CharCategory2["Other"] = 2] = "Other";
- return CharCategory2;
- }(CharCategory || (CharCategory = {}));
- var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
- var wordChar;
- try {
- wordChar = /* @__PURE__ */ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
- } catch (_) {
- }
- function hasWordChar(str) {
- if (wordChar)
- return wordChar.test(str);
- for (let i = 0; i < str.length; i++) {
- let ch = str[i];
- if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
- return true;
- }
- return false;
- }
- function makeCategorizer(wordChars) {
- return (char) => {
- if (!/\S/.test(char))
- return CharCategory.Space;
- if (hasWordChar(char))
- return CharCategory.Word;
- for (let i = 0; i < wordChars.length; i++)
- if (char.indexOf(wordChars[i]) > -1)
- return CharCategory.Word;
- return CharCategory.Other;
- };
- }
- var EditorState = class {
- constructor(config2, doc2, selection2, values, computeSlot, tr) {
- this.config = config2;
- this.doc = doc2;
- this.selection = selection2;
- this.values = values;
- this.status = config2.statusTemplate.slice();
- this.computeSlot = computeSlot;
- if (tr)
- tr._state = this;
- for (let i = 0; i < this.config.dynamicSlots.length; i++)
- ensureAddr(this, i << 1);
- this.computeSlot = null;
- }
- field(field, require2 = true) {
- let addr = this.config.address[field.id];
- if (addr == null) {
- if (require2)
- throw new RangeError("Field is not present in this state");
- return void 0;
- }
- ensureAddr(this, addr);
- return getAddr(this, addr);
- }
- /**
- Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
- state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
- can be passed. Unless
- [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
- [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
- are assumed to start in the _current_ document (not the document
- produced by previous specs), and its
- [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
- [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
- to the document created by its _own_ changes. The resulting
- transaction contains the combined effect of all the different
- specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
- specs take precedence over earlier ones.
- */
- update(...specs) {
- return resolveTransaction(this, specs, true);
- }
- /**
- @internal
- */
- applyTransaction(tr) {
- let conf = this.config, { base: base2, compartments } = conf;
- for (let effect of tr.effects) {
- if (effect.is(Compartment.reconfigure)) {
- if (conf) {
- compartments = /* @__PURE__ */ new Map();
- conf.compartments.forEach((val, key) => compartments.set(key, val));
- conf = null;
- }
- compartments.set(effect.value.compartment, effect.value.extension);
- } else if (effect.is(StateEffect.reconfigure)) {
- conf = null;
- base2 = effect.value;
- } else if (effect.is(StateEffect.appendConfig)) {
- conf = null;
- base2 = asArray(base2).concat(effect.value);
- }
- }
- let startValues;
- if (!conf) {
- conf = Configuration.resolve(base2, compartments, this);
- let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
- startValues = intermediateState.values;
- } else {
- startValues = tr.startState.values.slice();
- }
- new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr);
- }
- /**
- Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
- replaces every selection range with the given content.
- */
- replaceSelection(text) {
- if (typeof text == "string")
- text = this.toText(text);
- return this.changeByRange((range) => ({
- changes: { from: range.from, to: range.to, insert: text },
- range: EditorSelection.cursor(range.from + text.length)
- }));
- }
- /**
- Create a set of changes and a new selection by running the given
- function for each range in the active selection. The function
- can return an optional set of changes (in the coordinate space
- of the start document), plus an updated range (in the coordinate
- space of the document produced by the call's own changes). This
- method will merge all the changes and ranges into a single
- changeset and selection, and return it as a [transaction
- spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
- [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
- */
- changeByRange(f) {
- let sel = this.selection;
- let result1 = f(sel.ranges[0]);
- let changes = this.changes(result1.changes), ranges = [result1.range];
- let effects = asArray(result1.effects);
- for (let i = 1; i < sel.ranges.length; i++) {
- let result = f(sel.ranges[i]);
- let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
- for (let j = 0; j < i; j++)
- ranges[j] = ranges[j].map(newMapped);
- let mapBy = changes.mapDesc(newChanges, true);
- ranges.push(result.range.map(mapBy));
- changes = changes.compose(newMapped);
- effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
- }
- return {
- changes,
- selection: EditorSelection.create(ranges, sel.mainIndex),
- effects
- };
- }
- /**
- Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
- description, taking the state's document length and line
- separator into account.
- */
- changes(spec = []) {
- if (spec instanceof ChangeSet)
- return spec;
- return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
- }
- /**
- Using the state's [line
- separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
- [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
- */
- toText(string2) {
- return Text.of(string2.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
- }
- /**
- Return the given range of the document as a string.
- */
- sliceDoc(from = 0, to = this.doc.length) {
- return this.doc.sliceString(from, to, this.lineBreak);
- }
- /**
- Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
- */
- facet(facet) {
- let addr = this.config.address[facet.id];
- if (addr == null)
- return facet.default;
- ensureAddr(this, addr);
- return getAddr(this, addr);
- }
- /**
- Convert this state to a JSON-serializable object. When custom
- fields should be serialized, you can pass them in as an object
- mapping property names (in the resulting object, which should
- not use `doc` or `selection`) to fields.
- */
- toJSON(fields) {
- let result = {
- doc: this.sliceDoc(),
- selection: this.selection.toJSON()
- };
- if (fields)
- for (let prop in fields) {
- let value = fields[prop];
- if (value instanceof StateField && this.config.address[value.id] != null)
- result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
- }
- return result;
- }
- /**
- Deserialize a state from its JSON representation. When custom
- fields should be deserialized, pass the same object you passed
- to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
- third argument.
- */
- static fromJSON(json, config2 = {}, fields) {
- if (!json || typeof json.doc != "string")
- throw new RangeError("Invalid JSON representation for EditorState");
- let fieldInit = [];
- if (fields)
- for (let prop in fields) {
- if (Object.prototype.hasOwnProperty.call(json, prop)) {
- let field = fields[prop], value = json[prop];
- fieldInit.push(field.init((state) => field.spec.fromJSON(value, state)));
- }
- }
- return EditorState.create({
- doc: json.doc,
- selection: EditorSelection.fromJSON(json.selection),
- extensions: config2.extensions ? fieldInit.concat([config2.extensions]) : fieldInit
- });
- }
- /**
- Create a new state. You'll usually only need this when
- initializing an editor�봴pdated states are created by applying
- transactions.
- */
- static create(config2 = {}) {
- let configuration = Configuration.resolve(config2.extensions || [], /* @__PURE__ */ new Map());
- let doc2 = config2.doc instanceof Text ? config2.doc : Text.of((config2.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
- let selection2 = !config2.selection ? EditorSelection.single(0) : config2.selection instanceof EditorSelection ? config2.selection : EditorSelection.single(config2.selection.anchor, config2.selection.head);
- checkSelection(selection2, doc2.length);
- if (!configuration.staticFacet(allowMultipleSelections))
- selection2 = selection2.asSingle();
- return new EditorState(configuration, doc2, selection2, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
- }
- /**
- The size (in columns) of a tab in the document, determined by
- the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
- */
- get tabSize() {
- return this.facet(EditorState.tabSize);
- }
- /**
- Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
- string for this state.
- */
- get lineBreak() {
- return this.facet(EditorState.lineSeparator) || "\n";
- }
- /**
- Returns true when the editor is
- [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
- */
- get readOnly() {
- return this.facet(readOnly);
- }
- /**
- Look up a translation for the given phrase (via the
- [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
- original string if no translation is found.
-
- If additional arguments are passed, they will be inserted in
- place of markers like `$1` (for the first value) and `$2`, etc.
- A single `$` is equivalent to `$1`, and `$$` will produce a
- literal dollar sign.
- */
- phrase(phrase2, ...insert2) {
- for (let map of this.facet(EditorState.phrases))
- if (Object.prototype.hasOwnProperty.call(map, phrase2)) {
- phrase2 = map[phrase2];
- break;
- }
- if (insert2.length)
- phrase2 = phrase2.replace(/\$(\$|\d*)/g, (m, i) => {
- if (i == "$")
- return "$";
- let n = +(i || 1);
- return !n || n > insert2.length ? m : insert2[n - 1];
- });
- return phrase2;
- }
- /**
- Find the values for a given language data field, provided by the
- the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
-
- Examples of language data fields are...
-
- - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
- comment syntax.
- - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
- for providing language-specific completion sources.
- - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
- characters that should be considered part of words in this
- language.
- - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
- bracket closing behavior.
- */
- languageDataAt(name2, pos, side = -1) {
- let values = [];
- for (let provider of this.facet(languageData)) {
- for (let result of provider(this, pos, side)) {
- if (Object.prototype.hasOwnProperty.call(result, name2))
- values.push(result[name2]);
- }
- }
- return values;
- }
- /**
- Return a function that can categorize strings (expected to
- represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
- into one of:
-
- - Word (contains an alphanumeric character or a character
- explicitly listed in the local language's `"wordChars"`
- language data, which should be a string)
- - Space (contains only whitespace)
- - Other (anything else)
- */
- charCategorizer(at) {
- return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
- }
- /**
- Find the word at the given position, meaning the range
- containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
- around it. If no word characters are adjacent to the position,
- this returns null.
- */
- wordAt(pos) {
- let { text, from, length } = this.doc.lineAt(pos);
- let cat = this.charCategorizer(pos);
- let start = pos - from, end = pos - from;
- while (start > 0) {
- let prev = findClusterBreak(text, start, false);
- if (cat(text.slice(prev, start)) != CharCategory.Word)
- break;
- start = prev;
- }
- while (end < length) {
- let next = findClusterBreak(text, end);
- if (cat(text.slice(end, next)) != CharCategory.Word)
- break;
- end = next;
- }
- return start == end ? null : EditorSelection.range(start + from, end + from);
- }
- };
- EditorState.allowMultipleSelections = allowMultipleSelections;
- EditorState.tabSize = /* @__PURE__ */ Facet.define({
- combine: (values) => values.length ? values[0] : 4
- });
- EditorState.lineSeparator = lineSeparator;
- EditorState.readOnly = readOnly;
- EditorState.phrases = /* @__PURE__ */ Facet.define({
- compare(a, b) {
- let kA = Object.keys(a), kB = Object.keys(b);
- return kA.length == kB.length && kA.every((k) => a[k] == b[k]);
- }
- });
- EditorState.languageData = languageData;
- EditorState.changeFilter = changeFilter;
- EditorState.transactionFilter = transactionFilter;
- EditorState.transactionExtender = transactionExtender;
- Compartment.reconfigure = /* @__PURE__ */ StateEffect.define();
- function combineConfig(configs, defaults3, combine = {}) {
- let result = {};
- for (let config2 of configs)
- for (let key of Object.keys(config2)) {
- let value = config2[key], current = result[key];
- if (current === void 0)
- result[key] = value;
- else if (current === value || value === void 0)
- ;
- else if (Object.hasOwnProperty.call(combine, key))
- result[key] = combine[key](current, value);
- else
- throw new Error("Config merge conflict for field " + key);
- }
- for (let key in defaults3)
- if (result[key] === void 0)
- result[key] = defaults3[key];
- return result;
- }
- var RangeValue = class {
- /**
- Compare this value with another value. Used when comparing
- rangesets. The default implementation compares by identity.
- Unless you are only creating a fixed number of unique instances
- of your value type, it is a good idea to implement this
- properly.
- */
- eq(other) {
- return this == other;
- }
- /**
- Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
- */
- range(from, to = from) {
- return Range.create(from, to, this);
- }
- };
- RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
- RangeValue.prototype.point = false;
- RangeValue.prototype.mapMode = MapMode.TrackDel;
- var Range = class {
- constructor(from, to, value) {
- this.from = from;
- this.to = to;
- this.value = value;
- }
- /**
- @internal
- */
- static create(from, to, value) {
- return new Range(from, to, value);
- }
- };
- function cmpRange(a, b) {
- return a.from - b.from || a.value.startSide - b.value.startSide;
- }
- var Chunk = class {
- constructor(from, to, value, maxPoint) {
- this.from = from;
- this.to = to;
- this.value = value;
- this.maxPoint = maxPoint;
- }
- get length() {
- return this.to[this.to.length - 1];
- }
- // Find the index of the given position and side. Use the ranges'
- // `from` pos when `end == false`, `to` when `end == true`.
- findIndex(pos, side, end, startAt = 0) {
- let arr = end ? this.to : this.from;
- for (let lo = startAt, hi = arr.length; ; ) {
- if (lo == hi)
- return lo;
- let mid = lo + hi >> 1;
- let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
- if (mid == lo)
- return diff >= 0 ? lo : hi;
- if (diff >= 0)
- hi = mid;
- else
- lo = mid + 1;
- }
- }
- between(offset, from, to, f) {
- for (let i = this.findIndex(from, -1e9, true), e = this.findIndex(to, 1e9, false, i); i < e; i++)
- if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
- return false;
- }
- map(offset, changes) {
- let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
- for (let i = 0; i < this.value.length; i++) {
- let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
- if (curFrom == curTo) {
- let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
- if (mapped == null)
- continue;
- newFrom = newTo = mapped;
- if (val.startSide != val.endSide) {
- newTo = changes.mapPos(curFrom, val.endSide);
- if (newTo < newFrom)
- continue;
- }
- } else {
- newFrom = changes.mapPos(curFrom, val.startSide);
- newTo = changes.mapPos(curTo, val.endSide);
- if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
- continue;
- }
- if ((newTo - newFrom || val.endSide - val.startSide) < 0)
- continue;
- if (newPos < 0)
- newPos = newFrom;
- if (val.point)
- maxPoint = Math.max(maxPoint, newTo - newFrom);
- value.push(val);
- from.push(newFrom - newPos);
- to.push(newTo - newPos);
- }
- return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
- }
- };
- var RangeSet = class {
- constructor(chunkPos, chunk, nextLayer, maxPoint) {
- this.chunkPos = chunkPos;
- this.chunk = chunk;
- this.nextLayer = nextLayer;
- this.maxPoint = maxPoint;
- }
- /**
- @internal
- */
- static create(chunkPos, chunk, nextLayer, maxPoint) {
- return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
- }
- /**
- @internal
- */
- get length() {
- let last = this.chunk.length - 1;
- return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
- }
- /**
- The number of ranges in the set.
- */
- get size() {
- if (this.isEmpty)
- return 0;
- let size = this.nextLayer.size;
- for (let chunk of this.chunk)
- size += chunk.value.length;
- return size;
- }
- /**
- @internal
- */
- chunkEnd(index) {
- return this.chunkPos[index] + this.chunk[index].length;
- }
- /**
- Update the range set, optionally adding new ranges or filtering
- out existing ones.
-
- (Note: The type parameter is just there as a kludge to work
- around TypeScript variance issues that prevented `RangeSet`
- from being a subtype of `RangeSet` when `X` is a subtype of
- `Y`.)
- */
- update(updateSpec) {
- let { add: add2 = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
- let filter = updateSpec.filter;
- if (add2.length == 0 && !filter)
- return this;
- if (sort)
- add2 = add2.slice().sort(cmpRange);
- if (this.isEmpty)
- return add2.length ? RangeSet.of(add2) : this;
- let cur2 = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
- let builder = new RangeSetBuilder();
- while (cur2.value || i < add2.length) {
- if (i < add2.length && (cur2.from - add2[i].from || cur2.startSide - add2[i].value.startSide) >= 0) {
- let range = add2[i++];
- if (!builder.addInner(range.from, range.to, range.value))
- spill.push(range);
- } else if (cur2.rangeIndex == 1 && cur2.chunkIndex < this.chunk.length && (i == add2.length || this.chunkEnd(cur2.chunkIndex) < add2[i].from) && (!filter || filterFrom > this.chunkEnd(cur2.chunkIndex) || filterTo < this.chunkPos[cur2.chunkIndex]) && builder.addChunk(this.chunkPos[cur2.chunkIndex], this.chunk[cur2.chunkIndex])) {
- cur2.nextChunk();
- } else {
- if (!filter || filterFrom > cur2.to || filterTo < cur2.from || filter(cur2.from, cur2.to, cur2.value)) {
- if (!builder.addInner(cur2.from, cur2.to, cur2.value))
- spill.push(Range.create(cur2.from, cur2.to, cur2.value));
- }
- cur2.next();
- }
- }
- return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
- }
- /**
- Map this range set through a set of changes, return the new set.
- */
- map(changes) {
- if (changes.empty || this.isEmpty)
- return this;
- let chunks = [], chunkPos = [], maxPoint = -1;
- for (let i = 0; i < this.chunk.length; i++) {
- let start = this.chunkPos[i], chunk = this.chunk[i];
- let touch = changes.touchesRange(start, start + chunk.length);
- if (touch === false) {
- maxPoint = Math.max(maxPoint, chunk.maxPoint);
- chunks.push(chunk);
- chunkPos.push(changes.mapPos(start));
- } else if (touch === true) {
- let { mapped, pos } = chunk.map(start, changes);
- if (mapped) {
- maxPoint = Math.max(maxPoint, mapped.maxPoint);
- chunks.push(mapped);
- chunkPos.push(pos);
- }
- }
- }
- let next = this.nextLayer.map(changes);
- return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
- }
- /**
- Iterate over the ranges that touch the region `from` to `to`,
- calling `f` for each. There is no guarantee that the ranges will
- be reported in any specific order. When the callback returns
- `false`, iteration stops.
- */
- between(from, to, f) {
- if (this.isEmpty)
- return;
- for (let i = 0; i < this.chunk.length; i++) {
- let start = this.chunkPos[i], chunk = this.chunk[i];
- if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === false)
- return;
- }
- this.nextLayer.between(from, to, f);
- }
- /**
- Iterate over the ranges in this set, in order, including all
- ranges that end at or after `from`.
- */
- iter(from = 0) {
- return HeapCursor.from([this]).goto(from);
- }
- /**
- @internal
- */
- get isEmpty() {
- return this.nextLayer == this;
- }
- /**
- Iterate over the ranges in a collection of sets, in order,
- starting from `from`.
- */
- static iter(sets, from = 0) {
- return HeapCursor.from(sets).goto(from);
- }
- /**
- Iterate over two groups of sets, calling methods on `comparator`
- to notify it of possible differences.
- */
- static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) {
- let a = oldSets.filter((set2) => set2.maxPoint > 0 || !set2.isEmpty && set2.maxPoint >= minPointSize);
- let b = newSets.filter((set2) => set2.maxPoint > 0 || !set2.isEmpty && set2.maxPoint >= minPointSize);
- let sharedChunks = findSharedChunks(a, b, textDiff);
- let sideA = new SpanCursor(a, sharedChunks, minPointSize);
- let sideB = new SpanCursor(b, sharedChunks, minPointSize);
- textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
- if (textDiff.empty && textDiff.length == 0)
- compare(sideA, 0, sideB, 0, 0, comparator);
- }
- /**
- Compare the contents of two groups of range sets, returning true
- if they are equivalent in the given range.
- */
- static eq(oldSets, newSets, from = 0, to) {
- if (to == null)
- to = 1e9 - 1;
- let a = oldSets.filter((set2) => !set2.isEmpty && newSets.indexOf(set2) < 0);
- let b = newSets.filter((set2) => !set2.isEmpty && oldSets.indexOf(set2) < 0);
- if (a.length != b.length)
- return false;
- if (!a.length)
- return true;
- let sharedChunks = findSharedChunks(a, b);
- let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
- for (; ; ) {
- if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))
- return false;
- if (sideA.to > to)
- return true;
- sideA.next();
- sideB.next();
- }
- }
- /**
- Iterate over a group of range sets at the same time, notifying
- the iterator about the ranges covering every given piece of
- content. Returns the open count (see
- [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
- of the iteration.
- */
- static spans(sets, from, to, iterator2, minPointSize = -1) {
- let cursor2 = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
- let openRanges = cursor2.openStart;
- for (; ; ) {
- let curTo = Math.min(cursor2.to, to);
- if (cursor2.point) {
- let active = cursor2.activeForPoint(cursor2.to);
- let openCount = cursor2.pointFrom < from ? active.length + 1 : Math.min(active.length, openRanges);
- iterator2.point(pos, curTo, cursor2.point, active, openCount, cursor2.pointRank);
- openRanges = Math.min(cursor2.openEnd(curTo), active.length);
- } else if (curTo > pos) {
- iterator2.span(pos, curTo, cursor2.active, openRanges);
- openRanges = cursor2.openEnd(curTo);
- }
- if (cursor2.to > to)
- return openRanges + (cursor2.point && cursor2.to > to ? 1 : 0);
- pos = cursor2.to;
- cursor2.next();
- }
- }
- /**
- Create a range set for the given range or array of ranges. By
- default, this expects the ranges to be _sorted_ (by start
- position and, if two start at the same position,
- `value.startSide`). You can pass `true` as second argument to
- cause the method to sort them.
- */
- static of(ranges, sort = false) {
- let build = new RangeSetBuilder();
- for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)
- build.add(range.from, range.to, range.value);
- return build.finish();
- }
- };
- RangeSet.empty = /* @__PURE__ */ new RangeSet([], [], null, -1);
- function lazySort(ranges) {
- if (ranges.length > 1)
- for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
- let cur2 = ranges[i];
- if (cmpRange(prev, cur2) > 0)
- return ranges.slice().sort(cmpRange);
- prev = cur2;
- }
- return ranges;
- }
- RangeSet.empty.nextLayer = RangeSet.empty;
- var RangeSetBuilder = class {
- /**
- Create an empty builder.
- */
- constructor() {
- this.chunks = [];
- this.chunkPos = [];
- this.chunkStart = -1;
- this.last = null;
- this.lastFrom = -1e9;
- this.lastTo = -1e9;
- this.from = [];
- this.to = [];
- this.value = [];
- this.maxPoint = -1;
- this.setMaxPoint = -1;
- this.nextLayer = null;
- }
- finishChunk(newArrays) {
- this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
- this.chunkPos.push(this.chunkStart);
- this.chunkStart = -1;
- this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
- this.maxPoint = -1;
- if (newArrays) {
- this.from = [];
- this.to = [];
- this.value = [];
- }
- }
- /**
- Add a range. Ranges should be added in sorted (by `from` and
- `value.startSide`) order.
- */
- add(from, to, value) {
- if (!this.addInner(from, to, value))
- (this.nextLayer || (this.nextLayer = new RangeSetBuilder())).add(from, to, value);
- }
- /**
- @internal
- */
- addInner(from, to, value) {
- let diff = from - this.lastTo || value.startSide - this.last.endSide;
- if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
- throw new Error("Ranges must be added sorted by `from` position and `startSide`");
- if (diff < 0)
- return false;
- if (this.from.length == 250)
- this.finishChunk(true);
- if (this.chunkStart < 0)
- this.chunkStart = from;
- this.from.push(from - this.chunkStart);
- this.to.push(to - this.chunkStart);
- this.last = value;
- this.lastFrom = from;
- this.lastTo = to;
- this.value.push(value);
- if (value.point)
- this.maxPoint = Math.max(this.maxPoint, to - from);
- return true;
- }
- /**
- @internal
- */
- addChunk(from, chunk) {
- if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
- return false;
- if (this.from.length)
- this.finishChunk(true);
- this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
- this.chunks.push(chunk);
- this.chunkPos.push(from);
- let last = chunk.value.length - 1;
- this.last = chunk.value[last];
- this.lastFrom = chunk.from[last] + from;
- this.lastTo = chunk.to[last] + from;
- return true;
- }
- /**
- Finish the range set. Returns the new set. The builder can't be
- used anymore after this has been called.
- */
- finish() {
- return this.finishInner(RangeSet.empty);
- }
- /**
- @internal
- */
- finishInner(next) {
- if (this.from.length)
- this.finishChunk(false);
- if (this.chunks.length == 0)
- return next;
- let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
- this.from = null;
- return result;
- }
- };
- function findSharedChunks(a, b, textDiff) {
- let inA = /* @__PURE__ */ new Map();
- for (let set2 of a)
- for (let i = 0; i < set2.chunk.length; i++)
- if (set2.chunk[i].maxPoint <= 0)
- inA.set(set2.chunk[i], set2.chunkPos[i]);
- let shared = /* @__PURE__ */ new Set();
- for (let set2 of b)
- for (let i = 0; i < set2.chunk.length; i++) {
- let known = inA.get(set2.chunk[i]);
- if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set2.chunkPos[i] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set2.chunk[i].length)))
- shared.add(set2.chunk[i]);
- }
- return shared;
- }
- var LayerCursor = class {
- constructor(layer2, skip, minPoint, rank = 0) {
- this.layer = layer2;
- this.skip = skip;
- this.minPoint = minPoint;
- this.rank = rank;
- }
- get startSide() {
- return this.value ? this.value.startSide : 0;
- }
- get endSide() {
- return this.value ? this.value.endSide : 0;
- }
- goto(pos, side = -1e9) {
- this.chunkIndex = this.rangeIndex = 0;
- this.gotoInner(pos, side, false);
- return this;
- }
- gotoInner(pos, side, forward) {
- while (this.chunkIndex < this.layer.chunk.length) {
- let next = this.layer.chunk[this.chunkIndex];
- if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint))
- break;
- this.chunkIndex++;
- forward = false;
- }
- if (this.chunkIndex < this.layer.chunk.length) {
- let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
- if (!forward || this.rangeIndex < rangeIndex)
- this.setRangeIndex(rangeIndex);
- }
- this.next();
- }
- forward(pos, side) {
- if ((this.to - pos || this.endSide - side) < 0)
- this.gotoInner(pos, side, true);
- }
- next() {
- for (; ; ) {
- if (this.chunkIndex == this.layer.chunk.length) {
- this.from = this.to = 1e9;
- this.value = null;
- break;
- } else {
- let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
- let from = chunkPos + chunk.from[this.rangeIndex];
- this.from = from;
- this.to = chunkPos + chunk.to[this.rangeIndex];
- this.value = chunk.value[this.rangeIndex];
- this.setRangeIndex(this.rangeIndex + 1);
- if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
- break;
- }
- }
- }
- setRangeIndex(index) {
- if (index == this.layer.chunk[this.chunkIndex].value.length) {
- this.chunkIndex++;
- if (this.skip) {
- while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
- this.chunkIndex++;
- }
- this.rangeIndex = 0;
- } else {
- this.rangeIndex = index;
- }
- }
- nextChunk() {
- this.chunkIndex++;
- this.rangeIndex = 0;
- this.next();
- }
- compare(other) {
- return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide;
- }
- };
- var HeapCursor = class {
- constructor(heap) {
- this.heap = heap;
- }
- static from(sets, skip = null, minPoint = -1) {
- let heap = [];
- for (let i = 0; i < sets.length; i++) {
- for (let cur2 = sets[i]; !cur2.isEmpty; cur2 = cur2.nextLayer) {
- if (cur2.maxPoint >= minPoint)
- heap.push(new LayerCursor(cur2, skip, minPoint, i));
- }
- }
- return heap.length == 1 ? heap[0] : new HeapCursor(heap);
- }
- get startSide() {
- return this.value ? this.value.startSide : 0;
- }
- goto(pos, side = -1e9) {
- for (let cur2 of this.heap)
- cur2.goto(pos, side);
- for (let i = this.heap.length >> 1; i >= 0; i--)
- heapBubble(this.heap, i);
- this.next();
- return this;
- }
- forward(pos, side) {
- for (let cur2 of this.heap)
- cur2.forward(pos, side);
- for (let i = this.heap.length >> 1; i >= 0; i--)
- heapBubble(this.heap, i);
- if ((this.to - pos || this.value.endSide - side) < 0)
- this.next();
- }
- next() {
- if (this.heap.length == 0) {
- this.from = this.to = 1e9;
- this.value = null;
- this.rank = -1;
- } else {
- let top2 = this.heap[0];
- this.from = top2.from;
- this.to = top2.to;
- this.value = top2.value;
- this.rank = top2.rank;
- if (top2.value)
- top2.next();
- heapBubble(this.heap, 0);
- }
- }
- };
- function heapBubble(heap, index) {
- for (let cur2 = heap[index]; ; ) {
- let childIndex = (index << 1) + 1;
- if (childIndex >= heap.length)
- break;
- let child = heap[childIndex];
- if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
- child = heap[childIndex + 1];
- childIndex++;
- }
- if (cur2.compare(child) < 0)
- break;
- heap[childIndex] = cur2;
- heap[index] = child;
- index = childIndex;
- }
- }
- var SpanCursor = class {
- constructor(sets, skip, minPoint) {
- this.minPoint = minPoint;
- this.active = [];
- this.activeTo = [];
- this.activeRank = [];
- this.minActive = -1;
- this.point = null;
- this.pointFrom = 0;
- this.pointRank = 0;
- this.to = -1e9;
- this.endSide = 0;
- this.openStart = -1;
- this.cursor = HeapCursor.from(sets, skip, minPoint);
- }
- goto(pos, side = -1e9) {
- this.cursor.goto(pos, side);
- this.active.length = this.activeTo.length = this.activeRank.length = 0;
- this.minActive = -1;
- this.to = pos;
- this.endSide = side;
- this.openStart = -1;
- this.next();
- return this;
- }
- forward(pos, side) {
- while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
- this.removeActive(this.minActive);
- this.cursor.forward(pos, side);
- }
- removeActive(index) {
- remove(this.active, index);
- remove(this.activeTo, index);
- remove(this.activeRank, index);
- this.minActive = findMinIndex(this.active, this.activeTo);
- }
- addActive(trackOpen) {
- let i = 0, { value, to, rank } = this.cursor;
- while (i < this.activeRank.length && this.activeRank[i] <= rank)
- i++;
- insert(this.active, i, value);
- insert(this.activeTo, i, to);
- insert(this.activeRank, i, rank);
- if (trackOpen)
- insert(trackOpen, i, this.cursor.from);
- this.minActive = findMinIndex(this.active, this.activeTo);
- }
- // After calling this, if `this.point` != null, the next range is a
- // point. Otherwise, it's a regular range, covered by `this.active`.
- next() {
- let from = this.to, wasPoint = this.point;
- this.point = null;
- let trackOpen = this.openStart < 0 ? [] : null;
- for (; ; ) {
- let a = this.minActive;
- if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
- if (this.activeTo[a] > from) {
- this.to = this.activeTo[a];
- this.endSide = this.active[a].endSide;
- break;
- }
- this.removeActive(a);
- if (trackOpen)
- remove(trackOpen, a);
- } else if (!this.cursor.value) {
- this.to = this.endSide = 1e9;
- break;
- } else if (this.cursor.from > from) {
- this.to = this.cursor.from;
- this.endSide = this.cursor.startSide;
- break;
- } else {
- let nextVal = this.cursor.value;
- if (!nextVal.point) {
- this.addActive(trackOpen);
- this.cursor.next();
- } else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
- this.cursor.next();
- } else {
- this.point = nextVal;
- this.pointFrom = this.cursor.from;
- this.pointRank = this.cursor.rank;
- this.to = this.cursor.to;
- this.endSide = nextVal.endSide;
- this.cursor.next();
- this.forward(this.to, this.endSide);
- break;
- }
- }
- }
- if (trackOpen) {
- this.openStart = 0;
- for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
- this.openStart++;
- }
- }
- activeForPoint(to) {
- if (!this.active.length)
- return this.active;
- let active = [];
- for (let i = this.active.length - 1; i >= 0; i--) {
- if (this.activeRank[i] < this.pointRank)
- break;
- if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
- active.push(this.active[i]);
- }
- return active.reverse();
- }
- openEnd(to) {
- let open = 0;
- for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
- open++;
- return open;
- }
- };
- function compare(a, startA, b, startB, length, comparator) {
- a.goto(startA);
- b.goto(startB);
- let endB = startB + length;
- let pos = startB, dPos = startB - startA;
- for (; ; ) {
- let diff = a.to + dPos - b.to || a.endSide - b.endSide;
- let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
- if (a.point || b.point) {
- if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to))))
- comparator.comparePoint(pos, clipEnd, a.point, b.point);
- } else {
- if (clipEnd > pos && !sameValues(a.active, b.active))
- comparator.compareRange(pos, clipEnd, a.active, b.active);
- }
- if (end > endB)
- break;
- pos = end;
- if (diff <= 0)
- a.next();
- if (diff >= 0)
- b.next();
- }
- }
- function sameValues(a, b) {
- if (a.length != b.length)
- return false;
- for (let i = 0; i < a.length; i++)
- if (a[i] != b[i] && !a[i].eq(b[i]))
- return false;
- return true;
- }
- function remove(array, index) {
- for (let i = index, e = array.length - 1; i < e; i++)
- array[i] = array[i + 1];
- array.pop();
- }
- function insert(array, index, value) {
- for (let i = array.length - 1; i >= index; i--)
- array[i + 1] = array[i];
- array[index] = value;
- }
- function findMinIndex(value, array) {
- let found = -1, foundPos = 1e9;
- for (let i = 0; i < array.length; i++)
- if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
- found = i;
- foundPos = array[i];
- }
- return found;
- }
- function countColumn(string2, tabSize, to = string2.length) {
- let n = 0;
- for (let i = 0; i < to; ) {
- if (string2.charCodeAt(i) == 9) {
- n += tabSize - n % tabSize;
- i++;
- } else {
- n++;
- i = findClusterBreak(string2, i);
- }
- }
- return n;
- }
- function findColumn(string2, col, tabSize, strict) {
- for (let i = 0, n = 0; ; ) {
- if (n >= col)
- return i;
- if (i == string2.length)
- break;
- n += string2.charCodeAt(i) == 9 ? tabSize - n % tabSize : 1;
- i = findClusterBreak(string2, i);
- }
- return strict === true ? -1 : string2.length;
- }
-
- // node_modules/style-mod/src/style-mod.js
- var C = "\u037C";
- var COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
- var SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
- var top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
- var StyleModule = class {
- // :: (Object`;
- this.appendChild(boxDiv);
- this.editor = this.makeEditor(pySrc, shadowRoot);
- this.editor.focus();
- logger6.debug(`element ${this.id} successfully connected`);
- }
- get src() {
- return this.getAttribute("src");
- }
- set src(value) {
- this.setAttribute("src", value);
- }
- attributeChangedCallback(name2, oldVal, newVal) {
- if (name2 === "src" && newVal !== oldVal) {
- void this.loadReplSrc();
- }
- }
- /**
- * Fetch url from src attribute of py-repl tags and
- * preload the code from fetch response into the Corresponding py-repl tag,
- * but please note that they will not be pre-run unless you click the runbotton.
- */
- async loadReplSrc() {
- try {
- const response = await robustFetch(this.src);
- if (!response.ok) {
- return;
- }
- const cmcontentElement = $("div.cm-content", this.editor.dom);
- const { lastElementChild } = cmcontentElement;
- cmcontentElement.replaceChildren(lastElementChild);
- lastElementChild.textContent = await response.text();
- logger6.info(`loading code from ${this.src} to repl...success`);
- } catch (err) {
- const e = err;
- _createAlertBanner(e.message);
- }
- }
- /** Create and configure the codemirror editor
- */
- makeEditor(pySrc, parent) {
- const languageConf = new Compartment();
- const extensions = [
- indentUnit.of(" "),
- basicSetup,
- languageConf.of(python()),
- keymap.of([
- ...defaultKeymap,
- { key: "Ctrl-Enter", run: this.execute.bind(this), preventDefault: true },
- { key: "Alt-Enter", run: this.execute.bind(this), preventDefault: true },
- { key: "Shift-Enter", run: this.execute.bind(this), preventDefault: true }
- ])
- ];
- if (this.getAttribute("theme") === "dark") {
- extensions.push(oneDarkTheme);
- }
- return new EditorView({
- doc: pySrc,
- extensions,
- parent
- });
- }
- // ******** main entry point for py-repl DOM building **********
- //
- // The following functions are written in a top-down, depth-first
- // order (so that the order of code roughly matches the order of
- // execution)
- makeBoxDiv() {
- const boxDiv = document.createElement("div");
- boxDiv.className = "py-repl-box";
- const editorDiv = this.makeEditorDiv();
- this.outDiv = this.makeOutDiv();
- boxDiv.appendChild(editorDiv);
- boxDiv.appendChild(this.outDiv);
- return boxDiv;
- }
- makeEditorDiv() {
- const editorDiv = document.createElement("div");
- editorDiv.className = "py-repl-editor";
- editorDiv.setAttribute("aria-label", "Python Script Area");
- const runButton = this.makeRunButton();
- const editorShadowContainer = document.createElement("div");
- editorShadowContainer.addEventListener("keydown", (event) => {
- event.stopPropagation();
- });
- editorDiv.append(editorShadowContainer, runButton);
- return editorDiv;
- }
- makeRunButton() {
- const runButton = document.createElement("button");
- runButton.className = "absolute py-repl-run-button";
- // runButton.innerHTML = RUNBUTTON;
- runButton.setAttribute("aria-label", "Python Script Run Button");
- runButton.addEventListener("click", this.execute.bind(this));
- return runButton;
- }
- makeOutDiv() {
- const outDiv = document.createElement("div");
- outDiv.className = "py-repl-output";
- outDiv.id = this.id + "-repl-output";
- return outDiv;
- }
- // ********************* execution logic *********************
- /** Execute the python code written in the editor, and automatically
- * display() the last evaluated expression
- */
- async execute() {
- // const pySrc = this.getPySrc();
- const pySrc = this.convertPySrc(this.getPySrc());
- const outEl = this.outDiv;
- await app.plugins.beforePyReplExec({ interpreter: interpreter2, src: pySrc, outEl, pyReplTag: this });
- const { result } = await pyExec(interpreter2, pySrc, outEl);
- await app.plugins.afterPyReplExec({
- interpreter: interpreter2,
- src: pySrc,
- outEl,
- pyReplTag: this,
- result
- });
- await interpreter2._remote.destroyIfProxy(result);
- this.autogenerateMaybe();
- }
- // *************** [customed] utility functions *****************
- // 사용자가 입력한 코드에 try-except 구문과 mission_start 함수를 추가하여 반환
- convertPySrc(pySrc){
- let convertedCode = '';
- const lines = pySrc.split('\n');
- // const indent = ' '
- const indent = ''
- for(let i = 0; i < lines.length; i++){
- convertedCode += indent + lines[i] + '\n';
- }
-
- // const newCode = 'mission_start()\ntry:\n'+ convertedCode + ' pass\nexcept Exception as e:\n raise\n'+lines[lines.length-1];
- const newCode = 'mission_start()\n'+convertedCode;
- return newCode;
- }
- getPySrc() {
- return this.editor.state.doc.toString();
- }
- // XXX the autogenerate logic is very messy. We should redo it, and it
- // should be the default.
- autogenerateMaybe() {
- if (this.hasAttribute("auto-generate")) {
- const allPyRepls = $$(`py-repl[root='${this.getAttribute("root")}'][exec-id]`, document);
- const lastRepl = allPyRepls[allPyRepls.length - 1];
- const lastExecId = lastRepl.getAttribute("exec-id");
- const nextExecId = parseInt(lastExecId) + 1;
- const newPyRepl = document.createElement("py-repl");
- for (const attribute of ["root", "output-mode", "output", "stderr"]) {
- const attr = this.getAttribute(attribute);
- if (attr) {
- newPyRepl.setAttribute(attribute, attr);
- }
- }
- newPyRepl.id = this.getAttribute("root") + "-" + nextExecId.toString();
- if (this.hasAttribute("auto-generate")) {
- newPyRepl.setAttribute("auto-generate", "");
- this.removeAttribute("auto-generate");
- }
- newPyRepl.setAttribute("exec-id", nextExecId.toString());
- if (this.parentElement) {
- this.parentElement.appendChild(newPyRepl);
- }
- }
- }
- }
- PyRepl.observedAttributes = ["src"];
- return PyRepl;
- }
-
- // src/components/elements.ts
- function createCustomElements(interpreter2, app) {
- const PyRepl = make_PyRepl(interpreter2, app);
- customElements.define("py-repl", PyRepl);
- }
-
- // src/stdio.ts
- var DEFAULT_STDIO = {
- stdout_writeline: console.log,
- stderr_writeline: console.log
- };
- var TargetedStdio = class {
- constructor(source_element, source_attribute, capture_stdout = true, capture_stderr = true) {
- this.source_element = source_element;
- this.source_attribute = source_attribute;
- this.capture_stdout = capture_stdout;
- this.capture_stderr = capture_stderr;
- }
- /** Writes the given msg to an element with a given ID. The ID is the value an attribute
- * of the source_element specified by source_attribute.
- * Both the element to be targeted and the ID of the element to write to
- * are determined at write-time, not when the TargetdStdio object is
- * created. This way, if either the 'output' attribute of the HTML tag
- * or the ID of the target element changes during execution of the Python
- * code, the output is still routed (or not) as expected
- *
- * @param msg The output to be written
- */
- writeline_by_attribute(msg) {
- const target_id = this.source_element.getAttribute(this.source_attribute);
- const target = $("#" + target_id, document);
- if (target === null) {
- createSingularWarning(
- `${this.source_attribute} = "${target_id}" does not match the id of any element on the page.`
- );
- } else {
- msg = escape(msg).replace("\n", "
");
- if (!msg.endsWith("
") && !msg.endsWith("
")) {
- msg = msg + "
";
- }
- target.innerHTML += msg;
- }
- }
- stdout_writeline(msg) {
- if (this.capture_stdout) {
- this.writeline_by_attribute(msg);
- }
- }
- stderr_writeline(msg) {
- if (this.capture_stderr) {
- this.writeline_by_attribute(msg);
- }
- }
- };
- var StdioMultiplexer = class {
- constructor() {
- this._listeners = [];
- }
- addListener(obj) {
- this._listeners.push(obj);
- }
- removeListener(obj) {
- const index = this._listeners.indexOf(obj);
- if (index > -1) {
- this._listeners.splice(index, 1);
- }
- }
- stdout_writeline(msg) {
- for (const obj of this._listeners)
- obj.stdout_writeline(msg);
- }
- stderr_writeline(msg) {
- for (const obj of this._listeners)
- obj.stderr_writeline(msg);
- }
- };
-
- // src/plugins/pyterminal.ts
- var knownPyTerminalTags = /* @__PURE__ */ new WeakSet();
- var logger7 = getLogger("py-terminal");
- var PyTerminalPlugin = class extends Plugin {
- constructor(app) {
- super();
- this.app = app;
- }
- configure(config2) {
- validateConfigParameterFromArray({
- config: config2,
- name: "terminal",
- possibleValues: [true, false, "auto"],
- defaultValue: "auto"
- });
- validateConfigParameterFromArray({
- config: config2,
- name: "docked",
- possibleValues: [true, false, "docked"],
- defaultValue: "docked"
- });
- validateConfigParameterFromArray({
- config: config2,
- name: "xterm",
- possibleValues: [true, false, "xterm"],
- defaultValue: false
- });
- }
- beforeLaunch(config2) {
- const { terminal: t2, docked: d, xterm: x } = config2;
- const auto = t2 === true || t2 === "auto";
- const docked = d === true || d === "docked";
- const xterm = x === true || x === "xterm";
- if (auto && $("py-terminal", document) === null) {
- logger7.info("No found, adding one");
- const termElem = document.createElement("py-terminal");
- if (auto)
- termElem.setAttribute("auto", "");
- if (docked)
- termElem.setAttribute("docked", "");
- if (xterm)
- termElem.setAttribute("xterm", "");
- document.body.appendChild(termElem);
- }
- }
- afterSetup(_interpreter) {
- const PyTerminal = _interpreter.config.xterm ? make_PyTerminal_xterm(this.app) : make_PyTerminal_pre(this.app);
- customElements.define("py-terminal", PyTerminal);
- }
- };
- var PyTerminalBaseClass = class extends HTMLElement {
- isAuto() {
- return this.hasAttribute("auto");
- }
- isDocked() {
- return this.hasAttribute("docked");
- }
- setupPosition(app) {
- if (this.isAuto()) {
- this.classList.add("py-terminal-hidden");
- this.autoShowOnNextLine = true;
- } else {
- this.autoShowOnNextLine = false;
- }
- if (this.isDocked()) {
- this.classList.add("py-terminal-docked");
- }
- logger7.info("Registering stdio listener");
- app.registerStdioListener(this);
- }
- };
- function make_PyTerminal_pre(app) {
- class PyTerminalPre extends PyTerminalBaseClass {
- connectedCallback() {
- this.outElem = document.createElement("pre");
- this.outElem.classList.add("py-terminal");
- this.appendChild(this.outElem);
- this.setupPosition(app);
- }
- // implementation of the Stdio interface
- stdout_writeline(msg) {
- this.outElem.innerText += msg + "\n";
- if (this.isDocked()) {
- this.scrollTop = this.scrollHeight;
- }
- if (this.autoShowOnNextLine) {
- this.classList.remove("py-terminal-hidden");
- this.autoShowOnNextLine = false;
- }
- }
- stderr_writeline(msg) {
- this.stdout_writeline(msg);
- }
- // end of the Stdio interface
- }
- return PyTerminalPre;
- }
- function make_PyTerminal_xterm(app) {
- class PyTerminalXterm extends PyTerminalBaseClass {
- constructor() {
- super();
- this._xterm_cdn_base_url = "https://cdn.jsdelivr.net/npm/xterm@5.1.0";
- this.cachedStdOut = [];
- this.cachedStdErr = [];
- this._moduleResolved = false;
- this.style.width = "100%";
- this.style.height = "100%";
- }
- async connectedCallback() {
- if (knownPyTerminalTags.has(this))
- return;
- knownPyTerminalTags.add(this);
- this.outElem = document.createElement("div");
- this.appendChild(this.outElem);
- this.setupPosition(app);
- this.xtermReady = this._setupXterm();
- await this.xtermReady;
- }
- /**
- * Fetch the xtermjs library from CDN an initialize it.
- * @private
- * @returns the associated xterm.js Terminal
- */
- async _setupXterm() {
- if (this.xterm == void 0) {
- if (globalThis.Terminal == void 0) {
- await import(this._xterm_cdn_base_url + "/lib/xterm.js");
- const cssTag = document.createElement("link");
- cssTag.type = "text/css";
- cssTag.rel = "stylesheet";
- cssTag.href = this._xterm_cdn_base_url + "/css/xterm.css";
- document.head.appendChild(cssTag);
- }
- this.xterm = new Terminal({ screenReaderMode: true, cols: 80 });
- if (!this.autoShowOnNextLine)
- this.xterm.open(this);
- this._moduleResolved = true;
- this.cachedStdOut.forEach((value) => this.stdout_writeline(value));
- this.cachedStdErr.forEach((value) => this.stderr_writeline(value));
- } else {
- this._moduleResolved = true;
- }
- return this.xterm;
- }
- // implementation of the Stdio interface
- stdout_writeline(msg) {
- if (this._moduleResolved) {
- this.xterm.writeln(msg);
- if (this.isDocked()) {
- this.scrollTop = this.scrollHeight;
- }
- if (this.autoShowOnNextLine) {
- this.classList.remove("py-terminal-hidden");
- this.autoShowOnNextLine = false;
- this.xterm.open(this);
- }
- } else {
- this.cachedStdOut.push(msg);
- }
- }
- stderr_writeline(msg) {
- this.stdout_writeline(msg);
- }
- // end of the Stdio interface
- }
- return PyTerminalXterm;
- }
-
- // src/plugins/splashscreen.ts
- var logger8 = getLogger("py-splashscreen");
- var AUTOCLOSE_LOADER_DEPRECATED = `
-The setting autoclose_loader is deprecated. Please use the
-following instead:
-
-<py-config>
-[splashscreen]
-autoclose = false
-</py-config>
-
`;
- var SplashscreenPlugin = class extends Plugin {
- configure(config2) {
- this.autoclose = true;
- this.enabled = true;
- if ("autoclose_loader" in config2) {
- this.autoclose = config2.autoclose_loader;
- showWarning(AUTOCLOSE_LOADER_DEPRECATED, "html");
- }
- if (config2.splashscreen) {
- this.autoclose = config2.splashscreen.autoclose ?? true;
- this.enabled = config2.splashscreen.enabled ?? true;
- }
- }
- beforeLaunch(_config) {
- if (!this.enabled) {
- return;
- }
- logger8.info("add py-splashscreen");
- customElements.define("py-splashscreen", PySplashscreen);
- this.elem = document.createElement("py-splashscreen");
- document.body.append(this.elem);
- document.addEventListener("py-status-message", (e) => {
- const msg = e.detail;
- this.elem.log(msg);
- });
- }
- afterStartup(_interpreter) {
- if (this.autoclose && this.enabled) {
- this.elem.close();
- }
- }
- onUserError(_error) {
- if (this.elem !== void 0 && this.enabled) {
- this.elem.close();
- }
- }
- };
- var PySplashscreen = class extends HTMLElement {
- constructor() {
- super();
- }
- connectedCallback() {
- this.innerHTML = ``;
- this.mount_name = this.id.split("-").join("_");
- this.operation = $("#pyscript-operation", document);
- this.details = $("#pyscript-operation-details", document);
- }
- log(msg) {
- const newLog = document.createElement("p");
- newLog.innerText = msg;
- this.details.appendChild(newLog);
- }
- close() {
- logger8.info("Closing");
- this.remove();
- }
- };
-
- // src/plugins/importmap.ts
- var logger9 = getLogger("plugins/importmap");
- var ImportmapPlugin = class extends Plugin {
- async afterSetup(interpreter2) {
- for (const node of $$("script[type='importmap']", document)) {
- const importmap = (() => {
- try {
- return JSON.parse(node.textContent);
- } catch (e) {
- const error = e;
- showWarning("Failed to parse import map: " + error.message);
- }
- })();
- if (importmap?.imports == null)
- continue;
- for (const [name2, url] of Object.entries(importmap.imports)) {
- if (typeof name2 != "string" || typeof url != "string")
- continue;
- let exports;
- try {
- exports = { ...await import(url) };
- } catch {
- logger9.warn(`failed to fetch '${url}' for '${name2}'`);
- continue;
- }
- logger9.info("Registering JS module", name2);
- await interpreter2._remote.registerJsModule(name2, exports);
- }
- }
- }
- };
-
- // src/plugins/stdiodirector.ts
- var StdioDirector = class extends Plugin {
- constructor(stdio) {
- super();
- this._stdioMultiplexer = stdio;
- }
- /** Prior to a tag being evaluated, if that tag itself has
- * an 'output' attribute, a new TargetedStdio object is created and added
- * to the stdioMultiplexer to route sys.stdout and sys.stdout to the DOM object
- * with that ID for the duration of the evaluation.
- *
- */
- beforePyScriptExec(options) {
- if (options.pyScriptTag.hasAttribute("output")) {
- const targeted_io = new TargetedStdio(options.pyScriptTag, "output", true, true);
- options.pyScriptTag.stdout_manager = targeted_io;
- this._stdioMultiplexer.addListener(targeted_io);
- }
- if (options.pyScriptTag.hasAttribute("stderr")) {
- const targeted_io = new TargetedStdio(options.pyScriptTag, "stderr", false, true);
- options.pyScriptTag.stderr_manager = targeted_io;
- this._stdioMultiplexer.addListener(targeted_io);
- }
- }
- /** After a tag is evaluated, if that tag has a 'stdout_manager'
- * (presumably TargetedStdio, or some other future IO handler), it is removed.
- */
- afterPyScriptExec(options) {
- if (options.pyScriptTag.stdout_manager != null) {
- this._stdioMultiplexer.removeListener(options.pyScriptTag.stdout_manager);
- options.pyScriptTag.stdout_manager = null;
- }
- if (options.pyScriptTag.stderr_manager != null) {
- this._stdioMultiplexer.removeListener(options.pyScriptTag.stderr_manager);
- options.pyScriptTag.stderr_manager = null;
- }
- }
- beforePyReplExec(options) {
- if (options.pyReplTag.getAttribute("output-mode") != "append") {
- options.outEl.innerHTML = "";
- }
- let output_targeted_io;
- if (options.pyReplTag.hasAttribute("output")) {
- output_targeted_io = new TargetedStdio(options.pyReplTag, "output", true, true);
- } else {
- output_targeted_io = new TargetedStdio(options.pyReplTag.outDiv, "id", true, true);
- }
- options.pyReplTag.stdout_manager = output_targeted_io;
- this._stdioMultiplexer.addListener(output_targeted_io);
- if (options.pyReplTag.hasAttribute("stderr")) {
- const stderr_targeted_io = new TargetedStdio(options.pyReplTag, "stderr", false, true);
- options.pyReplTag.stderr_manager = stderr_targeted_io;
- this._stdioMultiplexer.addListener(stderr_targeted_io);
- }
- }
- async afterPyReplExec(options) {
- if (options.result !== void 0) {
- const outputId = options.pyReplTag.getAttribute("output");
- if (outputId) {
- if ($("#" + outputId, document)) {
- await pyDisplay(options.interpreter, options.result, { target: outputId });
- } else {
- createSingularWarning(`output = "${outputId}" does not match the id of any element on the page.`);
- }
- } else {
- await pyDisplay(options.interpreter, options.result, { target: options.outEl.id });
- }
- }
- if (options.pyReplTag.stdout_manager != null) {
- this._stdioMultiplexer.removeListener(options.pyReplTag.stdout_manager);
- options.pyReplTag.stdout_manager = null;
- }
- if (options.pyReplTag.stderr_manager != null) {
- this._stdioMultiplexer.removeListener(options.pyReplTag.stderr_manager);
- options.pyReplTag.stderr_manager = null;
- }
- }
- };
-
- // bundlePyscriptPythonPlugin:dummy
- var dummy_default = { dirs: ["pyscript"], files: [["pyscript/_html.py", `from textwrap import dedent
-
-import js
-from _pyscript_js import deepQuerySelector
-
-from . import _internal
-from ._mime import format_mime as _format_mime
-
-
-class HTML:
- """
- Wrap a string so that display() can render it as plain HTML
- """
-
- def __init__(self, html):
- self._html = html
-
- def _repr_html_(self):
- return self._html
-
-
-def write(element_id, value, append=False, exec_id=0):
- """Writes value to the element with id "element_id"""
- Element(element_id).write(value=value, append=append)
- js.console.warn(
- dedent(
- """PyScript Deprecation Warning: PyScript.write is
- marked as deprecated and will be removed sometime soon. Please, use
- Element().write instead."""
- )
- )
-
-
-def display(*values, target=None, append=True):
- if target is None:
- target = _internal.DISPLAY_TARGET
- if target is None:
- raise Exception(
- "Implicit target not allowed here. Please use display(..., target=...)"
- )
- for v in values:
- Element(target).write(v, append=append)
-
-
-class Element:
- def __init__(self, element_id, element=None):
- self._id = element_id
- self._element = element
-
- @property
- def id(self):
- return self._id
-
- @property
- def element(self):
- """Return the dom element"""
- if not self._element:
- self._element = deepQuerySelector(f"#{self._id}")
- return self._element
-
- @property
- def value(self):
- return self.element.value
-
- @property
- def innerHtml(self):
- return self.element.innerHTML
-
- def write(self, value, append=False):
- html, mime_type = _format_mime(value)
- if html == "\\n":
- return
-
- if append:
- child = js.document.createElement("div")
- self.element.appendChild(child)
-
- if append and self.element.children:
- out_element = self.element.children[-1]
- else:
- out_element = self.element
-
- if mime_type in ("application/javascript", "text/html"):
- script_element = js.document.createRange().createContextualFragment(html)
- out_element.appendChild(script_element)
- else:
- out_element.innerHTML = html
-
- def clear(self):
- if hasattr(self.element, "value"):
- self.element.value = ""
- else:
- self.write("", append=False)
-
- def select(self, query, from_content=False):
- el = self.element
-
- if from_content:
- el = el.content
-
- _el = el.querySelector(query)
- if _el:
- return Element(_el.id, _el)
- else:
- js.console.warn(f"WARNING: can't find element matching query {query}")
-
- def clone(self, new_id=None, to=None):
- if new_id is None:
- new_id = self.element.id
-
- clone = self.element.cloneNode(True)
- clone.id = new_id
-
- if to:
- to.element.appendChild(clone)
- # Inject it into the DOM
- to.element.after(clone)
- else:
- # Inject it into the DOM
- self.element.after(clone)
-
- return Element(clone.id, clone)
-
- def remove_class(self, classname):
- classList = self.element.classList
- if isinstance(classname, list):
- classList.remove(*classname)
- else:
- classList.remove(classname)
-
- def add_class(self, classname):
- classList = self.element.classList
- if isinstance(classname, list):
- classList.add(*classname)
- else:
- self.element.classList.add(classname)
-
-
-def add_classes(element, class_list):
- classList = element.classList
- classList.add(*class_list.split(" "))
-
-
-def create(what, id_=None, classes=""):
- element = js.document.createElement(what)
- if id_:
- element.id = id_
- add_classes(element, classes)
- return Element(id_, element)
-`], ["pyscript/__init__.py", `from _pyscript_js import showWarning
-
-from ._event_handling import when
-from ._event_loop import LOOP as loop
-from ._event_loop import run_until_complete
-from ._html import (
- HTML,
- Element,
- add_classes,
- create,
- display,
- write,
-)
-from ._plugin import Plugin
-
-# these are set by _set_version_info
-__version__ = None
-version_info = None
-
-
-def __getattr__(attr):
- if attr == "js":
- global js
- import js
- from _pyscript_js import showWarning
-
- # Deprecated after 2023.03.1
- showWarning(
- "pyscript.js
is deprecated, please use import js
instead.",
- "html",
- )
- return js
- raise AttributeError(f"module 'pyscript' has no attribute '{attr}'")
-
-
-__all__ = [
- "HTML",
- "write",
- "display",
- "Element",
- "add_classes",
- "create",
- "run_until_complete",
- "loop",
- "Plugin",
- "__version__",
- "version_info",
- "showWarning",
- "when",
-]
-`], ["pyscript/_plugin.py", 'from _pyscript_js import define_custom_element\nfrom js import console\nfrom pyodide.ffi import create_proxy\n\n\nclass Plugin:\n def __init__(self, name=None):\n if not name:\n name = self.__class__.__name__\n\n self.name = name\n self._custom_elements = []\n self.app = None\n\n def init(self, app):\n self.app = app\n\n def configure(self, config):\n pass\n\n def afterSetup(self, interpreter):\n pass\n\n def afterStartup(self, interpreter):\n pass\n\n def beforePyScriptExec(self, interpreter, src, pyScriptTag):\n pass\n\n def afterPyScriptExec(self, interpreter, src, pyScriptTag, result):\n pass\n\n def beforePyReplExec(self, interpreter, src, outEl, pyReplTag):\n pass\n\n def afterPyReplExec(self, interpreter, src, outEl, pyReplTag, result):\n pass\n\n def onUserError(self, error):\n pass\n\n def register_custom_element(self, tag):\n """\n Decorator to register a new custom element as part of a Plugin and associate\n tag to it. Internally, it delegates the registration to the PyScript internal\n [JS] plugin manager, who actually creates the JS custom element that can be\n attached to the page and instantiate an instance of the class passing the custom\n element to the plugin constructor.\n\n Exammple:\n >> plugin = Plugin("PyTutorial")\n >> @plugin.register_custom_element("py-tutor")\n >> class PyTutor:\n >> def __init__(self, element):\n >> self.element = element\n """\n # TODO: Ideally would be better to use the logger.\n console.info(f"Defining new custom element {tag}")\n\n def wrapper(class_):\n # TODO: this is very pyodide specific but will have to do\n # until we have JS interface that works across interpreters\n define_custom_element(tag, create_proxy(class_)) # noqa: F821\n\n self._custom_elements.append(tag)\n return create_proxy(wrapper)\n'], ["pyscript/_mime.py", `import base64
-import html
-import io
-import re
-
-from js import console
-
-MIME_METHODS = {
- "__repr__": "text/plain",
- "_repr_html_": "text/html",
- "_repr_markdown_": "text/markdown",
- "_repr_svg_": "image/svg+xml",
- "_repr_png_": "image/png",
- "_repr_pdf_": "application/pdf",
- "_repr_jpeg_": "image/jpeg",
- "_repr_latex": "text/latex",
- "_repr_json_": "application/json",
- "_repr_javascript_": "application/javascript",
- "savefig": "image/png",
-}
-
-
-def render_image(mime, value, meta):
- # If the image value is using bytes we should convert it to base64
- # otherwise it will return raw bytes and the browser will not be able to
- # render it.
- if isinstance(value, bytes):
- value = base64.b64encode(value).decode("utf-8")
-
- # This is the pattern of base64 strings
- base64_pattern = re.compile(
- r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"
- )
- # If value doesn't match the base64 pattern we should encode it to base64
- if len(value) > 0 and not base64_pattern.match(value):
- value = base64.b64encode(value.encode("utf-8")).decode("utf-8")
-
- data = f"data:{mime};charset=utf-8;base64,{value}"
- attrs = " ".join(['{k}="{v}"' for k, v in meta.items()])
- return f'
'
-
-
-def identity(value, meta):
- return value
-
-
-MIME_RENDERERS = {
- "text/plain": html.escape,
- "text/html": identity,
- "image/png": lambda value, meta: render_image("image/png", value, meta),
- "image/jpeg": lambda value, meta: render_image("image/jpeg", value, meta),
- "image/svg+xml": identity,
- "application/json": identity,
- "application/javascript": lambda value, meta: f"\",\n}\n\n\n# these are set by _set_version_info\n__version__ = None\nversion_info = None\n\n\ndef _set_version_info(version_from_runtime: str):\n \"\"\"Sets the __version__ and version_info properties from provided JSON data\n Args:\n version_from_runtime (str): A \"dotted\" representation of the version:\n YYYY.MM.m(m).releaselevel\n Year, Month, and Minor should be integers; releaselevel can be any string\n \"\"\"\n global __version__\n global version_info\n\n __version__ = version_from_runtime\n\n version_parts = version_from_runtime.split(\".\")\n year = int(version_parts[0])\n month = int(version_parts[1])\n minor = int(version_parts[2])\n if len(version_parts) > 3:\n releaselevel = version_parts[3]\n else:\n releaselevel = \"\"\n\n VersionInfo = namedtuple(\"version_info\", (\"year\", \"month\", \"minor\", \"releaselevel\"))\n version_info = VersionInfo(year, month, minor, releaselevel)\n\n # we ALSO set PyScript.__version__ and version_info for backwards\n # compatibility. Should be killed eventually.\n PyScript.__version__ = __version__\n PyScript.version_info = version_info\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n js.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\n@staticmethod\ndef run_until_complete(f):\n _ = loop.run_until_complete(f)\n\n\n@staticmethod\ndef write(element_id, value, append=False, exec_id=0):\n \"\"\"Writes value to the element with id \"element_id\"\"\"\n Element(element_id).write(value=value, append=append)\n js.console.warn(\n dedent(\n \"\"\"PyScript Deprecation Warning: PyScript.write is\n marked as deprecated and will be removed sometime soon. Please, use\n Element().write instead.\"\"\"\n )\n )\n\n\ndef set_current_display_target(target_id):\n get_current_display_target._id = target_id\n\n\ndef get_current_display_target():\n return get_current_display_target._id\n\n\nget_current_display_target._id = None\n\n\ndef display(*values, target=None, append=True):\n default_target = get_current_display_target()\n\n if default_target is None and target is None:\n raise Exception(\n \"Implicit target not allowed here. Please use display(..., target=...)\"\n )\n\n if target is not None:\n for v in values:\n Element(target).write(v, append=append)\n else:\n for v in values:\n Element(default_target).write(v, append=append)\n\n\nclass Element:\n def __init__(self, element_id, element=None):\n self._id = element_id\n self._element = element\n\n @property\n def id(self):\n return self._id\n\n @property\n def element(self):\n \"\"\"Return the dom element\"\"\"\n if not self._element:\n self._element = js.document.querySelector(f\"#{self._id}\")\n return self._element\n\n @property\n def value(self):\n return self.element.value\n\n @property\n def innerHtml(self):\n return self.element.innerHTML\n\n def write(self, value, append=False):\n html, mime_type = format_mime(value)\n if html == \"\\n\":\n return\n\n if append:\n child = js.document.createElement(\"div\")\n self.element.appendChild(child)\n\n if self.element.children:\n out_element = self.element.children[-1]\n else:\n out_element = self.element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = js.document.createRange().createContextualFragment(html)\n out_element.appendChild(script_element)\n else:\n out_element.innerHTML = html\n\n def clear(self):\n if hasattr(self.element, \"value\"):\n self.element.value = \"\"\n else:\n self.write(\"\", append=False)\n\n def select(self, query, from_content=False):\n el = self.element\n\n if from_content:\n el = el.content\n\n _el = el.querySelector(query)\n if _el:\n return Element(_el.id, _el)\n else:\n js.console.warn(f\"WARNING: can't find element matching query {query}\")\n\n def clone(self, new_id=None, to=None):\n if new_id is None:\n new_id = self.element.id\n\n clone = self.element.cloneNode(True)\n clone.id = new_id\n\n if to:\n to.element.appendChild(clone)\n # Inject it into the DOM\n to.element.after(clone)\n else:\n # Inject it into the DOM\n self.element.after(clone)\n\n return Element(clone.id, clone)\n\n def remove_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.remove_class(cl)\n else:\n self.element.classList.remove(classname)\n\n def add_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.element.classList.add(cl)\n else:\n self.element.classList.add(classname)\n\n\ndef add_classes(element, class_list):\n for klass in class_list.split(\" \"):\n element.classList.add(klass)\n\n\ndef create(what, id_=None, classes=\"\"):\n element = js.document.createElement(what)\n if id_:\n element.id = id_\n add_classes(element, classes)\n return Element(id_, element)\n\n\nclass PyWidgetTheme:\n def __init__(self, main_style_classes):\n self.main_style_classes = main_style_classes\n\n def theme_it(self, widget):\n for klass in self.main_style_classes.split(\" \"):\n widget.classList.add(klass)\n\n\nclass PyItemTemplate(Element):\n label_fields = None\n\n def __init__(self, data, labels=None, state_key=None, parent=None):\n self.data = data\n\n self.register_parent(parent)\n\n if not labels:\n labels = list(self.data.keys())\n self.labels = labels\n\n self.state_key = state_key\n\n super().__init__(self._id)\n\n def register_parent(self, parent):\n self._parent = parent\n if parent:\n self._id = f\"{self._parent._id}-c-{len(self._parent._children)}\"\n self.data[\"id\"] = self._id\n else:\n self._id = None\n\n def create(self):\n new_child = create(\"div\", self._id, \"py-li-element\")\n new_child._element.innerHTML = dedent(\n f\"\"\"\n \n \"\"\"\n )\n return new_child\n\n def on_click(self, evt):\n pass\n\n def pre_append(self):\n pass\n\n def post_append(self):\n self.element.click = self.on_click\n self.element.onclick = self.on_click\n\n self._post_append()\n\n def _post_append(self):\n pass\n\n def strike(self, value, extra=None):\n if value:\n self.add_class(\"line-through\")\n else:\n self.remove_class(\"line-through\")\n\n def render_content(self):\n return \" - \".join([self.data[f] for f in self.labels])\n\n\nclass PyListTemplate:\n theme = PyWidgetTheme(\"py-li-element\")\n item_class = PyItemTemplate\n\n def __init__(self, parent):\n self.parent = parent\n self._children = []\n self._id = self.parent.id\n\n @property\n def children(self):\n return self._children\n\n @property\n def data(self):\n return [c.data for c in self._children]\n\n def render_children(self):\n binds = {}\n for i, c in enumerate(self._children):\n txt = c.element.innerHTML\n rnd = str(time.time()).replace(\".\", \"\")[-5:]\n new_id = f\"{c.element.id}-{i}-{rnd}\"\n binds[new_id] = c.element.id\n txt = txt.replace(\">\", f\" id='{new_id}'>\")\n print(txt)\n\n def foo(evt):\n evtEl = evt.srcElement\n srcEl = Element(binds[evtEl.id])\n srcEl.element.onclick()\n evtEl.classList = srcEl.element.classList\n\n for new_id in binds:\n Element(new_id).element.onclick = foo\n\n def connect(self):\n self.md = main_div = js.document.createElement(\"div\")\n main_div.id = self._id + \"-list-tasks-container\"\n\n if self.theme:\n self.theme.theme_it(main_div)\n\n self.parent.appendChild(main_div)\n\n def add(self, *args, **kws):\n if not isinstance(args[0], self.item_class):\n child = self.item_class(*args, **kws)\n else:\n child = args[0]\n child.register_parent(self)\n return self._add(child)\n\n def _add(self, child_elem):\n self.pre_child_append(child_elem)\n child_elem.pre_append()\n self._children.append(child_elem)\n self.md.appendChild(child_elem.create().element)\n child_elem.post_append()\n self.child_appended(child_elem)\n return child_elem\n\n def pre_child_append(self, child):\n pass\n\n def child_appended(self, child):\n \"\"\"Overwrite me to define logic\"\"\"\n pass\n\n\nclass TopLevelAsyncFinder(ast.NodeVisitor):\n def is_source_top_level_await(self, source):\n self.async_found = False\n node = ast.parse(source)\n self.generic_visit(node)\n return self.async_found\n\n def visit_Await(self, node):\n self.async_found = True\n\n def visit_AsyncFor(self, node):\n self.async_found = True\n\n def visit_AsyncWith(self, node):\n self.async_found = True\n\n def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):\n pass # Do not visit children of async function defs\n\n\ndef uses_top_level_await(source: str) -> bool:\n return TopLevelAsyncFinder().is_source_top_level_await(source)\n\n\nclass Plugin:\n def __init__(self, name=None):\n if not name:\n name = self.__class__.__name__\n\n self.name = name\n\n def init(self, app):\n self.app = app\n self.app.plugins.addPythonPlugin(create_proxy(self))\n\n def register_custom_element(self, tag):\n # TODO: Ideally would be better to use the logger.\n js.console.info(f\"Defining new custom element {tag}\")\n\n def wrapper(class_):\n # TODO: this is very pyodide specific but will have to do\n # until we have JS interface that works across interpreters\n define_custom_element(tag, create_proxy(class_)) # noqa: F821\n\n return create_proxy(wrapper)\n\n\nclass DeprecatedGlobal:\n \"\"\"\n Proxy for globals which are deprecated.\n\n The intendend usage is as follows:\n\n # in the global namespace\n Element = pyscript.DeprecatedGlobal('Element', pyscript.Element, \"...\")\n console = pyscript.DeprecatedGlobal('console', js.console, \"...\")\n ...\n\n The proxy forwards __getattr__ and __call__ to the underlying object, and\n emit a warning on the first usage.\n\n This way users see a warning only if they actually access the top-level\n name.\n \"\"\"\n\n def __init__(self, name, obj, message):\n self.__name = name\n self.__obj = obj\n self.__message = message\n self.__warning_already_shown = False\n\n def __repr__(self):\n return f\"\"\n\n def _show_warning(self, message):\n \"\"\"\n NOTE: this is overridden by unit tests\n \"\"\"\n # this showWarning is implemented in js and injected into this\n # namespace by main.ts\n showWarning(message, \"html\") # noqa: F821\n\n def _show_warning_maybe(self):\n if self.__warning_already_shown:\n return\n self._show_warning(self.__message)\n self.__warning_already_shown = True\n\n def __getattr__(self, attr):\n self._show_warning_maybe()\n return getattr(self.__obj, attr)\n\n def __call__(self, *args, **kwargs):\n self._show_warning_maybe()\n return self.__obj(*args, **kwargs)\n\n def __iter__(self):\n self._show_warning_maybe()\n return iter(self.__obj)\n\n def __getitem__(self, key):\n self._show_warning_maybe()\n return self.__obj[key]\n\n def __setitem__(self, key, value):\n self._show_warning_maybe()\n self.__obj[key] = value\n\n\nclass PyScript:\n \"\"\"\n This class is deprecated since 2022.12.1.\n\n All its old functionalities are available as module-level functions. This\n class should be killed eventually.\n \"\"\"\n\n loop = loop\n\n @staticmethod\n def run_until_complete(f):\n run_until_complete(f)\n\n @staticmethod\n def write(element_id, value, append=False, exec_id=0):\n write(element_id, value, append, exec_id)\n\n\ndef _install_deprecated_globals_2022_12_1(ns):\n \"\"\"\n Install into the given namespace all the globals which have been\n deprecated since the 2022.12.1 release. Eventually they should be killed.\n \"\"\"\n\n def deprecate(name, obj, instead):\n message = f\"Direct usage of {name}
is deprecated. \" + instead\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # function/classes defined in pyscript.py ===> pyscript.XXX\n pyscript_names = [\n \"PyItemTemplate\",\n \"PyListTemplate\",\n \"PyWidgetTheme\",\n \"add_classes\",\n \"create\",\n \"loop\",\n ]\n for name in pyscript_names:\n deprecate(\n name, globals()[name], f\"Please use pyscript.{name}
instead.\"\n )\n\n # stdlib modules ===> import XXX\n stdlib_names = [\n \"asyncio\",\n \"base64\",\n \"io\",\n \"sys\",\n \"time\",\n \"datetime\",\n \"pyodide\",\n \"micropip\",\n ]\n for name in stdlib_names:\n obj = __import__(name)\n deprecate(name, obj, f\"Please use import {name}
instead.\")\n\n # special case\n deprecate(\n \"dedent\", dedent, \"Please use from textwrap import dedent
instead.\"\n )\n\n # these are names that used to leak in the globals but they are just\n # implementation details. People should not use them.\n private_names = [\n \"eval_formatter\",\n \"format_mime\",\n \"identity\",\n \"render_image\",\n \"MIME_RENDERERS\",\n \"MIME_METHODS\",\n ]\n for name in private_names:\n obj = globals()[name]\n message = (\n f\"{name}
is deprecated. \"\n \"This is a private implementation detail of pyscript. \"\n \"You should not use it.\"\n )\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # these names are available as js.XXX\n for name in [\"document\", \"console\"]:\n obj = getattr(js, name)\n deprecate(name, obj, f\"Please use js.{name}
instead.\")\n\n # PyScript is special, use a different message\n message = (\n \"The PyScript
object is deprecated. \"\n \"Please use pyscript
instead.\"\n )\n ns[\"PyScript\"] = DeprecatedGlobal(\"PyScript\", PyScript, message)\n";
-
- const logger = getLogger('pyscript/main');
- /* High-level overview of the lifecycle of a PyScript App:
-
- 1. pyscript.js is loaded by the browser. PyScriptApp().main() is called
-
- 2. loadConfig(): search for py-config and compute the config for the app
-
- 3. (it used to be "show the splashscreen", but now it's a plugin)
-
- 4. loadRuntime(): start downloading the actual runtime (e.g. pyodide.js)
-
- --- wait until (4) has finished ---
-
- 5. now the pyodide src is available. Initialize the engine
-
- 6. setup the environment, install packages
-
- 6.5: call the Plugin.afterSetup() hook
-
- 7. connect the py-script web component. This causes the execution of all the
- user scripts
-
- 8. initialize the rest of web components such as py-button, py-repl, etc.
-
- More concretely:
-
- - Points 1-4 are implemented sequentially in PyScriptApp.main().
-
- - PyScriptApp.loadRuntime adds a
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Weniv World Beta
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- terminal = false
- # packages = ["numpy", "nest_asyncio"]
-
- [[fetch]]
- from = "./assets/py/"
- files = ["built_in_functions.py", "character.py", "worldMap.py", "wall.py", "item.py", "coordinate.py", "modules.py", "error.py", "mob.py", "solution.py"]
-
-
-
-
-
-
-
-
- 코드 입력
-
- # shift + enter를 눌러 실행해 보세요.
- # 변수, 함수 목록은 World에 있습니다.
- mission_start()
- set_item(2, 2, 'fish-1')
- move()
- move()
- turn_left()
- turn_left()
- turn_left()
- repeat(2, move)
- # pick()
- mission_end()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-