The free and privacy-friendly screen recorder with no limits 🎥
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Stale first frame fix, better trim editor UX, better camera background blur, toasts hidden during recording
Alyssa X0db811b6b192
diff --git a/package-lock.json b/package-lock.jsonindex 5806ccc..0b4bd64 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,17 +1,17 @@{"name": "screenity",- "version": "4.7.1",+ "version": "4.7.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "screenity",- "version": "4.7.1",+ "version": "4.7.2","hasInstallScript": true,"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",- "@mediabunny/aac-encoder": "^1.56.0",- "@mediapipe/tasks-vision": "0.10.32",+ "@mediabunny/aac-encoder": "^1.62.1",+ "@mediapipe/tasks-vision": "1.1.1","@radix-ui/react-alert-dialog": "^1.0.4","@radix-ui/react-collapsible": "^1.0.2","@radix-ui/react-dropdown-menu": "^2.0.6",@@ -37,7 +37,7 @@"gif.js": "^0.2.0","jszip": "^3.10.1","localforage": "^1.10.0",- "mediabunny": "^1.56.0",+ "mediabunny": "^1.62.1","patch-package": "^8.0.0","plyr": "3.7.8","plyr-react": "^5.3.0",@@ -2159,9 +2159,9 @@}},"node_modules/@mediabunny/aac-encoder": {- "version": "1.61.5",- "resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.61.5.tgz",- "integrity": "sha512-PC1ZQJMX8FQlw7XjdyacVmTRCZ8DA6x8VyJXakmOQuWsddawfK+KBRhpSYD5ezqe1NdqfdmeLUwDsarjzsTSUA==",+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.62.1.tgz",+ "integrity": "sha512-3fiZYAX95d+TDp2vu0sXMYputLm2+W21fZQMUWTf9awKhsRC/wko9OXj4GLLmGKMRryvI9Ocv9HzhhHVRYWopQ==","license": "MPL-2.0","funding": {"type": "individual",@@ -2172,9 +2172,9 @@}},"node_modules/@mediapipe/tasks-vision": {- "version": "0.10.32",- "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.32.tgz",- "integrity": "sha512-3tiAZnmKloYnRXYoO3dKltTUGnqeCwzC4lV03uY0vCsE+aveJTyEVQyZHOlQGQNsjK+gRHzkf9q08C99Qm2K0Q==",+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-1.1.1.tgz",+ "integrity": "sha512-jwntgT5tzDrKOkqg6xNDNpRcTUnGvmylZE5DFnzPXossiWOIDdZX+C81LI75hlXhsG58YZW+lGzcmjH1qrQE/Q==","license": "Apache-2.0"},"node_modules/@nodelib/fs.scandir": {@@ -9007,9 +9007,9 @@}},"node_modules/mediabunny": {- "version": "1.61.5",- "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.61.5.tgz",- "integrity": "sha512-IYrDTozxGVRTWQ1YdIcF+P7S7qHvvkiQYsX3WUbAHkxgAcCfEn7a/RbM9i/WiJHJ1MSYZqSxZkna1UUn4FGGBQ==",+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.62.1.tgz",+ "integrity": "sha512-lYzeerDwo9QLhBCipqQDXOSV7InvaIFplllZQviPO5rPwH+IUr8M1uvumk1olIUgMRGkPiInRriv25WFErUgMw==","license": "MPL-2.0","workspaces": [".",diff --git a/package.json b/package.jsonindex cee3b03..7d2c2ec 100755--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "screenity",- "version": "4.7.1",+ "version": "4.7.2","description": "The free and privacy-friendly screen recorder with no sign in needed.","scripts": {"build": "cross-env NODE_ENV=production node utils/build.js",@@ -38,8 +38,8 @@},"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",- "@mediabunny/aac-encoder": "^1.56.0",- "@mediapipe/tasks-vision": "0.10.32",+ "@mediabunny/aac-encoder": "^1.62.1",+ "@mediapipe/tasks-vision": "1.1.1","@radix-ui/react-alert-dialog": "^1.0.4","@radix-ui/react-collapsible": "^1.0.2","@radix-ui/react-dropdown-menu": "^2.0.6",@@ -65,7 +65,7 @@"gif.js": "^0.2.0","jszip": "^3.10.1","localforage": "^1.10.0",- "mediabunny": "^1.56.0",+ "mediabunny": "^1.62.1","patch-package": "^8.0.0","plyr": "3.7.8","plyr-react": "^5.3.0",diff --git a/src/_locales/ca/messages.json b/src/_locales/ca/messages.jsonindex 000656d..2a5917f 100644--- a/src/_locales/ca/messages.json+++ b/src/_locales/ca/messages.json@@ -839,10 +839,6 @@"message": "Microfon desactivat","description": "Títol del missatge emergent amb el microfon deshabilitat"},- "hideUIAlerts": {- "message": "Amaga les notificacions d'eines",- "description": "Botó per amagar les alertes de la interfície"- },"noShowAgain": {"message": "No tornis a mostrar","description": "Botó de no tornis a mostrar"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "L'enregistrament d'una regió s'ha d'iniciar des de la pàgina","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Fes servir Retalla o Elimina per aplicar primer la selecció.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Afegeix primer un fitxer d'àudio per desar els canvis.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/de/messages.json b/src/_locales/de/messages.jsonindex fd4f03e..998cfd3 100644--- a/src/_locales/de/messages.json+++ b/src/_locales/de/messages.json@@ -839,10 +839,6 @@"message": "Mikrofon deaktiviert","description": "Toast-Titel 'Mikrofon deaktiviert'"},- "hideUIAlerts": {- "message": "UI-Benachrichtigungen ausblenden",- "description": "Schaltfläche 'UI-Benachrichtigungen ausblenden'"- },"noShowAgain": {"message": "Nicht erneut anzeigen","description": "Schaltfläche 'Nicht erneut anzeigen'"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "Die Aufnahme eines Bereichs muss auf der Seite gestartet werden","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Wende die Auswahl zuerst mit „Zuschneiden“ oder „Schneiden“ an.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Füge zuerst eine Audiodatei hinzu, um die Änderungen zu speichern.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.jsonindex 00ab0b7..0e98b56 100644--- a/src/_locales/en/messages.json+++ b/src/_locales/en/messages.json@@ -435,6 +435,14 @@"message": "Save changes","description": "Save button in sandbox editor page"},+ "sandboxEditorSelectionPendingHint": {+ "message": "Use Trim or Cut to apply your selection first.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Add an audio file first to save changes.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"+ },"sandboxEditorSaveProgressButton": {"message": "Saving...","description": "Save button in sandbox editor page while saving"@@ -839,10 +847,6 @@"message": "Microphone disabled","description": "Microphone disabled toast title"},- "hideUIAlerts": {- "message": "Hide UI notifications",- "description": "Hide UI alerts button"- },"noShowAgain": {"message": "Don't show again","description": "Don't show again button"diff --git a/src/_locales/es/messages.json b/src/_locales/es/messages.jsonindex da06d74..002e35d 100644--- a/src/_locales/es/messages.json+++ b/src/_locales/es/messages.json@@ -839,10 +839,6 @@"message": "Micrófono desactivado","description": "Título del aviso de micrófono deshabilitado"},- "hideUIAlerts": {- "message": "Ocultar las notificaciones de la interfaz",- "description": "Botón para ocultar las alertas de la interfaz"- },"noShowAgain": {"message": "No mostrar de nuevo","description": "Botón de no mostrar de nuevo"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "La grabación de una región debe iniciarse desde la página","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Usa Recortar o Quitar sección para aplicar primero tu selección.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Añade primero un archivo de audio para guardar los cambios.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/fr/messages.json b/src/_locales/fr/messages.jsonindex 70f838d..cf489c6 100644--- a/src/_locales/fr/messages.json+++ b/src/_locales/fr/messages.json@@ -839,10 +839,6 @@"message": "Microphone désactivé","description": "Titre de l'alerte microphone désactivé"},- "hideUIAlerts": {- "message": "Masquer les notifications de l'interface",- "description": "Bouton pour masquer les alertes de l'interface"- },"noShowAgain": {"message": "Ne pas afficher à nouveau","description": "Bouton Ne pas afficher à nouveau"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "L'enregistrement d'une zone doit être lancé depuis la page","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Utilisez Recadrer ou Supprimer pour appliquer d'abord votre sélection.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Ajoutez d'abord un fichier audio pour enregistrer les modifications.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/hi/messages.json b/src/_locales/hi/messages.jsonindex 622d94d..2c726ca 100644--- a/src/_locales/hi/messages.json+++ b/src/_locales/hi/messages.json@@ -839,10 +839,6 @@"message": "माइक्रोफ़ोन बंद है","description": "माइक्रोफ़ोन बंद टोस्ट शीर्षक"},- "hideUIAlerts": {- "message": "UI सूचनाओं को छुपाएं",- "description": "UI सूचनाओं को छुपाएं बटन"- },"noShowAgain": {"message": "फिर से दिखाना नहीं","description": "फिर से दिखाना नहीं बटन"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "क्षेत्र की रिकॉर्डिंग पेज से ही शुरू करनी होगी","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "पहले अपने चयन को लागू करने के लिए कटा या खंड काटें का उपयोग करें।",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "परिवर्तन सहेजने के लिए पहले एक ऑडियो फ़ाइल जोड़ें।",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/id/messages.json b/src/_locales/id/messages.jsonindex 9d916ba..52edd9d 100644--- a/src/_locales/id/messages.json+++ b/src/_locales/id/messages.json@@ -839,10 +839,6 @@"message": "Mikrofon dimatikan","description": "Judul toast Mikrofon dimatikan"},- "hideUIAlerts": {- "message": "Sembunyikan notifikasi UI",- "description": "Tombol Sembunyikan notifikasi UI"- },"noShowAgain": {"message": "Jangan tampilkan lagi","description": "Tombol Jangan tampilkan lagi"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "Perekaman area harus dimulai dari halaman","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Gunakan Potong untuk menerapkan pilihan Anda terlebih dahulu.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Tambahkan file audio terlebih dahulu untuk menyimpan perubahan.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/it/messages.json b/src/_locales/it/messages.jsonindex 08a8630..a392237 100644--- a/src/_locales/it/messages.json+++ b/src/_locales/it/messages.json@@ -839,10 +839,6 @@"message": "Microfono disattivato","description": "Titolo del messaggio del microfono disattivato"},- "hideUIAlerts": {- "message": "Nascondi le notifiche dell'interfaccia",- "description": "Pulsante per nascondere gli avvisi dell'interfaccia"- },"noShowAgain": {"message": "Non mostrare più","description": "Pulsante di non mostrare più"@@ -2051,5 +2047,13 @@"teleprompterRegionStartOnPage": {"message": "La registrazione di un'area deve essere avviata dalla pagina","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Usa Taglia o Rimuovi per applicare prima la selezione.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Aggiungi prima un file audio per salvare le modifiche.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/ko/messages.json b/src/_locales/ko/messages.jsonindex 6e76523..c13bf86 100644--- a/src/_locales/ko/messages.json+++ b/src/_locales/ko/messages.json@@ -839,10 +839,6 @@"message": "마이크 비활성화됨","description": "Microphone disabled toast title"},- "hideUIAlerts": {- "message": "UI 알림 숨기기",- "description": "Hide UI alerts button"- },"noShowAgain": {"message": "다시 표시하지 않음","description": "Don't show again button"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "영역 녹화는 페이지에서 시작해야 합니다","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "먼저 자르기를 사용해 선택 영역을 적용하세요.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "변경 사항을 저장하려면 먼저 오디오 파일을 추가하세요.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/pl/messages.json b/src/_locales/pl/messages.jsonindex 8c812d3..b309b1b 100644--- a/src/_locales/pl/messages.json+++ b/src/_locales/pl/messages.json@@ -839,10 +839,6 @@"message": "Mikrofon wyłączony","description": "Tytuł modalnego komunikatu o wyłączonym mikrofonie"},- "hideUIAlerts": {- "message": "Ukryj powiadomienia interfejsu",- "description": "Przycisk ukrywania alertów interfejsu"- },"noShowAgain": {"message": "Nie pokazuj ponownie","description": "Przycisk nie pokazuj ponownie"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "Nagrywanie obszaru trzeba rozpocząć ze strony","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Najpierw zastosuj zaznaczenie przyciskiem Przytnij lub Wycięcie.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Aby zapisać zmiany, najpierw dodaj plik audio.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/pt_BR/messages.json b/src/_locales/pt_BR/messages.jsonindex 5577126..6139540 100644--- a/src/_locales/pt_BR/messages.json+++ b/src/_locales/pt_BR/messages.json@@ -839,10 +839,6 @@"message": "Microfone desativado","description": "Título do aviso de microfone desativado"},- "hideUIAlerts": {- "message": "Ocultar notificações da interface",- "description": "Botão para ocultar alertas da interface"- },"noShowAgain": {"message": "Não mostrar novamente","description": "Botão de não mostrar novamente"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "A gravação de uma região precisa ser iniciada pela página","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Use Cortar para aplicar sua seleção primeiro.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Adicione primeiro um arquivo de áudio para salvar as alterações.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/pt_PT/messages.json b/src/_locales/pt_PT/messages.jsonindex aec58b3..50a8e4f 100644--- a/src/_locales/pt_PT/messages.json+++ b/src/_locales/pt_PT/messages.json@@ -839,10 +839,6 @@"message": "Microfone desativado","description": "Título do aviso de microfone desativado"},- "hideUIAlerts": {- "message": "Ocultar notificações da interface",- "description": "Botão para ocultar alertas da interface"- },"noShowAgain": {"message": "Não mostrar novamente","description": "Botão de não mostrar novamente"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "A gravação de uma região tem de ser iniciada a partir da página","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Use Recortar ou Cortar para aplicar primeiro a sua seleção.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Adicione primeiro um ficheiro de áudio para guardar as alterações.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/ru/messages.json b/src/_locales/ru/messages.jsonindex dd5ebec..56059c1 100644--- a/src/_locales/ru/messages.json+++ b/src/_locales/ru/messages.json@@ -839,10 +839,6 @@"message": "Микрофон отключен","description": "Заголовок всплывающего окна отключенного микрофона"},- "hideUIAlerts": {- "message": "Скрыть уведомления интерфейса",- "description": "Кнопка скрытия уведомлений интерфейса"- },"noShowAgain": {"message": "Не показывать снова","description": "Кнопка 'Не показывать снова'"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "Запись области нужно начинать со страницы","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Сначала примените выделение кнопкой «Обрезать» или «Вырезать».",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Чтобы сохранить изменения, сначала добавьте аудиофайл.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/ta/messages.json b/src/_locales/ta/messages.jsonindex 382fa1a..cd4a12e 100644--- a/src/_locales/ta/messages.json+++ b/src/_locales/ta/messages.json@@ -839,10 +839,6 @@"message": "மைக்ரோஃபோன் முடக்கப்பட்டுள்ளது","description": "மைக்ரோஃபோன் முடக்கப்பட்டுள்ளது விளக்க தலைப்பு"},- "hideUIAlerts": {- "message": "UI அறிவிப்புகளை மறை",- "description": "UI அறிவிப்புகளை மறைக்க பொது பொது"- },"noShowAgain": {"message": "மீண்டும் காட்ட விரும்பாதே","description": "மீண்டும் காட்ட விரும்பாதே பொது"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "பகுதி பதிவை பக்கத்திலிருந்தே தொடங்க வேண்டும்","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "முதலில் உங்கள் தேர்வைப் பயன்படுத்த குறை அல்லது பிளவு பயன்படுத்தவும்.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "மாற்றங்களை சேமிக்க முதலில் ஒரு ஆடியோ கோப்பைச் சேர்க்கவும்.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/tr/messages.json b/src/_locales/tr/messages.jsonindex 046f44f..8b38edf 100644--- a/src/_locales/tr/messages.json+++ b/src/_locales/tr/messages.json@@ -839,10 +839,6 @@"message": "Mikrofon devre dışı","description": "Mikrofon devre dışı bırakıldı bildirimi başlığı"},- "hideUIAlerts": {- "message": "UI bildirimlerini gizle",- "description": "UI uyarılarını gizle düğmesi"- },"noShowAgain": {"message": "Tekrar gösterme","description": "Tekrar gösterme düğmesi"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "Bölge kaydı sayfadan başlatılmalıdır","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Seçiminizi uygulamak için önce Kırp veya Kes'i kullanın.",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Değişiklikleri kaydetmek için önce bir ses dosyası ekleyin.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/uk/messages.json b/src/_locales/uk/messages.jsonindex 56bcdf5..925a5c2 100644--- a/src/_locales/uk/messages.json+++ b/src/_locales/uk/messages.json@@ -839,10 +839,6 @@"message": "Мікрофон вимкнено","description": "Microphone disabled toast title"},- "hideUIAlerts": {- "message": "Приховати сповіщення інтерфейсу",- "description": "Hide UI alerts button"- },"noShowAgain": {"message": "Не показувати знову","description": "Don't show again button"@@ -2054,5 +2050,13 @@"teleprompterRegionStartOnPage": {"message": "Запис області потрібно починати зі сторінки","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "Спочатку застосуйте виділення кнопкою «Обрізати» або «Вирізати».",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "Щоб зберегти зміни, спочатку додайте аудіофайл.",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.jsonindex b09ebfd..51e1655 100644--- a/src/_locales/zh_CN/messages.json+++ b/src/_locales/zh_CN/messages.json@@ -839,10 +839,6 @@"message": "麦克风已禁用","description": "Microphone disabled toast title"},- "hideUIAlerts": {- "message": "隐藏UI通知",- "description": "Hide UI alerts button"- },"noShowAgain": {"message": "不再显示","description": "Don't show again button"@@ -2055,5 +2051,13 @@"teleprompterRegionStartOnPage": {"message": "区域录制必须从页面开始","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "请先使用“修剪”或“剪切”应用所选范围。",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "请先添加音频文件,再保存更改。",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.jsonindex cc80f4c..ffea17a 100644--- a/src/_locales/zh_TW/messages.json+++ b/src/_locales/zh_TW/messages.json@@ -839,10 +839,6 @@"message": "麥克風已停用","description": "Microphone disabled toast title"},- "hideUIAlerts": {- "message": "隱藏介面內通知",- "description": "Hide UI alerts button"- },"noShowAgain": {"message": "不要再顯示","description": "Don't show again button"@@ -2056,5 +2052,13 @@"teleprompterRegionStartOnPage": {"message": "區域錄製必須從頁面開始","description": "Tooltip on the disabled Start button in the floating teleprompter window when recording a region, which can only be started from the page"+ },+ "sandboxEditorSelectionPendingHint": {+ "message": "請先使用「修剪」或「分割」套用所選範圍。",+ "description": "Tooltip on the disabled save button while trim handles are moved but no edit has been applied"+ },+ "sandboxEditorAudioPendingHint": {+ "message": "請先新增音訊檔案,再儲存變更。",+ "description": "Tooltip on the disabled save button in the audio editor until an audio file is added"}}diff --git a/src/assets/mediapipeVision/vision_wasm_internal.js b/src/assets/mediapipeVision/vision_wasm_internal.jsindex ac48a29..695157c 100644--- a/src/assets/mediapipeVision/vision_wasm_internal.js+++ b/src/assets/mediapipeVision/vision_wasm_internal.js@@ -1,2 +1,9140 @@-var ModuleFactory=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["jd"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("vision_wasm_internal.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}var tempDouble;var tempI64;var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{func();maybeExit()}catch(e){handleException(e)}};function getFullscreenElement(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement||document.msFullscreenElement}var safeSetTimeout=(func,timeout)=>setTimeout(()=>{callUserCallback(func)},timeout);var warnOnce=text=>{warnOnce.shown||={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;if(ENVIRONMENT_IS_NODE)text="warning: "+text;err(text)}};var preloadPlugins=[];var Browser={useWebGL:false,isFullscreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],preloadedImages:{},preloadedAudios:{},getCanvas:()=>Module["canvas"],init(){if(Browser.initted)return;Browser.initted=true;var imagePlugin={};imagePlugin["canHandle"]=function imagePlugin_canHandle(name){return!Module["noImageDecoding"]&&/\.(jpg|jpeg|png|bmp|webp)$/i.test(name)};imagePlugin["handle"]=async function imagePlugin_handle(byteArray,name){var b=new Blob([byteArray],{type:Browser.getMimetype(name)});if(b.size!==byteArray.length){b=new Blob([new Uint8Array(byteArray).buffer],{type:Browser.getMimetype(name)})}var url=URL.createObjectURL(b);return new Promise((resolve,reject)=>{var img=new Image;img.onload=()=>{var canvas=document.createElement("canvas");canvas.width=img.width;canvas.height=img.height;var ctx=canvas.getContext("2d");ctx.drawImage(img,0,0);Browser.preloadedImages[name]=canvas;URL.revokeObjectURL(url);resolve(byteArray)};img.onerror=event=>{err(`Image ${url} could not be decoded`);reject()};img.src=url})};preloadPlugins.push(imagePlugin);var audioPlugin={};audioPlugin["canHandle"]=function audioPlugin_canHandle(name){return!Module["noAudioDecoding"]&&name.slice(-4)in{".ogg":1,".wav":1,".mp3":1}};audioPlugin["handle"]=async function audioPlugin_handle(byteArray,name){return new Promise((resolve,reject)=>{var done=false;function finish(audio){if(done)return;done=true;Browser.preloadedAudios[name]=audio;resolve(byteArray)}var b=new Blob([byteArray],{type:Browser.getMimetype(name)});var url=URL.createObjectURL(b);var audio=new Audio;audio.addEventListener("canplaythrough",()=>finish(audio),false);audio.onerror=function audio_onerror(event){if(done)return;err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`);function encode64(data){var BASE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var PAD="=";var ret="";var leftchar=0;var leftbits=0;for(var i=0;i<data.length;i++){leftchar=leftchar<<8|data[i];leftbits+=8;while(leftbits>=6){var curr=leftchar>>leftbits-6&63;leftbits-=6;ret+=BASE[curr]}}if(leftbits==2){ret+=BASE[(leftchar&3)<<4];ret+=PAD+PAD}else if(leftbits==4){ret+=BASE[(leftchar&15)<<2];ret+=PAD}return ret}audio.src="data:audio/x-"+name.slice(-3)+";base64,"+encode64(byteArray);finish(audio)};audio.src=url;safeSetTimeout(()=>{finish(audio)},1e4)})};preloadPlugins.push(audioPlugin);function pointerLockChange(){var canvas=Browser.getCanvas();Browser.pointerLock=document.pointerLockElement===canvas}var canvas=Browser.getCanvas();if(canvas){document.addEventListener("pointerlockchange",pointerLockChange,false);if(Module["elementPointerLock"]){canvas.addEventListener("click",ev=>{if(!Browser.pointerLock&&Browser.getCanvas().requestPointerLock){Browser.getCanvas().requestPointerLock();ev.preventDefault()}},false)}}},createContext(canvas,useWebGL,setInModule,webGLContextAttributes){if(useWebGL&&Module["ctx"]&&canvas==Browser.getCanvas())return Module["ctx"];var ctx;var contextHandle;if(useWebGL){var contextAttributes={antialias:false,alpha:false,majorVersion:typeof WebGL2RenderingContext!="undefined"?2:1};if(webGLContextAttributes){for(var attribute in webGLContextAttributes){contextAttributes[attribute]=webGLContextAttributes[attribute]}}if(typeof GL!="undefined"){contextHandle=GL.createContext(canvas,contextAttributes);if(contextHandle){ctx=GL.getContext(contextHandle).GLctx}}}else{ctx=canvas.getContext("2d")}if(!ctx)return null;if(setInModule){Module["ctx"]=ctx;if(useWebGL)GL.makeContextCurrent(contextHandle);Browser.useWebGL=useWebGL;Browser.moduleContextCreatedCallbacks.forEach(callback=>callback());Browser.init()}return ctx},fullscreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullscreen(lockPointer,resizeCanvas){Browser.lockPointer=lockPointer;Browser.resizeCanvas=resizeCanvas;if(typeof Browser.lockPointer=="undefined")Browser.lockPointer=true;if(typeof Browser.resizeCanvas=="undefined")Browser.resizeCanvas=false;var canvas=Browser.getCanvas();function fullscreenChange(){Browser.isFullscreen=false;var canvasContainer=canvas.parentNode;if(getFullscreenElement()===canvasContainer){canvas.exitFullscreen=Browser.exitFullscreen;if(Browser.lockPointer)canvas.requestPointerLock();Browser.isFullscreen=true;if(Browser.resizeCanvas){Browser.setFullscreenCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}else{canvasContainer.parentNode.insertBefore(canvas,canvasContainer);canvasContainer.parentNode.removeChild(canvasContainer);if(Browser.resizeCanvas){Browser.setWindowedCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}Module["onFullScreen"]?.(Browser.isFullscreen);Module["onFullscreen"]?.(Browser.isFullscreen)}if(!Browser.fullscreenHandlersInstalled){Browser.fullscreenHandlersInstalled=true;document.addEventListener("fullscreenchange",fullscreenChange,false);document.addEventListener("mozfullscreenchange",fullscreenChange,false);document.addEventListener("webkitfullscreenchange",fullscreenChange,false);document.addEventListener("MSFullscreenChange",fullscreenChange,false)}var canvasContainer=document.createElement("div");canvas.parentNode.insertBefore(canvasContainer,canvas);canvasContainer.appendChild(canvas);canvasContainer.requestFullscreen=canvasContainer["requestFullscreen"]||canvasContainer["mozRequestFullScreen"]||canvasContainer["msRequestFullscreen"]||(canvasContainer["webkitRequestFullscreen"]?()=>canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"]):null)||(canvasContainer["webkitRequestFullScreen"]?()=>canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]):null);canvasContainer.requestFullscreen()},exitFullscreen(){if(!Browser.isFullscreen){return false}var CFS=document["exitFullscreen"]||document["cancelFullScreen"]||document["mozCancelFullScreen"]||document["msExitFullscreen"]||document["webkitCancelFullScreen"]||(()=>{});CFS.apply(document,[]);return true},safeSetTimeout(func,timeout){return safeSetTimeout(func,timeout)},getMimetype(name){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[name.slice(name.lastIndexOf(".")+1)]},getUserMedia(func){window.getUserMedia||=navigator["getUserMedia"]||navigator["mozGetUserMedia"];window.getUserMedia(func)},getMovementX(event){return event["movementX"]||event["mozMovementX"]||event["webkitMovementX"]||0},getMovementY(event){return event["movementY"]||event["mozMovementY"]||event["webkitMovementY"]||0},getMouseWheelDelta(event){var delta=0;switch(event.type){case"DOMMouseScroll":delta=event.detail/3;break;case"mousewheel":delta=event.wheelDelta/120;break;case"wheel":delta=event.deltaY;switch(event.deltaMode){case 0:delta/=100;break;case 1:delta/=3;break;case 2:delta*=80;break;default:abort("unrecognized mouse wheel delta mode: "+event.deltaMode)}break;default:abort("unrecognized mouse wheel event: "+event.type)}return delta},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseCoords(pageX,pageY){var canvas=Browser.getCanvas();var rect=canvas.getBoundingClientRect();var scrollX=typeof window.scrollX!="undefined"?window.scrollX:window.pageXOffset;var scrollY=typeof window.scrollY!="undefined"?window.scrollY:window.pageYOffset;var adjustedX=pageX-(scrollX+rect.left);var adjustedY=pageY-(scrollY+rect.top);adjustedX=adjustedX*(canvas.width/rect.width);adjustedY=adjustedY*(canvas.height/rect.height);return{x:adjustedX,y:adjustedY}},setMouseCoords(pageX,pageY){const{x,y}=Browser.calculateMouseCoords(pageX,pageY);Browser.mouseMovementX=x-Browser.mouseX;Browser.mouseMovementY=y-Browser.mouseY;Browser.mouseX=x;Browser.mouseY=y},calculateMouseEvent(event){if(Browser.pointerLock){if(event.type!="mousemove"&&"mozMovementX"in event){Browser.mouseMovementX=Browser.mouseMovementY=0}else{Browser.mouseMovementX=Browser.getMovementX(event);Browser.mouseMovementY=Browser.getMovementY(event)}Browser.mouseX+=Browser.mouseMovementX;Browser.mouseY+=Browser.mouseMovementY}else{if(event.type==="touchstart"||event.type==="touchend"||event.type==="touchmove"){var touch=event.touch;if(touch===undefined){return}var coords=Browser.calculateMouseCoords(touch.pageX,touch.pageY);if(event.type==="touchstart"){Browser.lastTouches[touch.identifier]=coords;Browser.touches[touch.identifier]=coords}else if(event.type==="touchend"||event.type==="touchmove"){var last=Browser.touches[touch.identifier];last||=coords;Browser.lastTouches[touch.identifier]=last;Browser.touches[touch.identifier]=coords}return}Browser.setMouseCoords(event.pageX,event.pageY)}},resizeListeners:[],updateResizeListeners(){var canvas=Browser.getCanvas();Browser.resizeListeners.forEach(listener=>listener(canvas.width,canvas.height))},setCanvasSize(width,height,noUpdates){var canvas=Browser.getCanvas();Browser.updateCanvasDimensions(canvas,width,height);if(!noUpdates)Browser.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>2];flags=flags|8388608;HEAP32[SDL.screen>>2]=flags}Browser.updateCanvasDimensions(Browser.getCanvas());Browser.updateResizeListeners()},setWindowedCanvasSize(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>2];flags=flags&~8388608;HEAP32[SDL.screen>>2]=flags}Browser.updateCanvasDimensions(Browser.getCanvas());Browser.updateResizeListeners()},updateCanvasDimensions(canvas,wNative,hNative){if(wNative&&hNative){canvas.widthNative=wNative;canvas.heightNative=hNative}else{wNative=canvas.widthNative;hNative=canvas.heightNative}var w=wNative;var h=hNative;if(Module["forcedAspectRatio"]>0){if(w/h<Module["forcedAspectRatio"]){w=Math.round(h*Module["forcedAspectRatio"])}else{h=Math.round(w/Module["forcedAspectRatio"])}}if(getFullscreenElement()===canvas.parentNode&&typeof screen!="undefined"){var factor=Math.min(screen.width/w,screen.height/h);w=Math.round(w*factor);h=Math.round(h*factor)}if(Browser.resizeCanvas){if(canvas.width!=w)canvas.width=w;if(canvas.height!=h)canvas.height=h;if(typeof canvas.style!="undefined"){canvas.style.removeProperty("width");canvas.style.removeProperty("height")}}else{if(canvas.width!=wNative)canvas.width=wNative;if(canvas.height!=hNative)canvas.height=hNative;if(typeof canvas.style!="undefined"){if(w!=wNative||h!=hNative){canvas.style.setProperty("width",w+"px","important");canvas.style.setProperty("height",h+"px","important")}else{canvas.style.removeProperty("width");canvas.style.removeProperty("height")}}}}};var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);return UTF8Decoder.decode(heapOrArray.buffer?heapOrArray.subarray(idx,endPtr):new Uint8Array(heapOrArray.slice(idx,endPtr)))};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var zeroMemory=(ptr,size)=>HEAPU8.fill(0,ptr,ptr+size);var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>{if(!ptr)return"";var end=findStringEnd(HEAPU8,ptr,maxBytesToRead,ignoreNul);return UTF8Decoder.decode(HEAPU8.subarray(ptr,end))};var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+24>>2]=tempI64[0],HEAP32[buf+28>>2]=tempI64[1];HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();tempI64=[Math.floor(atime/1e3)>>>0,(tempDouble=Math.floor(atime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;tempI64=[Math.floor(mtime/1e3)>>>0,(tempDouble=Math.floor(mtime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>2]=tempI64[0],HEAP32[buf+60>>2]=tempI64[1];HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;tempI64=[Math.floor(ctime/1e3)>>>0,(tempDouble=Math.floor(ctime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>2]=tempI64[0],HEAP32[buf+76>>2]=tempI64[1];HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>2]=tempI64[0],HEAP32[buf+92>>2]=tempI64[1];return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;tempI64=[stats.blocks>>>0,(tempDouble=stats.blocks,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+8>>2]=tempI64[0],HEAP32[buf+12>>2]=tempI64[1];tempI64=[stats.bfree>>>0,(tempDouble=stats.bfree,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+16>>2]=tempI64[0],HEAP32[buf+20>>2]=tempI64[1];tempI64=[stats.bavail>>>0,(tempDouble=stats.bavail,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+24>>2]=tempI64[0],HEAP32[buf+28>>2]=tempI64[1];tempI64=[stats.files>>>0,(tempDouble=stats.files,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+32>>2]=tempI64[0],HEAP32[buf+36>>2]=tempI64[1];tempI64=[stats.ffree>>>0,(tempDouble=stats.ffree,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_dup(fd){try{var old=SYSCALLS.getStreamFromFD(fd);return FS.dupStream(old).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){try{return SYSCALLS.writeStat(buf,FS.fstat(fd))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function ___syscall_ftruncate64(fd,length_low,length_high){var length=convertI32PairToI53Checked(length_low,length_high);try{if(isNaN(length))return-61;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.lstat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.writeStat(buf,nofollow?FS.lstat(path):FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=new TextDecoder("utf-16le");var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx))};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var argN=new Array(argCount);var invokerFunction=(handle,methodName,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=argFromPtr[i](args+offset);offset+=GenericWireTypeSize}var rv;switch(kind){case 0:rv=Emval.toValue(handle).apply(null,argN);break;case 2:rv=Reflect.construct(Emval.toValue(handle),argN);break;case 3:rv=argN[0];break;case 1:rv=Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);break}return emval_returnValue(toReturnWire,destructorsRef,rv)};var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_get_global=name=>{if(!name){return Emval.toHandle(globalThis)}name=getStringOrSymbol(name);return Emval.toHandle(globalThis[name])};var __emval_get_property=(handle,key)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);return Emval.toHandle(handle[key])};var __emval_incref=handle=>{if(handle>9){emval_handles[handle+1]+=1}};var __emval_instanceof=(object,constructor)=>{object=Emval.toValue(object);constructor=Emval.toValue(constructor);return object instanceof constructor};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var __emval_typeof=handle=>{handle=Emval.toValue(handle);return Emval.toHandle(typeof handle)};function __gmtime_js(time_low,time_high,tmPtr){var time=convertI32PairToI53Checked(time_low,time_high);var date=new Date(time*1e3);HEAP32[tmPtr>>2]=date.getUTCSeconds();HEAP32[tmPtr+4>>2]=date.getUTCMinutes();HEAP32[tmPtr+8>>2]=date.getUTCHours();HEAP32[tmPtr+12>>2]=date.getUTCDate();HEAP32[tmPtr+16>>2]=date.getUTCMonth();HEAP32[tmPtr+20>>2]=date.getUTCFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getUTCDay();var start=Date.UTC(date.getUTCFullYear(),0,1,0,0,0,0);var yday=(date.getTime()-start)/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday}var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};function __localtime_js(time_low,time_high,tmPtr){var time=convertI32PairToI53Checked(time_low,time_high);var date=new Date(time*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>2]=dst}var setTempRet0=val=>__emscripten_tempret_set(val);var __mktime_js=function(tmPtr){var ret=(()=>{var date=new Date(HEAP32[tmPtr+20>>2]+1900,HEAP32[tmPtr+16>>2],HEAP32[tmPtr+12>>2],HEAP32[tmPtr+8>>2],HEAP32[tmPtr+4>>2],HEAP32[tmPtr>>2],0);var dst=HEAP32[tmPtr+32>>2];var guessedOffset=date.getTimezoneOffset();var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dstOffset=Math.min(winterOffset,summerOffset);if(dst<0){HEAP32[tmPtr+32>>2]=Number(summerOffset!=winterOffset&&dstOffset==guessedOffset)}else if(dst>0!=(dstOffset==guessedOffset)){var nonDstOffset=Math.max(winterOffset,summerOffset);var trueOffset=dst>0?dstOffset:nonDstOffset;date.setTime(date.getTime()+(trueOffset-guessedOffset)*6e4)}HEAP32[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getYear();var timeMs=date.getTime();if(isNaN(timeMs)){return-1}return timeMs/1e3})();return setTempRet0((tempDouble=ret,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)),ret>>>0};function __mmap_js(len,prot,flags,fd,offset_low,offset_high,allocated,addr){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{var stream=SYSCALLS.getStreamFromFD(fd);var res=FS.mmap(stream,len,offset,prot,flags);var ptr=res.ptr;HEAP32[allocated>>2]=res.allocated;HEAPU32[addr>>2]=ptr;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function __munmap_js(addr,len,prot,flags,fd,offset_low,offset_high){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_get_now=()=>performance.now();var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;function _clock_time_get(clk_id,ignored_precision_low,ignored_precision_high,ptime){var ignored_precision=convertI32PairToI53Checked(ignored_precision_low,ignored_precision_high);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);tempI64=[nsec>>>0,(tempDouble=nsec,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptime>>2]=tempI64[0],HEAP32[ptime+4>>2]=tempI64[1];return 0}var readEmAsmArgsArray=[];var readEmAsmArgs=(sigPtr,buf)=>{readEmAsmArgsArray.length=0;var ch;while(ch=HEAPU8[sigPtr++]){var wide=ch!=105;wide&=ch!=112;buf+=wide&&buf%8?4:0;readEmAsmArgsArray.push(ch==112?HEAPU32[buf>>2]:ch==105?HEAP32[buf>>2]:HEAPF64[buf>>3]);buf+=wide?8:4}return readEmAsmArgsArray};var runEmAsmFunction=(code,sigPtr,argbuf)=>{var args=readEmAsmArgs(sigPtr,argbuf);return ASM_CONSTS[code](...args)};var _emscripten_asm_const_int=(code,sigPtr,argbuf)=>runEmAsmFunction(code,sigPtr,argbuf);var _emscripten_asm_const_ptr=(code,sigPtr,argbuf)=>runEmAsmFunction(code,sigPtr,argbuf);var _emscripten_errn=(str,len)=>err(UTF8ToString(str,len));var getHeapMax=()=>2147483648;var _emscripten_get_heap_max=()=>getHeapMax();var _emscripten_has_asyncify=()=>0;var _emscripten_outn=(str,len)=>out(UTF8ToString(str,len));var UNWIND_CACHE={};var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};var convertFrameToPC=frame=>{var match;if(match=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(frame)){return+match[1]}else if(match=/:(\d+):\d+(?:\)|$)/.exec(frame)){return 2147483648|+match[1]}return 0};var saveInUnwindCache=callstack=>{for(var line of callstack){var pc=convertFrameToPC(line);if(pc){UNWIND_CACHE[pc]=line}}};var jsStackTrace=()=>(new Error).stack.toString();var _emscripten_stack_snapshot=()=>{var callstack=jsStackTrace().split("\n");if(callstack[0]=="Error"){callstack.shift()}saveInUnwindCache(callstack);UNWIND_CACHE.last_addr=convertFrameToPC(callstack[3]);UNWIND_CACHE.last_stack=callstack;return UNWIND_CACHE.last_addr};var _emscripten_pc_get_function=pc=>{var frame=UNWIND_CACHE[pc];if(!frame)return 0;var name;var match;if(match=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(frame)){name=match[1]}else if(match=/^\s+at (.*) \(.*\)$/.exec(frame)){name=match[1]}else if(match=/^(.+?)@/.exec(frame)){name=match[1]}else{return 0}_free(_emscripten_pc_get_function.ret??0);_emscripten_pc_get_function.ret=stringToNewUTF8(name);return _emscripten_pc_get_function.ret};var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var _emscripten_stack_unwind_buffer=(addr,buffer,count)=>{var stack;if(UNWIND_CACHE.last_addr==addr){stack=UNWIND_CACHE.last_stack}else{stack=jsStackTrace().split("\n");if(stack[0]=="Error"){stack.shift()}saveInUnwindCache(stack)}var offset=3;while(stack[offset]&&convertFrameToPC(stack[offset])!=addr){++offset}for(var i=0;i<count&&stack[i+offset];++i){HEAP32[buffer+i*4>>2]=convertFrameToPC(stack[i+offset])}return i};var GLctx;var webgl_enable_ANGLE_instanced_arrays=ctx=>{var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=(index,divisor)=>ext["vertexAttribDivisorANGLE"](index,divisor);ctx["drawArraysInstanced"]=(mode,first,count,primcount)=>ext["drawArraysInstancedANGLE"](mode,first,count,primcount);ctx["drawElementsInstanced"]=(mode,count,type,indices,primcount)=>ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount);return 1}};var webgl_enable_OES_vertex_array_object=ctx=>{var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=()=>ext["createVertexArrayOES"]();ctx["deleteVertexArray"]=vao=>ext["deleteVertexArrayOES"](vao);ctx["bindVertexArray"]=vao=>ext["bindVertexArrayOES"](vao);ctx["isVertexArray"]=vao=>ext["isVertexArrayOES"](vao);return 1}};var webgl_enable_WEBGL_draw_buffers=ctx=>{var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=(n,bufs)=>ext["drawBuffersWEBGL"](n,bufs);return 1}};var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.dibvbi=ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.mdibvbi=ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));var webgl_enable_EXT_polygon_offset_clamp=ctx=>!!(ctx.extPolygonOffsetClamp=ctx.getExtension("EXT_polygon_offset_clamp"));var webgl_enable_EXT_clip_control=ctx=>!!(ctx.extClipControl=ctx.getExtension("EXT_clip_control"));var webgl_enable_WEBGL_polygon_mode=ctx=>!!(ctx.webglPolygonMode=ctx.getExtension("WEBGL_polygon_mode"));var webgl_enable_WEBGL_multi_draw=ctx=>!!(ctx.multiDrawWebgl=ctx.getExtension("WEBGL_multi_draw"));var getEmscriptenSupportedExtensions=ctx=>{var supportedExtensions=["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_disjoint_timer_query","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_depth_texture","WEBGL_draw_buffers","EXT_color_buffer_float","EXT_conservative_depth","EXT_disjoint_timer_query_webgl2","EXT_texture_norm16","NV_shader_noperspective_interpolation","WEBGL_clip_cull_distance","EXT_clip_control","EXT_color_buffer_half_float","EXT_depth_clamp","EXT_float_blend","EXT_polygon_offset_clamp","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","KHR_parallel_shader_compile","OES_texture_float_linear","WEBGL_blend_func_extended","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_multi_draw","WEBGL_polygon_mode"];return(ctx.getSupportedExtensions()||[]).filter(ext=>supportedExtensions.includes(ext))};var registerPreMainLoop=f=>{typeof MainLoop!="undefined"&&MainLoop.preMainLoop.push(f)};var GL={counter:1,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],samplers:[],transformFeedbacks:[],syncs:[],byteSizeByTypeRoot:5120,byteSizeByType:[1,1,2,2,4,4,4,2,3,4,8],stringCache:{},stringiCache:{},unpackAlignment:4,unpackRowLength:0,recordError:errorCode=>{if(!GL.lastError){GL.lastError=errorCode}},getNewId:table=>{var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}while(table[ret]){ret=GL.counter++}return ret},genObject:(n,buffers,createFunction,objectTable)=>{for(var i=0;i<n;i++){var buffer=GLctx[createFunction]();var id=buffer&&GL.getNewId(objectTable);if(buffer){buffer.name=id;objectTable[id]=buffer}else{GL.recordError(1282)}HEAP32[buffers+i*4>>2]=id}},MAX_TEMP_BUFFER_SIZE:2097152,numTempVertexBuffersPerSize:64,log2ceilLookup:i=>32-Math.clz32(i===0?0:i-1),generateTempBuffers:(quads,context)=>{var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);context.tempVertexBufferCounters1=[];context.tempVertexBufferCounters2=[];context.tempVertexBufferCounters1.length=context.tempVertexBufferCounters2.length=largestIndex+1;context.tempVertexBuffers1=[];context.tempVertexBuffers2=[];context.tempVertexBuffers1.length=context.tempVertexBuffers2.length=largestIndex+1;context.tempIndexBuffers=[];context.tempIndexBuffers.length=largestIndex+1;for(var i=0;i<=largestIndex;++i){context.tempIndexBuffers[i]=null;context.tempVertexBufferCounters1[i]=context.tempVertexBufferCounters2[i]=0;var ringbufferLength=GL.numTempVertexBuffersPerSize;context.tempVertexBuffers1[i]=[];context.tempVertexBuffers2[i]=[];var ringbuffer1=context.tempVertexBuffers1[i];var ringbuffer2=context.tempVertexBuffers2[i];ringbuffer1.length=ringbuffer2.length=ringbufferLength;for(var j=0;j<ringbufferLength;++j){ringbuffer1[j]=ringbuffer2[j]=null}}if(quads){context.tempQuadIndexBuffer=GLctx.createBuffer();context.GLctx.bindBuffer(34963,context.tempQuadIndexBuffer);var numIndexes=GL.MAX_TEMP_BUFFER_SIZE>>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<<idx,35048);GLctx.bindBuffer(34962,prevVBO);return ringbuffer[nextFreeBufferIndex]},getTempIndexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ibo=GL.currentContext.tempIndexBuffers[idx];if(ibo){return ibo}var prevIBO=GLctx.getParameter(34965);GL.currentContext.tempIndexBuffers[idx]=GLctx.createBuffer();GLctx.bindBuffer(34963,GL.currentContext.tempIndexBuffers[idx]);GLctx.bufferData(34963,1<<idx,35048);GLctx.bindBuffer(34963,prevIBO);return GL.currentContext.tempIndexBuffers[idx]},newRenderingFrameStarted:()=>{if(!GL.currentContext){return}var vb=GL.currentContext.tempVertexBuffers1;GL.currentContext.tempVertexBuffers1=GL.currentContext.tempVertexBuffers2;GL.currentContext.tempVertexBuffers2=vb;vb=GL.currentContext.tempVertexBufferCounters1;GL.currentContext.tempVertexBufferCounters1=GL.currentContext.tempVertexBufferCounters2;GL.currentContext.tempVertexBufferCounters2=vb;var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);for(var i=0;i<=largestIndex;++i){GL.currentContext.tempVertexBufferCounters1[i]=0}},getSource:(shader,count,string,length)=>{var source="";for(var i=0;i<count;++i){var len=length?HEAPU32[length+i*4>>2]:undefined;source+=UTF8ToString(HEAPU32[string+i*4>>2],len)}return source},calcBufLength:(size,type,stride,count)=>{if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:count=>{GL.resetBufferBinding=false;for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(!cb.clientside||!cb.enabled)continue;GL.resetBufferBinding=true;var size=GL.calcBufLength(cb.size,cb.type,cb.stride,count);var buf=GL.getTempVertexBuffer(size);GLctx.bindBuffer(34962,buf);GLctx.bufferSubData(34962,0,HEAPU8.subarray(cb.ptr,cb.ptr+size));cb.vertexAttribPointerAdaptor.call(GLctx,i,cb.size,cb.type,cb.normalized,cb.stride,0)}},postDrawHandleClientVertexAttribBindings:()=>{if(GL.resetBufferBinding){GLctx.bindBuffer(34962,GL.buffers[GLctx.currentArrayBufferBinding])}},createContext:(canvas,webGLContextAttributes)=>{if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:(ctx,webGLContextAttributes)=>{var handle=GL.getNewId(GL.contexts);var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault=="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i<context.maxVertexAttribs;i++){context.clientBuffers[i]={enabled:false,clientside:false,size:0,type:0,normalized:0,stride:0,ptr:0,vertexAttribPointerAdaptor:null}}GL.generateTempBuffers(false,context);return handle},makeContextCurrent:contextHandle=>{GL.currentContext=GL.contexts[contextHandle];Module["ctx"]=GLctx=GL.currentContext?.GLctx;return!(contextHandle&&!GLctx)},getContext:contextHandle=>GL.contexts[contextHandle],deleteContext:contextHandle=>{if(GL.currentContext===GL.contexts[contextHandle]){GL.currentContext=null}if(typeof JSEvents=="object"){JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas)}if(GL.contexts[contextHandle]?.GLctx.canvas){GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined}GL.contexts[contextHandle]=null},initExtensions:context=>{context||=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;webgl_enable_WEBGL_multi_draw(GLctx);webgl_enable_EXT_polygon_offset_clamp(GLctx);webgl_enable_EXT_clip_control(GLctx);webgl_enable_WEBGL_polygon_mode(GLctx);webgl_enable_ANGLE_instanced_arrays(GLctx);webgl_enable_OES_vertex_array_object(GLctx);webgl_enable_WEBGL_draw_buffers(GLctx);webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(context.version>=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}getEmscriptenSupportedExtensions(GLctx).forEach(ext=>{if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}})}};var webglPowerPreferences=["default","low-power","high-performance"];var specialHTMLTargets=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];var findEventTarget=target=>{if(!target)return window;if(typeof target=="number")target=specialHTMLTargets[target]||UTF8ToString(target);if(target==="#window")return window;else if(target==="#document")return document;else if(target==="#screen")return screen;else if(target==="#canvas")return Module["canvas"];else if(typeof target=="string")return typeof document!="undefined"?document.getElementById(target):null;return target};var findCanvasEventTarget=target=>{if(typeof target=="number")target=UTF8ToString(target);if(!target||target==="#canvas"){if(typeof GL!="undefined"&&GL.offscreenCanvases["canvas"])return GL.offscreenCanvases["canvas"];return Module["canvas"]}if(typeof GL!="undefined"&&GL.offscreenCanvases[target])return GL.offscreenCanvases[target];return findEventTarget(target)};var _emscripten_webgl_do_create_context=(target,attributes)=>{var attr32=attributes>>2;var powerPreference=HEAP32[attr32+(8>>2)];var contextAttributes={alpha:!!HEAP8[attributes+0],depth:!!HEAP8[attributes+1],stencil:!!HEAP8[attributes+2],antialias:!!HEAP8[attributes+3],premultipliedAlpha:!!HEAP8[attributes+4],preserveDrawingBuffer:!!HEAP8[attributes+5],powerPreference:webglPowerPreferences[powerPreference],failIfMajorPerformanceCaveat:!!HEAP8[attributes+12],majorVersion:HEAP32[attr32+(16>>2)],minorVersion:HEAP32[attr32+(20>>2)],enableExtensionsByDefault:HEAP8[attributes+24],explicitSwapControl:HEAP8[attributes+25],proxyContextToMainThread:HEAP32[attr32+(28>>2)],renderViaOffscreenBackBuffer:HEAP8[attributes+32]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle};var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;var _emscripten_webgl_destroy_context=contextHandle=>{if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)};var _emscripten_webgl_get_context_attributes=(c,a)=>{if(!a)return-5;c=GL.contexts[c];if(!c)return-3;var t=c.GLctx?.getContextAttributes();if(!t)return-3;HEAP8[a]=t.alpha;HEAP8[a+1]=t.depth;HEAP8[a+2]=t.stencil;HEAP8[a+3]=t.antialias;HEAP8[a+4]=t.premultipliedAlpha;HEAP8[a+5]=t.preserveDrawingBuffer;var power=t["powerPreference"]&&webglPowerPreferences.indexOf(t["powerPreference"]);HEAP32[a+8>>2]=power;HEAP8[a+12]=t.failIfMajorPerformanceCaveat;HEAP32[a+16>>2]=c.version;HEAP32[a+20>>2]=0;HEAP8[a+24]=c.attributes.enableExtensionsByDefault;return 0};var _emscripten_webgl_do_get_current_context=()=>GL.currentContext?GL.currentContext.handle:0;var _emscripten_webgl_get_current_context=_emscripten_webgl_do_get_current_context;var _emscripten_webgl_make_context_current=contextHandle=>{var success=GL.makeContextCurrent(contextHandle);return success?0:-5};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var writeI53ToI64=(ptr,num)=>{HEAPU32[ptr>>2]=num;var lower=HEAPU32[ptr>>2];HEAPU32[ptr+4>>2]=(num-lower)/4294967296};var readI53FromI64=ptr=>HEAPU32[ptr>>2]+HEAP32[ptr+4>>2]*4294967296;var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var WebGPU={Internals:{jsObjects:[],jsObjectInsert:(ptr,jsObject)=>{ptr>>>=0;WebGPU.Internals.jsObjects[ptr]=jsObject},bufferOnUnmaps:[],futures:[],futureInsert:(futureId,promise)=>{}},getJsObject:ptr=>{if(!ptr)return undefined;ptr>>>=0;return WebGPU.Internals.jsObjects[ptr]},importJsAdapter:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateAdapter(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsBindGroup:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateBindGroup(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsBindGroupLayout:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateBindGroupLayout(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsBuffer:(buffer,parentPtr=0)=>{assert(buffer.mapState!="pending");var mapState=buffer.mapState=="mapped"?3:1;var bufferPtr=_emwgpuCreateBuffer(parentPtr,mapState);WebGPU.Internals.jsObjectInsert(bufferPtr,buffer);if(buffer.mapState=="mapped"){WebGPU.Internals.bufferOnUnmaps[bufferPtr]=[]}return bufferPtr},importJsCommandBuffer:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateCommandBuffer(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsCommandEncoder:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateCommandEncoder(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsComputePassEncoder:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateComputePassEncoder(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsComputePipeline:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateComputePipeline(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsDevice:(device,parentPtr=0)=>{var queuePtr=_emwgpuCreateQueue(parentPtr);var devicePtr=_emwgpuCreateDevice(parentPtr,queuePtr);WebGPU.Internals.jsObjectInsert(queuePtr,device.queue);WebGPU.Internals.jsObjectInsert(devicePtr,device);return devicePtr},importJsExternalTexture:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateExternalTexture(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsPipelineLayout:(obj,parentPtr=0)=>{var ptr=_emwgpuCreatePipelineLayout(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsQuerySet:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateQuerySet(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsQueue:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateQueue(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsRenderBundle:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateRenderBundle(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsRenderBundleEncoder:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateRenderBundleEncoder(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsRenderPassEncoder:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateRenderPassEncoder(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsRenderPipeline:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateRenderPipeline(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsSampler:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateSampler(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsShaderModule:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateShaderModule(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsSurface:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateSurface(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsTexture:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateTexture(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},importJsTextureView:(obj,parentPtr=0)=>{var ptr=_emwgpuCreateTextureView(parentPtr);WebGPU.Internals.jsObjects[ptr]=obj;return ptr},errorCallback:(callback,type,message,userdata)=>{var sp=stackSave();var messagePtr=stringToUTF8OnStack(message);getWasmTableEntry(callback)(type,messagePtr,userdata);stackRestore(sp)},iterateExtensions:(root,handlers)=>{for(var ptr=HEAPU32[root>>2];ptr;ptr=HEAPU32[ptr>>2]){var sType=HEAP32[ptr+4>>2];var handler=handlers[sType](ptr)}},setStringView:(ptr,data,length)=>{HEAPU32[ptr>>2]=data;HEAPU32[ptr+4>>2]=length},makeStringFromStringView:stringViewPtr=>{var ptr=HEAPU32[stringViewPtr>>2];var length=HEAPU32[stringViewPtr+4>>2];return UTF8ToString(ptr,length)},makeStringFromOptionalStringView:stringViewPtr=>{var ptr=HEAPU32[stringViewPtr>>2];var length=HEAPU32[stringViewPtr+4>>2];if(!ptr){if(length===0){return""}return undefined}return UTF8ToString(ptr,length)},makeColor:ptr=>({r:HEAPF64[ptr>>3],g:HEAPF64[ptr+8>>3],b:HEAPF64[ptr+16>>3],a:HEAPF64[ptr+24>>3]}),makeExtent3D:ptr=>({width:HEAPU32[ptr>>2],height:HEAPU32[ptr+4>>2],depthOrArrayLayers:HEAPU32[ptr+8>>2]}),makeOrigin3D:ptr=>({x:HEAPU32[ptr>>2],y:HEAPU32[ptr+4>>2],z:HEAPU32[ptr+8>>2]}),makeTexelCopyTextureInfo:ptr=>({texture:WebGPU.getJsObject(HEAPU32[ptr>>2]),mipLevel:HEAPU32[ptr+4>>2],origin:WebGPU.makeOrigin3D(ptr+8),aspect:WebGPU.TextureAspect[HEAP32[ptr+20>>2]]}),makeTexelCopyBufferLayout:ptr=>{var bytesPerRow=HEAPU32[ptr+8>>2];var rowsPerImage=HEAPU32[ptr+12>>2];return{offset:readI53FromI64(ptr),bytesPerRow:bytesPerRow===4294967295?undefined:bytesPerRow,rowsPerImage:rowsPerImage===4294967295?undefined:rowsPerImage}},makeTexelCopyBufferInfo:ptr=>{var layoutPtr=ptr+0;var bufferCopyView=WebGPU.makeTexelCopyBufferLayout(layoutPtr);bufferCopyView["buffer"]=WebGPU.getJsObject(HEAPU32[ptr+16>>2]);return bufferCopyView},makePassTimestampWrites:ptr=>{if(ptr===0)return undefined;return{querySet:WebGPU.getJsObject(HEAPU32[ptr+4>>2]),beginningOfPassWriteIndex:HEAPU32[ptr+8>>2],endOfPassWriteIndex:HEAPU32[ptr+12>>2]}},makePipelineConstants:(constantCount,constantsPtr)=>{if(!constantCount)return;var constants={};for(var i=0;i<constantCount;++i){var entryPtr=constantsPtr+24*i;var key=WebGPU.makeStringFromStringView(entryPtr+4);constants[key]=HEAPF64[entryPtr+16>>3]}return constants},makePipelineLayout:layoutPtr=>{if(!layoutPtr)return"auto";return WebGPU.getJsObject(layoutPtr)},makeComputeState:ptr=>{if(!ptr)return undefined;var desc={module:WebGPU.getJsObject(HEAPU32[ptr+4>>2]),constants:WebGPU.makePipelineConstants(HEAPU32[ptr+16>>2],HEAPU32[ptr+20>>2]),entryPoint:WebGPU.makeStringFromOptionalStringView(ptr+8)};return desc},makeComputePipelineDesc:descriptor=>{var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),layout:WebGPU.makePipelineLayout(HEAPU32[descriptor+12>>2]),compute:WebGPU.makeComputeState(descriptor+16)};return desc},makeRenderPipelineDesc:descriptor=>{function makePrimitiveState(psPtr){if(!psPtr)return undefined;return{topology:WebGPU.PrimitiveTopology[HEAP32[psPtr+4>>2]],stripIndexFormat:WebGPU.IndexFormat[HEAP32[psPtr+8>>2]],frontFace:WebGPU.FrontFace[HEAP32[psPtr+12>>2]],cullMode:WebGPU.CullMode[HEAP32[psPtr+16>>2]],unclippedDepth:!!HEAPU32[psPtr+20>>2]}}function makeBlendComponent(bdPtr){if(!bdPtr)return undefined;return{operation:WebGPU.BlendOperation[HEAP32[bdPtr>>2]],srcFactor:WebGPU.BlendFactor[HEAP32[bdPtr+4>>2]],dstFactor:WebGPU.BlendFactor[HEAP32[bdPtr+8>>2]]}}function makeBlendState(bsPtr){if(!bsPtr)return undefined;return{alpha:makeBlendComponent(bsPtr+12),color:makeBlendComponent(bsPtr+0)}}function makeColorState(csPtr){var format=WebGPU.TextureFormat[HEAP32[csPtr+4>>2]];return format?{format,blend:makeBlendState(HEAPU32[csPtr+8>>2]),writeMask:HEAPU32[csPtr+16>>2]}:undefined}function makeColorStates(count,csArrayPtr){var states=[];for(var i=0;i<count;++i){states.push(makeColorState(csArrayPtr+24*i))}return states}function makeStencilStateFace(ssfPtr){return{compare:WebGPU.CompareFunction[HEAP32[ssfPtr>>2]],failOp:WebGPU.StencilOperation[HEAP32[ssfPtr+4>>2]],depthFailOp:WebGPU.StencilOperation[HEAP32[ssfPtr+8>>2]],passOp:WebGPU.StencilOperation[HEAP32[ssfPtr+12>>2]]}}function makeDepthStencilState(dssPtr){if(!dssPtr)return undefined;return{format:WebGPU.TextureFormat[HEAP32[dssPtr+4>>2]],depthWriteEnabled:!!HEAPU32[dssPtr+8>>2],depthCompare:WebGPU.CompareFunction[HEAP32[dssPtr+12>>2]],stencilFront:makeStencilStateFace(dssPtr+16),stencilBack:makeStencilStateFace(dssPtr+32),stencilReadMask:HEAPU32[dssPtr+48>>2],stencilWriteMask:HEAPU32[dssPtr+52>>2],depthBias:HEAP32[dssPtr+56>>2],depthBiasSlopeScale:HEAPF32[dssPtr+60>>2],depthBiasClamp:HEAPF32[dssPtr+64>>2]}}function makeVertexAttribute(vaPtr){return{format:WebGPU.VertexFormat[HEAP32[vaPtr+4>>2]],offset:readI53FromI64(vaPtr+8),shaderLocation:HEAPU32[vaPtr+16>>2]}}function makeVertexAttributes(count,vaArrayPtr){var vas=[];for(var i=0;i<count;++i){vas.push(makeVertexAttribute(vaArrayPtr+i*24))}return vas}function makeVertexBuffer(vbPtr){if(!vbPtr)return undefined;var stepMode=WebGPU.VertexStepMode[HEAP32[vbPtr+4>>2]];var attributeCount=HEAPU32[vbPtr+16>>2];if(!stepMode&&!attributeCount){return null}return{arrayStride:readI53FromI64(vbPtr+8),stepMode,attributes:makeVertexAttributes(attributeCount,HEAPU32[vbPtr+20>>2])}}function makeVertexBuffers(count,vbArrayPtr){if(!count)return undefined;var vbs=[];for(var i=0;i<count;++i){vbs.push(makeVertexBuffer(vbArrayPtr+i*24))}return vbs}function makeVertexState(viPtr){if(!viPtr)return undefined;var desc={module:WebGPU.getJsObject(HEAPU32[viPtr+4>>2]),constants:WebGPU.makePipelineConstants(HEAPU32[viPtr+16>>2],HEAPU32[viPtr+20>>2]),buffers:makeVertexBuffers(HEAPU32[viPtr+24>>2],HEAPU32[viPtr+28>>2]),entryPoint:WebGPU.makeStringFromOptionalStringView(viPtr+8)};return desc}function makeMultisampleState(msPtr){if(!msPtr)return undefined;return{count:HEAPU32[msPtr+4>>2],mask:HEAPU32[msPtr+8>>2],alphaToCoverageEnabled:!!HEAPU32[msPtr+12>>2]}}function makeFragmentState(fsPtr){if(!fsPtr)return undefined;var desc={module:WebGPU.getJsObject(HEAPU32[fsPtr+4>>2]),constants:WebGPU.makePipelineConstants(HEAPU32[fsPtr+16>>2],HEAPU32[fsPtr+20>>2]),targets:makeColorStates(HEAPU32[fsPtr+24>>2],HEAPU32[fsPtr+28>>2]),entryPoint:WebGPU.makeStringFromOptionalStringView(fsPtr+8)};return desc}var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),layout:WebGPU.makePipelineLayout(HEAPU32[descriptor+12>>2]),vertex:makeVertexState(descriptor+16),primitive:makePrimitiveState(descriptor+48),depthStencil:makeDepthStencilState(HEAPU32[descriptor+72>>2]),multisample:makeMultisampleState(descriptor+76),fragment:makeFragmentState(HEAPU32[descriptor+92>>2])};return desc},fillLimitStruct:(limits,limitsOutPtr)=>{function setLimitValueU32(name,limitOffset){var limitValue=limits[name];HEAPU32[limitsOutPtr+limitOffset>>2]=limitValue}function setLimitValueU64(name,limitOffset){var limitValue=limits[name];writeI53ToI64(limitsOutPtr+limitOffset,limitValue)}setLimitValueU32("maxTextureDimension1D",4);setLimitValueU32("maxTextureDimension2D",8);setLimitValueU32("maxTextureDimension3D",12);setLimitValueU32("maxTextureArrayLayers",16);setLimitValueU32("maxBindGroups",20);setLimitValueU32("maxBindGroupsPlusVertexBuffers",24);setLimitValueU32("maxBindingsPerBindGroup",28);setLimitValueU32("maxDynamicUniformBuffersPerPipelineLayout",32);setLimitValueU32("maxDynamicStorageBuffersPerPipelineLayout",36);setLimitValueU32("maxSampledTexturesPerShaderStage",40);setLimitValueU32("maxSamplersPerShaderStage",44);setLimitValueU32("maxStorageBuffersPerShaderStage",48);setLimitValueU32("maxStorageTexturesPerShaderStage",52);setLimitValueU32("maxUniformBuffersPerShaderStage",56);setLimitValueU32("minUniformBufferOffsetAlignment",80);setLimitValueU32("minStorageBufferOffsetAlignment",84);setLimitValueU64("maxUniformBufferBindingSize",64);setLimitValueU64("maxStorageBufferBindingSize",72);setLimitValueU32("maxVertexBuffers",88);setLimitValueU64("maxBufferSize",96);setLimitValueU32("maxVertexAttributes",104);setLimitValueU32("maxVertexBufferArrayStride",108);setLimitValueU32("maxInterStageShaderVariables",112);setLimitValueU32("maxColorAttachments",116);setLimitValueU32("maxColorAttachmentBytesPerSample",120);setLimitValueU32("maxComputeWorkgroupStorageSize",124);setLimitValueU32("maxComputeInvocationsPerWorkgroup",128);setLimitValueU32("maxComputeWorkgroupSizeX",132);setLimitValueU32("maxComputeWorkgroupSizeY",136);setLimitValueU32("maxComputeWorkgroupSizeZ",140);setLimitValueU32("maxComputeWorkgroupsPerDimension",144);if(limits.maxImmediateSize!==undefined){setLimitValueU32("maxImmediateSize",148)}},fillAdapterInfoStruct:(info,infoStruct)=>{HEAPU32[infoStruct+52>>2]=info.subgroupMinSize;HEAPU32[infoStruct+56>>2]=info.subgroupMaxSize;var strs=info.vendor+info.architecture+info.device+info.description;var strPtr=stringToNewUTF8(strs);var vendorLen=lengthBytesUTF8(info.vendor);WebGPU.setStringView(infoStruct+4,strPtr,vendorLen);strPtr+=vendorLen;var architectureLen=lengthBytesUTF8(info.architecture);WebGPU.setStringView(infoStruct+12,strPtr,architectureLen);strPtr+=architectureLen;var deviceLen=lengthBytesUTF8(info.device);WebGPU.setStringView(infoStruct+20,strPtr,deviceLen);strPtr+=deviceLen;var descriptionLen=lengthBytesUTF8(info.description);WebGPU.setStringView(infoStruct+28,strPtr,descriptionLen);strPtr+=descriptionLen;HEAP32[infoStruct+36>>2]=2;var adapterType=info.isFallbackAdapter?3:4;HEAP32[infoStruct+40>>2]=adapterType;HEAPU32[infoStruct+44>>2]=0;HEAPU32[infoStruct+48>>2]=0},AddressMode:[,"clamp-to-edge","repeat","mirror-repeat"],BlendFactor:[,"zero","one","src","one-minus-src","src-alpha","one-minus-src-alpha","dst","one-minus-dst","dst-alpha","one-minus-dst-alpha","src-alpha-saturated","constant","one-minus-constant","src1","one-minus-src1","src1alpha","one-minus-src1alpha"],BlendOperation:[,"add","subtract","reverse-subtract","min","max"],BufferBindingType:[,,"uniform","storage","read-only-storage"],BufferMapState:[,"unmapped","pending","mapped"],CompareFunction:[,"never","less","equal","less-equal","greater","not-equal","greater-equal","always"],CompilationInfoRequestStatus:[,"success","callback-cancelled"],ComponentSwizzle:[,"0","1","r","g","b","a"],CompositeAlphaMode:[,"opaque","premultiplied","unpremultiplied","inherit"],CullMode:[,"none","front","back"],ErrorFilter:[,"validation","out-of-memory","internal"],FeatureLevel:[,"compatibility","core"],FeatureName:{1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},FilterMode:[,"nearest","linear"],FrontFace:[,"ccw","cw"],IndexFormat:[,"uint16","uint32"],InstanceFeatureName:[,"timed-wait-any","shader-source-spirv","multiple-devices-per-adapter"],LoadOp:[,"load","clear"],MipmapFilterMode:[,"nearest","linear"],OptionalBool:["false","true"],PowerPreference:[,"low-power","high-performance"],PredefinedColorSpace:[,"srgb","display-p3"],PrimitiveTopology:[,"point-list","line-list","line-strip","triangle-list","triangle-strip"],QueryType:[,"occlusion","timestamp"],SamplerBindingType:[,,"filtering","non-filtering","comparison"],Status:[,"success","error"],StencilOperation:[,"keep","zero","replace","invert","increment-clamp","decrement-clamp","increment-wrap","decrement-wrap"],StorageTextureAccess:[,,"write-only","read-only","read-write"],StoreOp:[,"store","discard"],SurfaceGetCurrentTextureStatus:[,"success-optimal","success-suboptimal","timeout","outdated","lost","error"],TextureAspect:[,"all","stencil-only","depth-only"],TextureDimension:[,"1d","2d","3d"],TextureFormat:[,"r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat","rg32float","rg32uint","rg32sint","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],TextureSampleType:[,,"float","unfilterable-float","depth","sint","uint"],TextureViewDimension:[,"1d","2d","2d-array","cube","cube-array","3d"],ToneMappingMode:[,"standard","extended"],VertexFormat:[,"uint8","uint8x2","uint8x4","sint8","sint8x2","sint8x4","unorm8","unorm8x2","unorm8x4","snorm8","snorm8x2","snorm8x4","uint16","uint16x2","uint16x4","sint16","sint16x2","sint16x4","unorm16","unorm16x2","unorm16x4","snorm16","snorm16x2","snorm16x4","float16","float16x2","float16x4","float32","float32x2","float32x3","float32x4","uint32","uint32x2","uint32x3","uint32x4","sint32","sint32x2","sint32x3","sint32x4","unorm10-10-10-2","unorm8x4-bgra"],VertexStepMode:[,"vertex","instance"],WGSLLanguageFeatureName:[,"readonly_and_readwrite_storage_textures","packed_4x8_integer_dot_product","unrestricted_pointer_parameters","pointer_composite_access","uniform_buffer_standard_layout","subgroup_id"]};var _emscripten_webgpu_get_device=()=>{if(WebGPU.preinitializedDeviceId===undefined){WebGPU.preinitializedDeviceId=WebGPU.importJsDevice(Module["preinitializedWebGPUDevice"]);_wgpuDeviceAddRef(WebGPU.preinitializedDeviceId)}_wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);return WebGPU.preinitializedDeviceId};var _emwgpuBufferDestroy=bufferPtr=>{var buffer=WebGPU.getJsObject(bufferPtr);var onUnmap=WebGPU.Internals.bufferOnUnmaps[bufferPtr];if(onUnmap){for(var i=0;i<onUnmap.length;++i){onUnmap[i]()}delete WebGPU.Internals.bufferOnUnmaps[bufferPtr]}buffer.destroy()};var _emwgpuBufferGetMappedRange=(bufferPtr,offset,size)=>{var buffer=WebGPU.getJsObject(bufferPtr);if(size==-1)size=undefined;var mapped;try{mapped=buffer.getMappedRange(offset,size)}catch(ex){return 0}var data=_memalign(16,mapped.byteLength);HEAPU8.fill(0,data,mapped.byteLength);WebGPU.Internals.bufferOnUnmaps[bufferPtr].push(()=>{new Uint8Array(mapped).set(HEAPU8.subarray(data,data+mapped.byteLength));_free(data)});return data};var _emwgpuBufferUnmap=bufferPtr=>{var buffer=WebGPU.getJsObject(bufferPtr);var onUnmap=WebGPU.Internals.bufferOnUnmaps[bufferPtr];if(!onUnmap){return}for(var i=0;i<onUnmap.length;++i){onUnmap[i]()}delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];buffer.unmap()};var _emwgpuDelete=ptr=>{delete WebGPU.Internals.jsObjects[ptr]};var _emwgpuDeviceCreateBuffer=(devicePtr,descriptor,bufferPtr)=>{var mappedAtCreation=!!HEAPU32[descriptor+32>>2];var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),usage:HEAPU32[descriptor+16>>2],size:readI53FromI64(descriptor+24),mappedAtCreation};var device=WebGPU.getJsObject(devicePtr);var buffer;try{buffer=device.createBuffer(desc)}catch(ex){return false}WebGPU.Internals.jsObjectInsert(bufferPtr,buffer);if(mappedAtCreation){WebGPU.Internals.bufferOnUnmaps[bufferPtr]=[]}return true};var _emwgpuDeviceCreateComputePipelineAsync=function(devicePtr,futureId_low,futureId_high,descriptor,pipelinePtr){var futureId=convertI32PairToI53Checked(futureId_low,futureId_high);var desc=WebGPU.makeComputePipelineDesc(descriptor);var device=WebGPU.getJsObject(devicePtr);WebGPU.Internals.futureInsert(futureId,device.createComputePipelineAsync(desc).then(pipeline=>{callUserCallback(()=>{WebGPU.Internals.jsObjectInsert(pipelinePtr,pipeline);_emwgpuOnCreateComputePipelineCompleted(futureId,1,pipelinePtr,0)})},pipelineError=>{callUserCallback(()=>{var sp=stackSave();var messagePtr=stringToUTF8OnStack(pipelineError.message);var status=pipelineError.reason==="validation"?3:pipelineError.reason==="internal"?4:0;_emwgpuOnCreateComputePipelineCompleted(futureId,status,pipelinePtr,messagePtr);stackRestore(sp)})}))};var _emwgpuDeviceCreateRenderPipelineAsync=function(devicePtr,futureId_low,futureId_high,descriptor,pipelinePtr){var futureId=convertI32PairToI53Checked(futureId_low,futureId_high);var desc=WebGPU.makeRenderPipelineDesc(descriptor);var device=WebGPU.getJsObject(devicePtr);WebGPU.Internals.futureInsert(futureId,device.createRenderPipelineAsync(desc).then(pipeline=>{callUserCallback(()=>{WebGPU.Internals.jsObjectInsert(pipelinePtr,pipeline);_emwgpuOnCreateRenderPipelineCompleted(futureId,1,pipelinePtr,0)})},pipelineError=>{callUserCallback(()=>{var sp=stackSave();var messagePtr=stringToUTF8OnStack(pipelineError.message);var status=pipelineError.reason==="validation"?3:pipelineError.reason==="internal"?4:0;_emwgpuOnCreateRenderPipelineCompleted(futureId,status,pipelinePtr,messagePtr);stackRestore(sp)})}))};var _emwgpuDeviceCreateShaderModule=(devicePtr,descriptor,shaderModulePtr)=>{var nextInChainPtr=HEAPU32[descriptor>>2];var sType=HEAP32[nextInChainPtr+4>>2];var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),code:""};switch(sType){case 2:{desc["code"]=WebGPU.makeStringFromStringView(nextInChainPtr+8);break}}var device=WebGPU.getJsObject(devicePtr);WebGPU.Internals.jsObjectInsert(shaderModulePtr,device.createShaderModule(desc))};var _emwgpuDeviceDestroy=devicePtr=>{const device=WebGPU.getJsObject(devicePtr);device.onuncapturederror=null;device.destroy()};var _emwgpuWaitAny=(futurePtr,futureCount,timeoutMSPtr)=>{abort("TODO: Implement asyncify-free WaitAny for timeout=0")};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.language||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _emscripten_glActiveTexture=x0=>GLctx.activeTexture(x0);var _glActiveTexture=_emscripten_glActiveTexture;var _emscripten_glAttachShader=(program,shader)=>{GLctx.attachShader(GL.programs[program],GL.shaders[shader])};var _glAttachShader=_emscripten_glAttachShader;var _emscripten_glBindAttribLocation=(program,index,name)=>{GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))};var _glBindAttribLocation=_emscripten_glBindAttribLocation;var _emscripten_glBindBuffer=(target,buffer)=>{if(buffer&&!GL.buffers[buffer]){var b=GLctx.createBuffer();b.name=buffer;GL.buffers[buffer]=b}if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])};var _glBindBuffer=_emscripten_glBindBuffer;var _emscripten_glBindBufferBase=(target,index,buffer)=>{GLctx.bindBufferBase(target,index,GL.buffers[buffer])};var _glBindBufferBase=_emscripten_glBindBufferBase;var _emscripten_glBindFramebuffer=(target,framebuffer)=>{GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])};var _glBindFramebuffer=_emscripten_glBindFramebuffer;var _emscripten_glBindTexture=(target,texture)=>{GLctx.bindTexture(target,GL.textures[texture])};var _glBindTexture=_emscripten_glBindTexture;var _emscripten_glBindVertexArray=vao=>{GLctx.bindVertexArray(GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0};var _glBindVertexArray=_emscripten_glBindVertexArray;var _emscripten_glBlendEquation=x0=>GLctx.blendEquation(x0);var _glBlendEquation=_emscripten_glBlendEquation;var _emscripten_glBlendFunc=(x0,x1)=>GLctx.blendFunc(x0,x1);var _glBlendFunc=_emscripten_glBlendFunc;var _emscripten_glBufferData=(target,size,data,usage)=>{if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}return}GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)};var _glBufferData=_emscripten_glBufferData;var _emscripten_glClear=x0=>GLctx.clear(x0);var _glClear=_emscripten_glClear;var _emscripten_glClearColor=(x0,x1,x2,x3)=>GLctx.clearColor(x0,x1,x2,x3);var _glClearColor=_emscripten_glClearColor;var convertI32PairToI53=(lo,hi)=>(lo>>>0)+hi*4294967296;var _emscripten_glClientWaitSync=(sync,flags,timeout_low,timeout_high)=>{var timeout=convertI32PairToI53(timeout_low,timeout_high);return GLctx.clientWaitSync(GL.syncs[sync],flags,timeout)};var _glClientWaitSync=_emscripten_glClientWaitSync;var _emscripten_glColorMask=(red,green,blue,alpha)=>{GLctx.colorMask(!!red,!!green,!!blue,!!alpha)};var _glColorMask=_emscripten_glColorMask;var _emscripten_glCompileShader=shader=>{GLctx.compileShader(GL.shaders[shader])};var _glCompileShader=_emscripten_glCompileShader;var _emscripten_glCreateProgram=()=>{var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id};var _glCreateProgram=_emscripten_glCreateProgram;var _emscripten_glCreateShader=shaderType=>{var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id};var _glCreateShader=_emscripten_glCreateShader;var _emscripten_glDeleteBuffers=(n,buffers)=>{for(var i=0;i<n;i++){var id=HEAP32[buffers+i*4>>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}};var _glDeleteBuffers=_emscripten_glDeleteBuffers;var _emscripten_glDeleteFramebuffers=(n,framebuffers)=>{for(var i=0;i<n;++i){var id=HEAP32[framebuffers+i*4>>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}};var _glDeleteFramebuffers=_emscripten_glDeleteFramebuffers;var _emscripten_glDeleteProgram=id=>{if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null};var _glDeleteProgram=_emscripten_glDeleteProgram;var _emscripten_glDeleteShader=id=>{if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null};var _glDeleteShader=_emscripten_glDeleteShader;var _emscripten_glDeleteSync=id=>{if(!id)return;var sync=GL.syncs[id];if(!sync){GL.recordError(1281);return}GLctx.deleteSync(sync);sync.name=0;GL.syncs[id]=null};var _glDeleteSync=_emscripten_glDeleteSync;var _emscripten_glDeleteTextures=(n,textures)=>{for(var i=0;i<n;i++){var id=HEAP32[textures+i*4>>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}};var _glDeleteTextures=_emscripten_glDeleteTextures;var _emscripten_glDeleteVertexArrays=(n,vaos)=>{for(var i=0;i<n;i++){var id=HEAP32[vaos+i*4>>2];GLctx.deleteVertexArray(GL.vaos[id]);GL.vaos[id]=null}};var _glDeleteVertexArrays=_emscripten_glDeleteVertexArrays;var _emscripten_glDetachShader=(program,shader)=>{GLctx.detachShader(GL.programs[program],GL.shaders[shader])};var _glDetachShader=_emscripten_glDetachShader;var _emscripten_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDisableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=false;GLctx.disableVertexAttribArray(index)};var _glDisableVertexAttribArray=_emscripten_glDisableVertexAttribArray;var _emscripten_glDrawArrays=(mode,first,count)=>{GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()};var _glDrawArrays=_emscripten_glDrawArrays;var tempFixedLengthArray=[];var _emscripten_glDrawBuffers=(n,bufs)=>{var bufArray=tempFixedLengthArray[n];for(var i=0;i<n;i++){bufArray[i]=HEAP32[bufs+i*4>>2]}GLctx.drawBuffers(bufArray)};var _glDrawBuffers=_emscripten_glDrawBuffers;var _emscripten_glEnable=x0=>GLctx.enable(x0);var _glEnable=_emscripten_glEnable;var _emscripten_glEnableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)};var _glEnableVertexAttribArray=_emscripten_glEnableVertexAttribArray;var _emscripten_glFenceSync=(condition,flags)=>{var sync=GLctx.fenceSync(condition,flags);if(sync){var id=GL.getNewId(GL.syncs);sync.name=id;GL.syncs[id]=sync;return id}return 0};var _glFenceSync=_emscripten_glFenceSync;var _emscripten_glFinish=()=>GLctx.finish();var _glFinish=_emscripten_glFinish;var _emscripten_glFlush=()=>GLctx.flush();var _glFlush=_emscripten_glFlush;var _emscripten_glFramebufferTexture2D=(target,attachment,textarget,texture,level)=>{GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)};var _glFramebufferTexture2D=_emscripten_glFramebufferTexture2D;var _emscripten_glFramebufferTextureLayer=(target,attachment,texture,level,layer)=>{GLctx.framebufferTextureLayer(target,attachment,GL.textures[texture],level,layer)};var _glFramebufferTextureLayer=_emscripten_glFramebufferTextureLayer;var _emscripten_glGenBuffers=(n,buffers)=>{GL.genObject(n,buffers,"createBuffer",GL.buffers)};var _glGenBuffers=_emscripten_glGenBuffers;var _emscripten_glGenFramebuffers=(n,ids)=>{GL.genObject(n,ids,"createFramebuffer",GL.framebuffers)};var _glGenFramebuffers=_emscripten_glGenFramebuffers;var _emscripten_glGenTextures=(n,textures)=>{GL.genObject(n,textures,"createTexture",GL.textures)};var _glGenTextures=_emscripten_glGenTextures;var _emscripten_glGenVertexArrays=(n,arrays)=>{GL.genObject(n,arrays,"createVertexArray",GL.vaos)};var _glGenVertexArrays=_emscripten_glGenVertexArrays;var _emscripten_glGetAttribLocation=(program,name)=>GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name));var _glGetAttribLocation=_emscripten_glGetAttribLocation;var _emscripten_glGetError=()=>{var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error};var _glGetError=_emscripten_glGetError;var webglGetExtensions=()=>{var exts=getEmscriptenSupportedExtensions(GLctx);exts=exts.concat(exts.map(e=>"GL_"+e));return exts};var emscriptenWebGLGet=(name_,p,type)=>{if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}ret=webglGetExtensions().length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i<result.length;++i){switch(type){case 0:HEAP32[p+i*4>>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);return}}break;default:GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof result}!`);return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p]=ret?1:0;break}};var _emscripten_glGetFloatv=(name_,p)=>emscriptenWebGLGet(name_,p,2);var _glGetFloatv=_emscripten_glGetFloatv;var _emscripten_glGetIntegerv=(name_,p)=>emscriptenWebGLGet(name_,p,0);var _glGetIntegerv=_emscripten_glGetIntegerv;var _emscripten_glGetProgramiv=(program,pname,p)=>{if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(var i=0;i<numActiveUniforms;++i){program.maxUniformLength=Math.max(program.maxUniformLength,GLctx.getActiveUniform(program,i).name.length+1)}}HEAP32[p>>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){var numActiveAttributes=GLctx.getProgramParameter(program,35721);for(var i=0;i<numActiveAttributes;++i){program.maxAttributeLength=Math.max(program.maxAttributeLength,GLctx.getActiveAttrib(program,i).name.length+1)}}HEAP32[p>>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){var numActiveUniformBlocks=GLctx.getProgramParameter(program,35382);for(var i=0;i<numActiveUniformBlocks;++i){program.maxUniformBlockNameLength=Math.max(program.maxUniformBlockNameLength,GLctx.getActiveUniformBlockName(program,i).length+1)}}HEAP32[p>>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}};var _glGetProgramiv=_emscripten_glGetProgramiv;var _emscripten_glGetShaderInfoLog=(shader,maxLength,length,infoLog)=>{var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetShaderInfoLog=_emscripten_glGetShaderInfoLog;var _emscripten_glGetShaderiv=(shader,pname,p)=>{if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}};var _glGetShaderiv=_emscripten_glGetShaderiv;var _emscripten_glGetString=name_=>{var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:ret=stringToNewUTF8(webglGetExtensions().join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s?stringToNewUTF8(s):0;break;case 7938:var webGLVersion=GLctx.getParameter(7938);var glVersion=`OpenGL ES 2.0 (${webGLVersion})`;if(GL.currentContext.version>=2)glVersion=`OpenGL ES 3.0 (${webGLVersion})`;ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion=`OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret};var _glGetString=_emscripten_glGetString;var _emscripten_glGetUniformBlockIndex=(program,uniformBlockName)=>GLctx.getUniformBlockIndex(GL.programs[program],UTF8ToString(uniformBlockName));var _glGetUniformBlockIndex=_emscripten_glGetUniformBlockIndex;var jstoi_q=str=>parseInt(str);var webglGetLeftBracePos=name=>name.slice(-1)=="]"&&name.lastIndexOf("[");var webglPrepareUniformLocationsBeforeFirstUse=program=>{var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(i=0;i<numActiveUniforms;++i){var u=GLctx.getActiveUniform(program,i);var nm=u.name;var sz=u.size;var lb=webglGetLeftBracePos(nm);var arrayName=lb>0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j<sz;++j){uniformLocsById[id]=j;program.uniformArrayNamesById[id++]=arrayName}}}};var _emscripten_glGetUniformLocation=(program,name)=>{name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex<sizeAndId[0]){arrayIndex+=sizeAndId[1];if(uniformLocsById[arrayIndex]=uniformLocsById[arrayIndex]||GLctx.getUniformLocation(program,name)){return arrayIndex}}}else{GL.recordError(1281)}return-1};var _glGetUniformLocation=_emscripten_glGetUniformLocation;var _emscripten_glLineWidth=x0=>GLctx.lineWidth(x0);var _glLineWidth=_emscripten_glLineWidth;var _emscripten_glLinkProgram=program=>{program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}};var _glLinkProgram=_emscripten_glLinkProgram;var _emscripten_glPixelStorei=(pname,param)=>{if(pname==3317){GL.unpackAlignment=param}else if(pname==3314){GL.unpackRowLength=param}GLctx.pixelStorei(pname,param)};var _glPixelStorei=_emscripten_glPixelStorei;var computeUnpackAlignedImageSize=(width,height,sizePerPixel)=>{function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=(GL.unpackRowLength||width)*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,GL.unpackAlignment);return height*alignedRowSize};var colorChannelsInGlTextureFormat=format=>{var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1};var heapObjectForWebGLType=type=>{type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16};var toTypedArrayIndex=(pointer,heap)=>pointer>>>31-Math.clz32(heap.BYTES_PER_ELEMENT);var emscriptenWebGLGetTexPixelData=(type,format,width,height,pixels,internalFormat)=>{var heap=heapObjectForWebGLType(type);var sizePerPixel=colorChannelsInGlTextureFormat(format)*heap.BYTES_PER_ELEMENT;var bytes=computeUnpackAlignedImageSize(width,height,sizePerPixel);return heap.subarray(toTypedArrayIndex(pixels,heap),toTypedArrayIndex(pixels+bytes,heap))};var _emscripten_glReadPixels=(x,y,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelPackBufferBinding){GLctx.readPixels(x,y,width,height,format,type,pixels);return}var heap=heapObjectForWebGLType(type);var target=toTypedArrayIndex(pixels,heap);GLctx.readPixels(x,y,width,height,format,type,heap,target);return}var pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,format);if(!pixelData){GL.recordError(1280);return}GLctx.readPixels(x,y,width,height,format,type,pixelData)};var _glReadPixels=_emscripten_glReadPixels;var _emscripten_glShaderSource=(shader,count,string,length)=>{var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)};var _glShaderSource=_emscripten_glShaderSource;var _emscripten_glTexImage2D=(target,level,internalFormat,width,height,border,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);var index=toTypedArrayIndex(pixels,heap);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,index);return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null;GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixelData)};var _glTexImage2D=_emscripten_glTexImage2D;var _emscripten_glTexParameterf=(x0,x1,x2)=>GLctx.texParameterf(x0,x1,x2);var _glTexParameterf=_emscripten_glTexParameterf;var _emscripten_glTexParameterfv=(target,pname,params)=>{var param=HEAPF32[params>>2];GLctx.texParameterf(target,pname,param)};var _glTexParameterfv=_emscripten_glTexParameterfv;var _emscripten_glTexParameteri=(x0,x1,x2)=>GLctx.texParameteri(x0,x1,x2);var _glTexParameteri=_emscripten_glTexParameteri;var _emscripten_glTexStorage2D=(x0,x1,x2,x3,x4)=>GLctx.texStorage2D(x0,x1,x2,x3,x4);var _glTexStorage2D=_emscripten_glTexStorage2D;var _emscripten_glTexStorage3D=(x0,x1,x2,x3,x4,x5)=>GLctx.texStorage3D(x0,x1,x2,x3,x4,x5);var _glTexStorage3D=_emscripten_glTexStorage3D;var _emscripten_glTexSubImage2D=(target,level,xoffset,yoffset,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,toTypedArrayIndex(pixels,heap));return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0):null;GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)};var _glTexSubImage2D=_emscripten_glTexSubImage2D;var _emscripten_glTexSubImage3D=(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels)=>{if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,heap,toTypedArrayIndex(pixels,heap))}else{GLctx.texSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,null)}};var _glTexSubImage3D=_emscripten_glTexSubImage3D;var webglGetUniformLocation=location=>{var p=GLctx.currentProgram;if(p){var webglLoc=p.uniformLocsById[location];if(typeof webglLoc=="number"){p.uniformLocsById[location]=webglLoc=GLctx.getUniformLocation(p,p.uniformArrayNamesById[location]+(webglLoc>0?`[${webglLoc}]`:""))}return webglLoc}else{GL.recordError(1282)}};var _emscripten_glUniform1f=(location,v0)=>{GLctx.uniform1f(webglGetUniformLocation(location),v0)};var _glUniform1f=_emscripten_glUniform1f;var miniTempWebGLFloatBuffers=[];var _emscripten_glUniform1fv=(location,count,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniform1fv(webglGetUniformLocation(location),HEAPF32,value>>2,count);return}if(count<=288){var view=miniTempWebGLFloatBuffers[count];for(var i=0;i<count;++i){view[i]=HEAPF32[value+4*i>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*4>>2)}GLctx.uniform1fv(webglGetUniformLocation(location),view)};var _glUniform1fv=_emscripten_glUniform1fv;var _emscripten_glUniform1i=(location,v0)=>{GLctx.uniform1i(webglGetUniformLocation(location),v0)};var _glUniform1i=_emscripten_glUniform1i;var _emscripten_glUniform2f=(location,v0,v1)=>{GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)};var _glUniform2f=_emscripten_glUniform2f;var _emscripten_glUniform2fv=(location,count,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniform2fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*2);return}if(count<=144){count*=2;var view=miniTempWebGLFloatBuffers[count];for(var i=0;i<count;i+=2){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*8>>2)}GLctx.uniform2fv(webglGetUniformLocation(location),view)};var _glUniform2fv=_emscripten_glUniform2fv;var _emscripten_glUniform3f=(location,v0,v1,v2)=>{GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)};var _glUniform3f=_emscripten_glUniform3f;var _emscripten_glUniform4f=(location,v0,v1,v2,v3)=>{GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)};var _glUniform4f=_emscripten_glUniform4f;var _emscripten_glUniform4fv=(location,count,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniform4fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*4);return}if(count<=72){var view=miniTempWebGLFloatBuffers[4*count];var heap=HEAPF32;value=value>>2;count*=4;for(var i=0;i<count;i+=4){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3]}}else{var view=HEAPF32.subarray(value>>2,value+count*16>>2)}GLctx.uniform4fv(webglGetUniformLocation(location),view)};var _glUniform4fv=_emscripten_glUniform4fv;var miniTempWebGLIntBuffers=[];var _emscripten_glUniform4iv=(location,count,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniform4iv(webglGetUniformLocation(location),HEAP32,value>>2,count*4);return}if(count<=72){count*=4;var view=miniTempWebGLIntBuffers[count];for(var i=0;i<count;i+=4){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2];view[i+2]=HEAP32[value+(4*i+8)>>2];view[i+3]=HEAP32[value+(4*i+12)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*16>>2)}GLctx.uniform4iv(webglGetUniformLocation(location),view)};var _glUniform4iv=_emscripten_glUniform4iv;var _emscripten_glUniformBlockBinding=(program,uniformBlockIndex,uniformBlockBinding)=>{program=GL.programs[program];GLctx.uniformBlockBinding(program,uniformBlockIndex,uniformBlockBinding)};var _glUniformBlockBinding=_emscripten_glUniformBlockBinding;var _emscripten_glUniformMatrix2fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix2fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*4);return}if(count<=72){count*=4;var view=miniTempWebGLFloatBuffers[count];for(var i=0;i<count;i+=4){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2];view[i+3]=HEAPF32[value+(4*i+12)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*16>>2)}GLctx.uniformMatrix2fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix2fv=_emscripten_glUniformMatrix2fv;var _emscripten_glUniformMatrix3fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*9);return}if(count<=32){count*=9;var view=miniTempWebGLFloatBuffers[count];for(var i=0;i<count;i+=9){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2];view[i+3]=HEAPF32[value+(4*i+12)>>2];view[i+4]=HEAPF32[value+(4*i+16)>>2];view[i+5]=HEAPF32[value+(4*i+20)>>2];view[i+6]=HEAPF32[value+(4*i+24)>>2];view[i+7]=HEAPF32[value+(4*i+28)>>2];view[i+8]=HEAPF32[value+(4*i+32)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*36>>2)}GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix3fv=_emscripten_glUniformMatrix3fv;var _emscripten_glUniformMatrix4fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count];var heap=HEAPF32;value=value>>2;count*=16;for(var i=0;i<count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix4fv=_emscripten_glUniformMatrix4fv;var _emscripten_glUseProgram=program=>{program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program};var _glUseProgram=_emscripten_glUseProgram;var _emscripten_glVertexAttribPointer=(index,size,type,normalized,stride,ptr)=>{var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)};var _glVertexAttribPointer=_emscripten_glVertexAttribPointer;var _emscripten_glViewport=(x0,x1,x2,x3)=>GLctx.viewport(x0,x1,x2,x3);var _glViewport=_emscripten_glViewport;function _mediapipe_find_canvas_event_target(canvasSelector){let target=findCanvasEventTarget(canvasSelector);if(Module&&!target){target=Module.canvasWebGpu}return Emval.toHandle(target)}function _mediapipe_webgl_tex_image_drawable(drawableHandle){const drawable=Emval.toValue(drawableHandle);GLctx.texImage2D(GLctx.TEXTURE_2D,0,GLctx.RGBA,GLctx.RGBA,GLctx.UNSIGNED_BYTE,drawable)}function _random_get(buffer,size){try{randomFill(HEAPU8.subarray(buffer,buffer+size));return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _wgpuCommandEncoderBeginComputePass=(encoderPtr,descriptor)=>{var desc;if(descriptor){desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),timestampWrites:WebGPU.makePassTimestampWrites(HEAPU32[descriptor+12>>2])}}var commandEncoder=WebGPU.getJsObject(encoderPtr);var ptr=_emwgpuCreateComputePassEncoder(0);WebGPU.Internals.jsObjectInsert(ptr,commandEncoder.beginComputePass(desc));return ptr};var _wgpuCommandEncoderBeginRenderPass=(encoderPtr,descriptor)=>{function makeColorAttachment(caPtr){var viewPtr=HEAPU32[caPtr+4>>2];if(viewPtr===0){return undefined}var depthSlice=HEAPU32[caPtr+8>>2];if(depthSlice==4294967295)depthSlice=undefined;return{view:WebGPU.getJsObject(viewPtr),depthSlice,resolveTarget:WebGPU.getJsObject(HEAPU32[caPtr+12>>2]),clearValue:WebGPU.makeColor(caPtr+24),loadOp:WebGPU.LoadOp[HEAP32[caPtr+16>>2]],storeOp:WebGPU.StoreOp[HEAP32[caPtr+20>>2]]}}function makeColorAttachments(count,caPtr){var attachments=[];for(var i=0;i<count;++i){attachments.push(makeColorAttachment(caPtr+56*i))}return attachments}function makeDepthStencilAttachment(dsaPtr){if(dsaPtr===0)return undefined;return{view:WebGPU.getJsObject(HEAPU32[dsaPtr+4>>2]),depthClearValue:HEAPF32[dsaPtr+16>>2],depthLoadOp:WebGPU.LoadOp[HEAP32[dsaPtr+8>>2]],depthStoreOp:WebGPU.StoreOp[HEAP32[dsaPtr+12>>2]],depthReadOnly:!!HEAPU32[dsaPtr+20>>2],stencilClearValue:HEAPU32[dsaPtr+32>>2],stencilLoadOp:WebGPU.LoadOp[HEAP32[dsaPtr+24>>2]],stencilStoreOp:WebGPU.StoreOp[HEAP32[dsaPtr+28>>2]],stencilReadOnly:!!HEAPU32[dsaPtr+36>>2]}}function makeRenderPassDescriptor(descriptor){var nextInChainPtr=HEAPU32[descriptor>>2];var maxDrawCount=undefined;if(nextInChainPtr!==0){var sType=HEAP32[nextInChainPtr+4>>2];var renderPassMaxDrawCount=nextInChainPtr;maxDrawCount=readI53FromI64(renderPassMaxDrawCount+8)}var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),colorAttachments:makeColorAttachments(HEAPU32[descriptor+12>>2],HEAPU32[descriptor+16>>2]),depthStencilAttachment:makeDepthStencilAttachment(HEAPU32[descriptor+20>>2]),occlusionQuerySet:WebGPU.getJsObject(HEAPU32[descriptor+24>>2]),timestampWrites:WebGPU.makePassTimestampWrites(HEAPU32[descriptor+28>>2]),maxDrawCount};return desc}var desc=makeRenderPassDescriptor(descriptor);var commandEncoder=WebGPU.getJsObject(encoderPtr);var ptr=_emwgpuCreateRenderPassEncoder(0);WebGPU.Internals.jsObjectInsert(ptr,commandEncoder.beginRenderPass(desc));return ptr};var _wgpuCommandEncoderCopyBufferToTexture=(encoderPtr,srcPtr,dstPtr,copySizePtr)=>{var commandEncoder=WebGPU.getJsObject(encoderPtr);var copySize=WebGPU.makeExtent3D(copySizePtr);commandEncoder.copyBufferToTexture(WebGPU.makeTexelCopyBufferInfo(srcPtr),WebGPU.makeTexelCopyTextureInfo(dstPtr),copySize)};var _wgpuCommandEncoderCopyTextureToBuffer=(encoderPtr,srcPtr,dstPtr,copySizePtr)=>{var commandEncoder=WebGPU.getJsObject(encoderPtr);var copySize=WebGPU.makeExtent3D(copySizePtr);commandEncoder.copyTextureToBuffer(WebGPU.makeTexelCopyTextureInfo(srcPtr),WebGPU.makeTexelCopyBufferInfo(dstPtr),copySize)};var _wgpuCommandEncoderCopyTextureToTexture=(encoderPtr,srcPtr,dstPtr,copySizePtr)=>{var commandEncoder=WebGPU.getJsObject(encoderPtr);var copySize=WebGPU.makeExtent3D(copySizePtr);commandEncoder.copyTextureToTexture(WebGPU.makeTexelCopyTextureInfo(srcPtr),WebGPU.makeTexelCopyTextureInfo(dstPtr),copySize)};var _wgpuCommandEncoderFinish=(encoderPtr,descriptor)=>{var commandEncoder=WebGPU.getJsObject(encoderPtr);var ptr=_emwgpuCreateCommandBuffer(0);WebGPU.Internals.jsObjectInsert(ptr,commandEncoder.finish());return ptr};var _wgpuComputePassEncoderDispatchWorkgroups=(passPtr,x,y,z)=>{var pass=WebGPU.getJsObject(passPtr);pass.dispatchWorkgroups(x,y,z)};var _wgpuComputePassEncoderEnd=passPtr=>{var pass=WebGPU.getJsObject(passPtr);pass.end()};var _wgpuComputePassEncoderSetBindGroup=(passPtr,groupIndex,groupPtr,dynamicOffsetCount,dynamicOffsetsPtr)=>{var pass=WebGPU.getJsObject(passPtr);var group=WebGPU.getJsObject(groupPtr);if(dynamicOffsetCount==0){pass.setBindGroup(groupIndex,group)}else{pass.setBindGroup(groupIndex,group,HEAPU32,dynamicOffsetsPtr>>2,dynamicOffsetCount)}};var _wgpuComputePassEncoderSetPipeline=(passPtr,pipelinePtr)=>{var pass=WebGPU.getJsObject(passPtr);var pipeline=WebGPU.getJsObject(pipelinePtr);pass.setPipeline(pipeline)};var _wgpuComputePipelineGetBindGroupLayout=(pipelinePtr,groupIndex)=>{var pipeline=WebGPU.getJsObject(pipelinePtr);var ptr=_emwgpuCreateBindGroupLayout(0);WebGPU.Internals.jsObjectInsert(ptr,pipeline.getBindGroupLayout(groupIndex));return ptr};var _wgpuDeviceCreateBindGroup=(devicePtr,descriptor)=>{function makeEntry(entryPtr){var bufferPtr=HEAPU32[entryPtr+8>>2];var samplerPtr=HEAPU32[entryPtr+32>>2];var textureViewPtr=HEAPU32[entryPtr+36>>2];var externalTexturePtr=0;WebGPU.iterateExtensions(entryPtr,{327681:ptr=>{externalTexturePtr=HEAPU32[ptr+8>>2]}});var resource;if(bufferPtr){var size=readI53FromI64(entryPtr+24);if(size==-1)size=undefined;resource={buffer:WebGPU.getJsObject(bufferPtr),offset:readI53FromI64(entryPtr+16),size}}else{resource=WebGPU.getJsObject(samplerPtr||textureViewPtr||externalTexturePtr)}return{binding:HEAPU32[entryPtr+4>>2],resource}}function makeEntries(count,entriesPtrs){var entries=[];for(var i=0;i<count;++i){entries.push(makeEntry(entriesPtrs+40*i))}return entries}var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),layout:WebGPU.getJsObject(HEAPU32[descriptor+12>>2]),entries:makeEntries(HEAPU32[descriptor+16>>2],HEAPU32[descriptor+20>>2])};var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreateBindGroup(0);WebGPU.Internals.jsObjectInsert(ptr,device.createBindGroup(desc));return ptr};var _wgpuDeviceCreateBindGroupLayout=(devicePtr,descriptor)=>{function makeBufferEntry(substructPtr){var typeInt=HEAPU32[substructPtr+4>>2];if(!typeInt)return undefined;return{type:WebGPU.BufferBindingType[typeInt],hasDynamicOffset:!!HEAPU32[substructPtr+8>>2],minBindingSize:readI53FromI64(substructPtr+16)}}function makeSamplerEntry(substructPtr){var typeInt=HEAPU32[substructPtr+4>>2];if(!typeInt)return undefined;return{type:WebGPU.SamplerBindingType[typeInt]}}function makeTextureEntry(substructPtr){var sampleTypeInt=HEAPU32[substructPtr+4>>2];if(!sampleTypeInt)return undefined;return{sampleType:WebGPU.TextureSampleType[sampleTypeInt],viewDimension:WebGPU.TextureViewDimension[HEAP32[substructPtr+8>>2]],multisampled:!!HEAPU32[substructPtr+12>>2]}}function makeStorageTextureEntry(substructPtr){var accessInt=HEAPU32[substructPtr+4>>2];if(!accessInt)return undefined;return{access:WebGPU.StorageTextureAccess[accessInt],format:WebGPU.TextureFormat[HEAP32[substructPtr+8>>2]],viewDimension:WebGPU.TextureViewDimension[HEAP32[substructPtr+12>>2]]}}function makeEntry(entryPtr){var entry={binding:HEAPU32[entryPtr+4>>2],visibility:HEAPU32[entryPtr+8>>2],buffer:makeBufferEntry(entryPtr+24),sampler:makeSamplerEntry(entryPtr+48),texture:makeTextureEntry(entryPtr+56),storageTexture:makeStorageTextureEntry(entryPtr+72)};WebGPU.iterateExtensions(entryPtr,{327682:ptr=>{entry["externalTexture"]={}}});return entry}function makeEntries(count,entriesPtrs){var entries=[];for(var i=0;i<count;++i){entries.push(makeEntry(entriesPtrs+88*i))}return entries}var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),entries:makeEntries(HEAPU32[descriptor+12>>2],HEAPU32[descriptor+16>>2])};var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreateBindGroupLayout(0);WebGPU.Internals.jsObjectInsert(ptr,device.createBindGroupLayout(desc));return ptr};var _wgpuDeviceCreateCommandEncoder=(devicePtr,descriptor)=>{var desc;if(descriptor){desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4)}}var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreateCommandEncoder(0);WebGPU.Internals.jsObjectInsert(ptr,device.createCommandEncoder(desc));return ptr};var _wgpuDeviceCreateComputePipeline=(devicePtr,descriptor)=>{var desc=WebGPU.makeComputePipelineDesc(descriptor);var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreateComputePipeline(0);WebGPU.Internals.jsObjectInsert(ptr,device.createComputePipeline(desc));return ptr};var _wgpuDeviceCreatePipelineLayout=(devicePtr,descriptor)=>{var bglCount=HEAPU32[descriptor+12>>2];var bglPtr=HEAPU32[descriptor+16>>2];var bgls=[];for(var i=0;i<bglCount;++i){bgls.push(WebGPU.getJsObject(HEAPU32[bglPtr+4*i>>2]))}var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),bindGroupLayouts:bgls};var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreatePipelineLayout(0);WebGPU.Internals.jsObjectInsert(ptr,device.createPipelineLayout(desc));return ptr};var _wgpuDeviceCreateRenderPipeline=(devicePtr,descriptor)=>{var desc=WebGPU.makeRenderPipelineDesc(descriptor);var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreateRenderPipeline(0);WebGPU.Internals.jsObjectInsert(ptr,device.createRenderPipeline(desc));return ptr};var _wgpuDeviceCreateSampler=(devicePtr,descriptor)=>{var desc;if(descriptor){desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),addressModeU:WebGPU.AddressMode[HEAP32[descriptor+12>>2]],addressModeV:WebGPU.AddressMode[HEAP32[descriptor+16>>2]],addressModeW:WebGPU.AddressMode[HEAP32[descriptor+20>>2]],magFilter:WebGPU.FilterMode[HEAP32[descriptor+24>>2]],minFilter:WebGPU.FilterMode[HEAP32[descriptor+28>>2]],mipmapFilter:WebGPU.MipmapFilterMode[HEAP32[descriptor+32>>2]],lodMinClamp:HEAPF32[descriptor+36>>2],lodMaxClamp:HEAPF32[descriptor+40>>2],compare:WebGPU.CompareFunction[HEAP32[descriptor+44>>2]],maxAnisotropy:HEAPU16[descriptor+48>>1]}}var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreateSampler(0);WebGPU.Internals.jsObjectInsert(ptr,device.createSampler(desc));return ptr};var _wgpuDeviceCreateTexture=(devicePtr,descriptor)=>{var desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),size:WebGPU.makeExtent3D(descriptor+28),mipLevelCount:HEAPU32[descriptor+44>>2],sampleCount:HEAPU32[descriptor+48>>2],dimension:WebGPU.TextureDimension[HEAP32[descriptor+24>>2]],format:WebGPU.TextureFormat[HEAP32[descriptor+40>>2]],usage:HEAPU32[descriptor+16>>2]};var viewFormatCount=HEAPU32[descriptor+52>>2];if(viewFormatCount){var viewFormatsPtr=HEAPU32[descriptor+56>>2];desc["viewFormats"]=Array.from(HEAP32.subarray(viewFormatsPtr>>2,viewFormatsPtr+viewFormatCount*4>>2),format=>WebGPU.TextureFormat[format])}var device=WebGPU.getJsObject(devicePtr);var ptr=_emwgpuCreateTexture(0);WebGPU.Internals.jsObjectInsert(ptr,device.createTexture(desc));return ptr};var _wgpuQueueSubmit=(queuePtr,commandCount,commands)=>{var queue=WebGPU.getJsObject(queuePtr);var cmds=Array.from(HEAP32.subarray(commands>>2,commands+commandCount*4>>2),id=>WebGPU.getJsObject(id));queue.submit(cmds)};function _wgpuQueueWriteBuffer(queuePtr,bufferPtr,bufferOffset_low,bufferOffset_high,data,size){var bufferOffset=convertI32PairToI53Checked(bufferOffset_low,bufferOffset_high);var queue=WebGPU.getJsObject(queuePtr);var buffer=WebGPU.getJsObject(bufferPtr);var subarray=HEAPU8.subarray(data,data+size);queue.writeBuffer(buffer,bufferOffset,subarray,0,size)}var _wgpuQueueWriteTexture=(queuePtr,destinationPtr,data,dataSize,dataLayoutPtr,writeSizePtr)=>{var queue=WebGPU.getJsObject(queuePtr);var destination=WebGPU.makeTexelCopyTextureInfo(destinationPtr);var dataLayout=WebGPU.makeTexelCopyBufferLayout(dataLayoutPtr);var writeSize=WebGPU.makeExtent3D(writeSizePtr);var subarray=HEAPU8.subarray(data,data+dataSize);queue.writeTexture(destination,subarray,dataLayout,writeSize)};var _wgpuRenderPassEncoderDraw=(passPtr,vertexCount,instanceCount,firstVertex,firstInstance)=>{firstVertex>>>=0;firstInstance>>>=0;var pass=WebGPU.getJsObject(passPtr);pass.draw(vertexCount,instanceCount,firstVertex,firstInstance)};var _wgpuRenderPassEncoderEnd=encoderPtr=>{var encoder=WebGPU.getJsObject(encoderPtr);encoder.end()};var _wgpuRenderPassEncoderSetBindGroup=(passPtr,groupIndex,groupPtr,dynamicOffsetCount,dynamicOffsetsPtr)=>{var pass=WebGPU.getJsObject(passPtr);var group=WebGPU.getJsObject(groupPtr);if(dynamicOffsetCount==0){pass.setBindGroup(groupIndex,group)}else{pass.setBindGroup(groupIndex,group,HEAPU32,dynamicOffsetsPtr>>2,dynamicOffsetCount)}};var _wgpuRenderPassEncoderSetPipeline=(passPtr,pipelinePtr)=>{var pass=WebGPU.getJsObject(passPtr);var pipeline=WebGPU.getJsObject(pipelinePtr);pass.setPipeline(pipeline)};var _wgpuRenderPipelineGetBindGroupLayout=(pipelinePtr,groupIndex)=>{var pipeline=WebGPU.getJsObject(pipelinePtr);var ptr=_emwgpuCreateBindGroupLayout(0);WebGPU.Internals.jsObjectInsert(ptr,pipeline.getBindGroupLayout(groupIndex));return ptr};var _wgpuTextureCreateView=(texturePtr,descriptor)=>{var desc;if(descriptor){var swizzle;var nextInChainPtr=HEAPU32[descriptor>>2];if(nextInChainPtr!==0){var sType=HEAP32[nextInChainPtr+4>>2];var swizzleDescriptor=nextInChainPtr;var swizzlePtr=swizzleDescriptor+8;var r=WebGPU.ComponentSwizzle[HEAP32[swizzlePtr>>2]]||"r";var g=WebGPU.ComponentSwizzle[HEAP32[swizzlePtr+4>>2]]||"g";var b=WebGPU.ComponentSwizzle[HEAP32[swizzlePtr+8>>2]]||"b";var a=WebGPU.ComponentSwizzle[HEAP32[swizzlePtr+12>>2]]||"a";swizzle=`${r}${g}${b}${a}`}var mipLevelCount=HEAPU32[descriptor+24>>2];var arrayLayerCount=HEAPU32[descriptor+32>>2];desc={label:WebGPU.makeStringFromOptionalStringView(descriptor+4),format:WebGPU.TextureFormat[HEAP32[descriptor+12>>2]],dimension:WebGPU.TextureViewDimension[HEAP32[descriptor+16>>2]],baseMipLevel:HEAPU32[descriptor+20>>2],mipLevelCount:mipLevelCount===4294967295?undefined:mipLevelCount,baseArrayLayer:HEAPU32[descriptor+28>>2],arrayLayerCount:arrayLayerCount===4294967295?undefined:arrayLayerCount,aspect:WebGPU.TextureAspect[HEAP32[descriptor+36>>2]],swizzle}}var texture=WebGPU.getJsObject(texturePtr);var ptr=_emwgpuCreateTextureView(0);WebGPU.Internals.jsObjectInsert(ptr,texture.createView(desc));return ptr};var _wgpuTextureDestroy=texturePtr=>{WebGPU.getJsObject(texturePtr).destroy()};var _wgpuTextureGetFormat=texturePtr=>{var texture=WebGPU.getJsObject(texturePtr);return WebGPU.TextureFormat.indexOf(texture.format)};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();registerPreMainLoop(()=>GL.newRenderingFrameStarted());for(let i=0;i<32;++i)tempFixedLengthArray.push(new Array(i));var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<=288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i)}var miniTempWebGLIntBuffersStorage=new Int32Array(288);for(var i=0;i<=288;++i){miniTempWebGLIntBuffers[i]=miniTempWebGLIntBuffersStorage.subarray(0,i)}{if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["stringToNewUTF8"]=stringToNewUTF8;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;var ASM_CONSTS={1486195:$0=>{const canvas=Emval.toValue($0);const context=canvas.getContext("webgpu");return WebGPU.importJsTexture(context.getCurrentTexture())},1486338:($0,$1,$2,$3,$4)=>{const drawable=Emval.toValue($0);const device=WebGPU.getJsObject($1);const texture=WebGPU.getJsObject($2);const width=$3;const height=$4;device.queue.copyExternalImageToTexture({source:drawable},{texture},[width,height])},1486597:($0,$1,$2,$3)=>{const sourceExtTex=Emval.toValue($0);const device=WebGPU.getJsObject($1);const sampler=WebGPU.getJsObject($2);const bgLayout=WebGPU.getJsObject($3);const bindGroup=device.createBindGroup({layout:bgLayout,entries:[{binding:0,resource:sampler},{binding:1,resource:sourceExtTex}]});return WebGPU.importJsBindGroup(bindGroup)},1486967:($0,$1)=>{const input=Emval.toValue($0);const output=Emval.toValue($1);const ctx=output.getContext("2d");ctx.drawImage(input,0,0,output.width,output.height)},1487132:($0,$1)=>{const inputArray=Emval.toValue($0);const output=Emval.toValue($1);const ctx=output.getContext("2d");const image_data=new ImageData(inputArray,output.width,output.height);ctx.putImageData(image_data,0,0)},1487356:($0,$1)=>{const input=Emval.toValue($0);const outputArray=Emval.toValue($1);const ctx=input.getContext("2d");const data=ctx.getImageData(0,0,input.width,input.height);outputArray.set(data.data)},1487560:()=>typeof HTMLCanvasElement!=="undefined",1487615:()=>!!Module["preinitializedWebGPUDevice"],1487666:()=>{specialHTMLTargets["#canvas"]=Module.canvas}};function BeginGlQueryTiming(calc_name,num_repetitions){const gl=Module.canvas.getContext("webgl2");const query=gl.createQuery();Module.WEBGL_SHADER_CALC_METRICS=Module.WEBGL_SHADER_CALC_METRICS||{};Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)]={query,repetitions:num_repetitions};Module.WEBGL_QUERY_TIMER_EXT=Module.WEBGL_QUERY_TIMER_EXT||gl.getExtension("EXT_disjoint_timer_query_webgl2");gl.beginQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT,query)}function EndGlQueryTiming(calc_name){const gl=Module.canvas.getContext("webgl2");gl.endQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT,Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)].query)}function JsWrapImageConverter(){if(!Module._imageConverter){Module._imageConverter=(binaryPtr,binarySize,width,height,numChannels,makeDeepCopy,outputType)=>{const imageData=new outputType(makeDeepCopy?Module.HEAPU8.slice(binaryPtr,binaryPtr+binarySize).buffer:Module.HEAPU8.buffer,binaryPtr,width*height*numChannels);return{data:imageData,width,height}}}}function JsOnUint8ArrayImageListener(output_stream_name,binary_ptr,binary_size,width,height,num_channels,make_deep_copy,timestamp_ms){const image=Module._imageConverter(binary_ptr,binary_size,width,height,num_channels,make_deep_copy,Uint8Array);Module._wrapSimpleListenerOutput(output_stream_name,image,timestamp_ms)}function JsOnFloat32ArrayImageListener(output_stream_name,binary_ptr,binary_size,width,height,num_channels,make_deep_copy,timestamp_ms){const image=Module._imageConverter(binary_ptr,binary_size,width,height,num_channels,make_deep_copy,Float32Array);Module._wrapSimpleListenerOutput(output_stream_name,image,timestamp_ms)}function JsOnWebGLTextureListener(output_stream_name,name,width,height,timestamp_ms){Module._wrapSimpleListenerOutput(output_stream_name,{data:GL.textures[name],width,height},timestamp_ms)}function JsOnUint8ArrayImageVectorListener(output_stream_name,binary_ptr,binary_size,width,height,num_channels,make_deep_copy,timestamp_ms){const image=Module._imageConverter(binary_ptr,binary_size,width,height,num_channels,make_deep_copy,Uint8Array);Module._wrapSimpleListenerOutput(output_stream_name,image,false,timestamp_ms)}function JsOnFloat32ArrayImageVectorListener(output_stream_name,binary_ptr,binary_size,width,height,num_channels,make_deep_copy,timestamp_ms){const image=Module._imageConverter(binary_ptr,binary_size,width,height,num_channels,make_deep_copy,Float32Array);Module._wrapSimpleListenerOutput(output_stream_name,image,false,timestamp_ms)}function JsOnWebGLTextureVectorListener(output_stream_name,name,width,height,timestamp_ms){Module._wrapSimpleListenerOutput(output_stream_name,{data:GL.textures[name],width,height},false,timestamp_ms)}function JsOnEmptyPacketListener(output_stream_name,timestamp){Module._wrapEmptyPacketListenerOutput(output_stream_name,timestamp)}function JsOnVectorFinishedListener(output_stream_name,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,undefined,true,timestamp)}function JsOnSimpleListenerBool(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,timestamp)}function JsOnVectorListenerBool(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,false,timestamp)}function JsOnSimpleListenerInt(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,timestamp)}function JsOnVectorListenerInt(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,false,timestamp)}function JsOnSimpleListenerUint(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,timestamp)}function JsOnVectorListenerUint(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,false,timestamp)}function JsOnSimpleListenerDouble(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,timestamp)}function JsOnVectorListenerDouble(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,false,timestamp)}function JsOnSimpleListenerFloat(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,timestamp)}function JsOnVectorListenerFloat(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,out_data,false,timestamp)}function JsOnSimpleListenerString(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,UTF8ToString(out_data),timestamp)}function JsOnVectorListenerString(output_stream_name,out_data,timestamp){Module._wrapSimpleListenerOutput(output_stream_name,UTF8ToString(out_data),false,timestamp)}function JsOnVectorListenerProto(output_stream_name,proto_ptr,proto_size,make_deep_copy,timestamp){const newProtoArray=make_deep_copy?Module.HEAPU8.slice(proto_ptr,proto_ptr+proto_size):new Uint8Array(Module.HEAPU8.buffer,proto_ptr,proto_size);Module._wrapSimpleListenerOutput(output_stream_name,newProtoArray,false,timestamp)}function JsWrapSimpleListeners(){if(!Module._wrapSimpleListenerOutput){Module._wrapSimpleListenerOutput=(outputStreamName,...args)=>{if(Module.simpleListeners){const streamName=UTF8ToString(outputStreamName);if(Module.simpleListeners[streamName]){Module.simpleListeners[streamName](...args)}}}}if(!Module._wrapEmptyPacketListenerOutput){Module._wrapEmptyPacketListenerOutput=(outputStreamName,timestamp)=>{if(Module.emptyPacketListeners){const streamName=UTF8ToString(outputStreamName);if(Module.emptyPacketListeners[streamName]){Module.emptyPacketListeners[streamName](timestamp)}}}}}function JsOnSimpleListenerBinaryArray(output_stream_name,binary_ptr,binary_size,make_deep_copy,timestamp){const newProtoArray=make_deep_copy?Module.HEAPU8.slice(binary_ptr,binary_ptr+binary_size):new Uint8Array(Module.HEAPU8.buffer,binary_ptr,binary_size);Module._wrapSimpleListenerOutput(output_stream_name,newProtoArray,timestamp)}function mediapipe_import_external_texture(device_handle,source_handle){const device=WebGPU.getJsObject(device_handle);const source=Emval.toValue(source_handle);const externalTexture=device.importExternalTexture({source});return Emval.toHandle(externalTexture)}function mediapipe_create_utility_canvas2d(){let canvas;if(typeof HTMLCanvasElement!=="undefined"){canvas=document.createElement("canvas");canvas.style.display="none"}else{canvas=new OffscreenCanvas(0,0)}return Emval.toHandle(canvas)}function GetAdapterArchitecture(){const device=Module["preinitializedWebGPUDevice"];const architecture=device.adapterInfo?device.adapterInfo.architecture:"Unknown";return stringToNewUTF8(architecture)}function GetAdapterDescription(){const device=Module["preinitializedWebGPUDevice"];const description=device.adapterInfo?device.adapterInfo.description:"Unknown";return stringToNewUTF8(description)}function GetAdapterDeviceName(){const device=Module["preinitializedWebGPUDevice"];const deviceName=device.adapterInfo?device.adapterInfo.device:"Unknown";return stringToNewUTF8(deviceName)}function GetAdapterVendor(){const device=Module["preinitializedWebGPUDevice"];const vendor=device.adapterInfo?device.adapterInfo.vendor:"Unknown";return stringToNewUTF8(vendor)}function __asyncjs__mediapipe_map_buffer_jspi(buffer_handle,data){return Asyncify.handleAsync(async()=>{const buffer=WebGPU.getJsObject(buffer_handle);if("mapSync"in buffer){buffer.mapSync(GPUMapMode.READ)}else{await buffer.mapAsync(GPUMapMode.READ)}const mapped=buffer.getMappedRange();HEAPU8.set(new Uint8Array(mapped),data);buffer.unmap()})}function hardware_concurrency(){var concurrency=1;try{concurrency=self.navigator.hardwareConcurrency}catch(e){}return concurrency}function JsWrapErrorListener(code,message){if(Module.errorListener){const stringMessage=UTF8ToString(message);Module.errorListener(code,stringMessage)}}function UseBottomLeftGpuOrigin(){return Module&&Module.gpuOriginForWebTexturesIsBottomLeft}function custom_emscripten_dbgn(str,len){if(typeof dbg!=="undefined"){dbg(UTF8ToString(str,len))}else{if(typeof custom_dbg==="undefined"){function custom_dbg(text){console.warn.apply(console,arguments)}}custom_dbg(UTF8ToString(str,len))}}var _free,_malloc,_wgpuDeviceAddRef,_addBoundTextureAsImageToStream,_attachImageListener,_attachImageVectorListener,_registerModelResourcesGraphService,_bindTextureToStream,_addBoundTextureToStream,_addDoubleToInputStream,_addFloatToInputStream,_addBoolToInputStream,_addIntToInputStream,_addUintToInputStream,_addStringToInputStream,_addRawDataSpanToInputStream,_allocateBoolVector,_allocateFloatVector,_allocateDoubleVector,_allocateIntVector,_allocateUintVector,_allocateStringVector,_addBoolVectorEntry,_addFloatVectorEntry,_addDoubleVectorEntry,_addIntVectorEntry,_addUintVectorEntry,_addStringVectorEntry,_addBoolVectorToInputStream,_addFloatVectorToInputStream,_addDoubleVectorToInputStream,_addIntVectorToInputStream,_addUintVectorToInputStream,_addStringVectorToInputStream,_addFlatHashMapToInputStream,_addProtoToInputStream,_addEmptyPacketToInputStream,_addBoolToInputSidePacket,_addDoubleToInputSidePacket,_addFloatToInputSidePacket,_addIntToInputSidePacket,_addUintToInputSidePacket,_addStringToInputSidePacket,_addRawDataSpanToInputSidePacket,_addProtoToInputSidePacket,_addBoolVectorToInputSidePacket,_addDoubleVectorToInputSidePacket,_addFloatVectorToInputSidePacket,_addIntVectorToInputSidePacket,_addUintVectorToInputSidePacket,_addStringVectorToInputSidePacket,_attachBoolListener,_attachBoolVectorListener,_attachDoubleListener,_attachDoubleVectorListener,_attachFloatListener,_attachFloatVectorListener,_attachIntListener,_attachIntVectorListener,_attachUintListener,_attachUintVectorListener,_attachStringListener,_attachStringVectorListener,_attachProtoListener,_attachProtoVectorListener,_getGraphConfig,___getTypeName,_emwgpuCreateBindGroup,_emwgpuCreateBindGroupLayout,_emwgpuCreateCommandBuffer,_emwgpuCreateCommandEncoder,_emwgpuCreateComputePassEncoder,_emwgpuCreateComputePipeline,_emwgpuCreateExternalTexture,_emwgpuCreatePipelineLayout,_emwgpuCreateQuerySet,_emwgpuCreateRenderBundle,_emwgpuCreateRenderBundleEncoder,_emwgpuCreateRenderPassEncoder,_emwgpuCreateRenderPipeline,_emwgpuCreateSampler,_emwgpuCreateSurface,_emwgpuCreateTexture,_emwgpuCreateTextureView,_emwgpuCreateAdapter,_emwgpuCreateBuffer,_emwgpuCreateDevice,_emwgpuCreateQueue,_emwgpuCreateShaderModule,_emwgpuOnCreateComputePipelineCompleted,_emwgpuOnCreateRenderPipelineCompleted,_clearSubgraphs,_pushBinarySubgraph,_pushTextSubgraph,_changeBinaryGraph,_changeTextGraph,_processGl,_process,_bindTextureToCanvas,_requestShaderRefreshOnGraphChange,_waitUntilIdle,_closeGraph,_setAutoRenderToScreen,_emscripten_builtin_memalign,_memalign,__emscripten_tempret_set,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,dynCall_ji,dynCall_jii,dynCall_iiiijij,dynCall_viiji,dynCall_viji,dynCall_iiiji,dynCall_jjj,dynCall_iiiijj,dynCall_viijj,dynCall_viiijjj,dynCall_vij,dynCall_viijii,dynCall_viiiji,dynCall_vijjj,dynCall_vj,dynCall_viij,dynCall_jiji,dynCall_iiiiij,dynCall_iiiiijj,dynCall_iiiiiijj,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_free=Module["_free"]=wasmExports["ld"];_malloc=Module["_malloc"]=wasmExports["md"];_wgpuDeviceAddRef=wasmExports["nd"];_addBoundTextureAsImageToStream=Module["_addBoundTextureAsImageToStream"]=wasmExports["od"];_attachImageListener=Module["_attachImageListener"]=wasmExports["pd"];_attachImageVectorListener=Module["_attachImageVectorListener"]=wasmExports["qd"];_registerModelResourcesGraphService=Module["_registerModelResourcesGraphService"]=wasmExports["rd"];_bindTextureToStream=Module["_bindTextureToStream"]=wasmExports["sd"];_addBoundTextureToStream=Module["_addBoundTextureToStream"]=wasmExports["td"];_addDoubleToInputStream=Module["_addDoubleToInputStream"]=wasmExports["ud"];_addFloatToInputStream=Module["_addFloatToInputStream"]=wasmExports["vd"];_addBoolToInputStream=Module["_addBoolToInputStream"]=wasmExports["wd"];_addIntToInputStream=Module["_addIntToInputStream"]=wasmExports["xd"];_addUintToInputStream=Module["_addUintToInputStream"]=wasmExports["yd"];_addStringToInputStream=Module["_addStringToInputStream"]=wasmExports["zd"];_addRawDataSpanToInputStream=Module["_addRawDataSpanToInputStream"]=wasmExports["Ad"];_allocateBoolVector=Module["_allocateBoolVector"]=wasmExports["Bd"];_allocateFloatVector=Module["_allocateFloatVector"]=wasmExports["Cd"];_allocateDoubleVector=Module["_allocateDoubleVector"]=wasmExports["Dd"];_allocateIntVector=Module["_allocateIntVector"]=wasmExports["Ed"];_allocateUintVector=Module["_allocateUintVector"]=wasmExports["Fd"];_allocateStringVector=Module["_allocateStringVector"]=wasmExports["Gd"];_addBoolVectorEntry=Module["_addBoolVectorEntry"]=wasmExports["Hd"];_addFloatVectorEntry=Module["_addFloatVectorEntry"]=wasmExports["Id"];_addDoubleVectorEntry=Module["_addDoubleVectorEntry"]=wasmExports["Jd"];_addIntVectorEntry=Module["_addIntVectorEntry"]=wasmExports["Kd"];_addUintVectorEntry=Module["_addUintVectorEntry"]=wasmExports["Ld"];_addStringVectorEntry=Module["_addStringVectorEntry"]=wasmExports["Md"];_addBoolVectorToInputStream=Module["_addBoolVectorToInputStream"]=wasmExports["Nd"];_addFloatVectorToInputStream=Module["_addFloatVectorToInputStream"]=wasmExports["Od"];_addDoubleVectorToInputStream=Module["_addDoubleVectorToInputStream"]=wasmExports["Pd"];_addIntVectorToInputStream=Module["_addIntVectorToInputStream"]=wasmExports["Qd"];_addUintVectorToInputStream=Module["_addUintVectorToInputStream"]=wasmExports["Rd"];_addStringVectorToInputStream=Module["_addStringVectorToInputStream"]=wasmExports["Sd"];_addFlatHashMapToInputStream=Module["_addFlatHashMapToInputStream"]=wasmExports["Td"];_addProtoToInputStream=Module["_addProtoToInputStream"]=wasmExports["Ud"];_addEmptyPacketToInputStream=Module["_addEmptyPacketToInputStream"]=wasmExports["Vd"];_addBoolToInputSidePacket=Module["_addBoolToInputSidePacket"]=wasmExports["Wd"];_addDoubleToInputSidePacket=Module["_addDoubleToInputSidePacket"]=wasmExports["Xd"];_addFloatToInputSidePacket=Module["_addFloatToInputSidePacket"]=wasmExports["Yd"];_addIntToInputSidePacket=Module["_addIntToInputSidePacket"]=wasmExports["Zd"];_addUintToInputSidePacket=Module["_addUintToInputSidePacket"]=wasmExports["_d"];_addStringToInputSidePacket=Module["_addStringToInputSidePacket"]=wasmExports["$d"];_addRawDataSpanToInputSidePacket=Module["_addRawDataSpanToInputSidePacket"]=wasmExports["ae"];_addProtoToInputSidePacket=Module["_addProtoToInputSidePacket"]=wasmExports["be"];_addBoolVectorToInputSidePacket=Module["_addBoolVectorToInputSidePacket"]=wasmExports["ce"];_addDoubleVectorToInputSidePacket=Module["_addDoubleVectorToInputSidePacket"]=wasmExports["de"];_addFloatVectorToInputSidePacket=Module["_addFloatVectorToInputSidePacket"]=wasmExports["ee"];_addIntVectorToInputSidePacket=Module["_addIntVectorToInputSidePacket"]=wasmExports["fe"];_addUintVectorToInputSidePacket=Module["_addUintVectorToInputSidePacket"]=wasmExports["ge"];_addStringVectorToInputSidePacket=Module["_addStringVectorToInputSidePacket"]=wasmExports["he"];_attachBoolListener=Module["_attachBoolListener"]=wasmExports["ie"];_attachBoolVectorListener=Module["_attachBoolVectorListener"]=wasmExports["je"];_attachDoubleListener=Module["_attachDoubleListener"]=wasmExports["ke"];_attachDoubleVectorListener=Module["_attachDoubleVectorListener"]=wasmExports["le"];_attachFloatListener=Module["_attachFloatListener"]=wasmExports["me"];_attachFloatVectorListener=Module["_attachFloatVectorListener"]=wasmExports["ne"];_attachIntListener=Module["_attachIntListener"]=wasmExports["oe"];_attachIntVectorListener=Module["_attachIntVectorListener"]=wasmExports["pe"];_attachUintListener=Module["_attachUintListener"]=wasmExports["qe"];_attachUintVectorListener=Module["_attachUintVectorListener"]=wasmExports["re"];_attachStringListener=Module["_attachStringListener"]=wasmExports["se"];_attachStringVectorListener=Module["_attachStringVectorListener"]=wasmExports["te"];_attachProtoListener=Module["_attachProtoListener"]=wasmExports["ue"];_attachProtoVectorListener=Module["_attachProtoVectorListener"]=wasmExports["ve"];_getGraphConfig=Module["_getGraphConfig"]=wasmExports["we"];___getTypeName=wasmExports["xe"];_emwgpuCreateBindGroup=wasmExports["ye"];_emwgpuCreateBindGroupLayout=wasmExports["ze"];_emwgpuCreateCommandBuffer=wasmExports["Ae"];_emwgpuCreateCommandEncoder=wasmExports["Be"];_emwgpuCreateComputePassEncoder=wasmExports["Ce"];_emwgpuCreateComputePipeline=wasmExports["De"];_emwgpuCreateExternalTexture=wasmExports["Ee"];_emwgpuCreatePipelineLayout=wasmExports["Fe"];_emwgpuCreateQuerySet=wasmExports["Ge"];_emwgpuCreateRenderBundle=wasmExports["He"];_emwgpuCreateRenderBundleEncoder=wasmExports["Ie"];_emwgpuCreateRenderPassEncoder=wasmExports["Je"];_emwgpuCreateRenderPipeline=wasmExports["Ke"];_emwgpuCreateSampler=wasmExports["Le"];_emwgpuCreateSurface=wasmExports["Me"];_emwgpuCreateTexture=wasmExports["Ne"];_emwgpuCreateTextureView=wasmExports["Oe"];_emwgpuCreateAdapter=wasmExports["Pe"];_emwgpuCreateBuffer=wasmExports["Qe"];_emwgpuCreateDevice=wasmExports["Re"];_emwgpuCreateQueue=wasmExports["Se"];_emwgpuCreateShaderModule=wasmExports["Te"];_emwgpuOnCreateComputePipelineCompleted=wasmExports["Ue"];_emwgpuOnCreateRenderPipelineCompleted=wasmExports["Ve"];_clearSubgraphs=Module["_clearSubgraphs"]=wasmExports["We"];_pushBinarySubgraph=Module["_pushBinarySubgraph"]=wasmExports["Xe"];_pushTextSubgraph=Module["_pushTextSubgraph"]=wasmExports["Ye"];_changeBinaryGraph=Module["_changeBinaryGraph"]=wasmExports["Ze"];_changeTextGraph=Module["_changeTextGraph"]=wasmExports["_e"];_processGl=Module["_processGl"]=wasmExports["$e"];_process=Module["_process"]=wasmExports["af"];_bindTextureToCanvas=Module["_bindTextureToCanvas"]=wasmExports["bf"];_requestShaderRefreshOnGraphChange=Module["_requestShaderRefreshOnGraphChange"]=wasmExports["cf"];_waitUntilIdle=Module["_waitUntilIdle"]=wasmExports["df"];_closeGraph=Module["_closeGraph"]=wasmExports["ef"];_setAutoRenderToScreen=Module["_setAutoRenderToScreen"]=wasmExports["ff"];_emscripten_builtin_memalign=wasmExports["gf"];_memalign=wasmExports["hf"];__emscripten_tempret_set=wasmExports["jf"];__emscripten_stack_restore=wasmExports["kf"];__emscripten_stack_alloc=wasmExports["lf"];_emscripten_stack_get_current=wasmExports["mf"];dynCall_ji=wasmExports["dynCall_ji"];dynCall_jii=wasmExports["dynCall_jii"];dynCall_iiiijij=wasmExports["dynCall_iiiijij"];dynCall_viiji=wasmExports["dynCall_viiji"];dynCall_viji=wasmExports["dynCall_viji"];dynCall_iiiji=wasmExports["dynCall_iiiji"];dynCall_jjj=wasmExports["dynCall_jjj"];dynCall_iiiijj=wasmExports["dynCall_iiiijj"];dynCall_viijj=wasmExports["dynCall_viijj"];dynCall_viiijjj=wasmExports["dynCall_viiijjj"];dynCall_vij=wasmExports["dynCall_vij"];dynCall_viijii=wasmExports["dynCall_viijii"];dynCall_viiiji=wasmExports["dynCall_viiiji"];dynCall_vijjj=wasmExports["dynCall_vijjj"];dynCall_vj=wasmExports["dynCall_vj"];dynCall_viij=wasmExports["dynCall_viij"];dynCall_jiji=wasmExports["dynCall_jiji"];dynCall_iiiiij=wasmExports["dynCall_iiiiij"];dynCall_iiiiijj=wasmExports["dynCall_iiiiijj"];dynCall_iiiiiijj=wasmExports["dynCall_iiiiiijj"];memory=wasmMemory=wasmExports["id"];__indirect_function_table=wasmTable=wasmExports["kd"]}var _kVersionStampBuildChangelistStr=Module["_kVersionStampBuildChangelistStr"]=1024;var _kVersionStampCitcSnapshotStr=Module["_kVersionStampCitcSnapshotStr"]=1056;var _kVersionStampCitcWorkspaceIdStr=Module["_kVersionStampCitcWorkspaceIdStr"]=1088;var _kVersionStampSourceUriStr=Module["_kVersionStampSourceUriStr"]=1600;var _kVersionStampBuildClientStr=Module["_kVersionStampBuildClientStr"]=2112;var _kVersionStampBuildClientMintStatusStr=Module["_kVersionStampBuildClientMintStatusStr"]=2624;var _kVersionStampBuildCompilerStr=Module["_kVersionStampBuildCompilerStr"]=2656;var _kVersionStampBuildDateTimePstStr=Module["_kVersionStampBuildDateTimePstStr"]=3168;var _kVersionStampBuildDepotPathStr=Module["_kVersionStampBuildDepotPathStr"]=3200;var _kVersionStampBuildIdStr=Module["_kVersionStampBuildIdStr"]=3712;var _kVersionStampBuildInfoStr=Module["_kVersionStampBuildInfoStr"]=4224;var _kVersionStampBuildLabelStr=Module["_kVersionStampBuildLabelStr"]=4736;var _kVersionStampBuildTargetStr=Module["_kVersionStampBuildTargetStr"]=5248;var _kVersionStampBuildTimestampStr=Module["_kVersionStampBuildTimestampStr"]=5760;var _kVersionStampBuildToolStr=Module["_kVersionStampBuildToolStr"]=5792;var _kVersionStampG3BuildTargetStr=Module["_kVersionStampG3BuildTargetStr"]=6304;var _kVersionStampVerifiableStr=Module["_kVersionStampVerifiableStr"]=6816;var _kVersionStampBuildFdoTypeStr=Module["_kVersionStampBuildFdoTypeStr"]=6848;var _kVersionStampBuildBaselineChangelistStr=Module["_kVersionStampBuildBaselineChangelistStr"]=6880;var _kVersionStampBuildLtoTypeStr=Module["_kVersionStampBuildLtoTypeStr"]=6912;var _kVersionStampBuildPropellerTypeStr=Module["_kVersionStampBuildPropellerTypeStr"]=6944;var _kVersionStampBuildPghoTypeStr=Module["_kVersionStampBuildPghoTypeStr"]=6976;var _kVersionStampBuildUsernameStr=Module["_kVersionStampBuildUsernameStr"]=7008;var _kVersionStampBuildHostnameStr=Module["_kVersionStampBuildHostnameStr"]=7520;var _kVersionStampBuildDirectoryStr=Module["_kVersionStampBuildDirectoryStr"]=8032;var _kVersionStampBuildChangelistInt=Module["_kVersionStampBuildChangelistInt"]=8544;var _kVersionStampCitcSnapshotInt=Module["_kVersionStampCitcSnapshotInt"]=8552;var _kVersionStampBuildClientMintStatusInt=Module["_kVersionStampBuildClientMintStatusInt"]=8556;var _kVersionStampBuildTimestampInt=Module["_kVersionStampBuildTimestampInt"]=8560;var _kVersionStampVerifiableInt=Module["_kVersionStampVerifiableInt"]=8568;var _kVersionStampBuildCoverageEnabledInt=Module["_kVersionStampBuildCoverageEnabledInt"]=8572;var _kVersionStampBuildBaselineChangelistInt=Module["_kVersionStampBuildBaselineChangelistInt"]=8576;var _kVersionStampPrecookedTimestampStr=Module["_kVersionStampPrecookedTimestampStr"]=8592;var _kVersionStampPrecookedClientInfoStr=Module["_kVersionStampPrecookedClientInfoStr"]=9104;var wasmImports={hd:BeginGlQueryTiming,gd:EndGlQueryTiming,fd:GetAdapterArchitecture,ed:GetAdapterDescription,dd:GetAdapterDeviceName,cd:GetAdapterVendor,bd:JsOnEmptyPacketListener,ad:JsOnFloat32ArrayImageListener,$c:JsOnFloat32ArrayImageVectorListener,pb:JsOnSimpleListenerBinaryArray,_c:JsOnSimpleListenerBool,Zc:JsOnSimpleListenerDouble,Yc:JsOnSimpleListenerFloat,Xc:JsOnSimpleListenerInt,Wc:JsOnSimpleListenerString,Vc:JsOnSimpleListenerUint,Uc:JsOnUint8ArrayImageListener,Tc:JsOnUint8ArrayImageVectorListener,O:JsOnVectorFinishedListener,Sc:JsOnVectorListenerBool,Rc:JsOnVectorListenerDouble,Qc:JsOnVectorListenerFloat,Pc:JsOnVectorListenerInt,Oc:JsOnVectorListenerProto,Nc:JsOnVectorListenerString,Mc:JsOnVectorListenerUint,Lc:JsOnWebGLTextureListener,Kc:JsOnWebGLTextureVectorListener,Pa:JsWrapErrorListener,ob:JsWrapImageConverter,u:JsWrapSimpleListeners,nb:UseBottomLeftGpuOrigin,yb:__asyncjs__mediapipe_map_buffer_jspi,o:___cxa_throw,Jc:___syscall_dup,Ic:___syscall_faccessat,mb:___syscall_fcntl64,Hc:___syscall_fstat64,Mb:___syscall_ftruncate64,Gc:___syscall_ioctl,Fc:___syscall_lstat64,Ec:___syscall_newfstatat,lb:___syscall_openat,Dc:___syscall_stat64,yc:__abort_js,Jb:__embind_register_bigint,xc:__embind_register_bool,wc:__embind_register_emval,jb:__embind_register_float,I:__embind_register_integer,r:__embind_register_memory_view,vc:__embind_register_std_string,Ma:__embind_register_std_wstring,uc:__embind_register_void,$:__emval_create_invoker,q:__emval_decref,La:__emval_get_global,ib:__emval_get_property,ja:__emval_incref,Ka:__emval_instanceof,_:__emval_invoke,ua:__emval_new_cstring,Z:__emval_run_destructors,hb:__emval_set_property,tc:__emval_typeof,Ib:__gmtime_js,Hb:__localtime_js,Gb:__mktime_js,Fb:__mmap_js,Eb:__munmap_js,sc:__tzset_js,Lb:_clock_time_get,rc:custom_emscripten_dbgn,Y:_emscripten_asm_const_int,gb:_emscripten_asm_const_ptr,Ja:_emscripten_errn,qc:_emscripten_get_heap_max,y:_emscripten_get_now,ia:_emscripten_has_asyncify,pc:_emscripten_outn,oc:_emscripten_pc_get_function,nc:_emscripten_resize_heap,fb:_emscripten_stack_snapshot,mc:_emscripten_stack_unwind_buffer,lc:_emscripten_webgl_create_context,kc:_emscripten_webgl_destroy_context,jc:_emscripten_webgl_get_context_attributes,ha:_emscripten_webgl_get_current_context,ic:_emscripten_webgl_make_context_current,Q:_emscripten_webgpu_get_device,hc:_emwgpuBufferDestroy,gc:_emwgpuBufferGetMappedRange,fc:_emwgpuBufferUnmap,x:_emwgpuDelete,ec:_emwgpuDeviceCreateBuffer,Db:_emwgpuDeviceCreateComputePipelineAsync,Cb:_emwgpuDeviceCreateRenderPipelineAsync,dc:_emwgpuDeviceCreateShaderModule,cc:_emwgpuDeviceDestroy,bc:_emwgpuWaitAny,Cc:_environ_get,Bc:_environ_sizes_get,eb:_exit,Oa:_fd_close,kb:_fd_read,Kb:_fd_seek,Na:_fd_write,b:_glActiveTexture,ta:_glAttachShader,ac:_glBindAttribLocation,c:_glBindBuffer,db:_glBindBufferBase,t:_glBindFramebuffer,a:_glBindTexture,m:_glBindVertexArray,cb:_glBlendEquation,$b:_glBlendFunc,j:_glBufferData,H:_glClear,X:_glClearColor,da:_glClientWaitSync,ga:_glColorMask,bb:_glCompileShader,ab:_glCreateProgram,$a:_glCreateShader,p:_glDeleteBuffers,P:_glDeleteFramebuffers,h:_glDeleteProgram,sa:_glDeleteShader,ra:_glDeleteSync,D:_glDeleteTextures,A:_glDeleteVertexArrays,_a:_glDetachShader,G:_glDisable,n:_glDisableVertexAttribArray,i:_glDrawArrays,fa:_glDrawBuffers,_b:_glEnable,l:_glEnableVertexAttribArray,Za:_glFenceSync,qa:_glFinish,v:_glFlush,C:_glFramebufferTexture2D,Ya:_glFramebufferTextureLayer,s:_glGenBuffers,W:_glGenFramebuffers,F:_glGenTextures,B:_glGenVertexArrays,Xa:_glGetAttribLocation,ea:_glGetError,Zb:_glGetFloatv,w:_glGetIntegerv,Yb:_glGetProgramiv,Xb:_glGetShaderInfoLog,Wb:_glGetShaderiv,N:_glGetString,Vb:_glGetUniformBlockIndex,d:_glGetUniformLocation,Ub:_glLineWidth,Wa:_glLinkProgram,pa:_glPixelStorei,oa:_glReadPixels,Va:_glShaderSource,E:_glTexImage2D,na:_glTexParameterf,Ua:_glTexParameterfv,f:_glTexParameteri,ma:_glTexStorage2D,Tb:_glTexStorage3D,V:_glTexSubImage2D,Sb:_glTexSubImage3D,M:_glUniform1f,la:_glUniform1fv,e:_glUniform1i,U:_glUniform2f,Rb:_glUniform2fv,Ia:_glUniform3f,Ta:_glUniform4f,T:_glUniform4fv,Qb:_glUniform4iv,Pb:_glUniformBlockBinding,Ob:_glUniformMatrix2fv,Nb:_glUniformMatrix3fv,Ha:_glUniformMatrix4fv,g:_glUseProgram,k:_glVertexAttribPointer,S:_glViewport,Ga:hardware_concurrency,Bb:mediapipe_create_utility_canvas2d,Ab:_mediapipe_find_canvas_event_target,zb:mediapipe_import_external_texture,xb:_mediapipe_webgl_tex_image_drawable,Ac:_proc_exit,zc:_random_get,Fa:_wgpuCommandEncoderBeginComputePass,Ea:_wgpuCommandEncoderBeginRenderPass,wb:_wgpuCommandEncoderCopyBufferToTexture,vb:_wgpuCommandEncoderCopyTextureToBuffer,ub:_wgpuCommandEncoderCopyTextureToTexture,L:_wgpuCommandEncoderFinish,Da:_wgpuComputePassEncoderDispatchWorkgroups,Ca:_wgpuComputePassEncoderEnd,Ba:_wgpuComputePassEncoderSetBindGroup,Aa:_wgpuComputePassEncoderSetPipeline,za:_wgpuComputePipelineGetBindGroupLayout,ca:_wgpuDeviceCreateBindGroup,tb:_wgpuDeviceCreateBindGroupLayout,K:_wgpuDeviceCreateCommandEncoder,sb:_wgpuDeviceCreateComputePipeline,rb:_wgpuDeviceCreatePipelineLayout,Sa:_wgpuDeviceCreateRenderPipeline,R:_wgpuDeviceCreateSampler,ba:_wgpuDeviceCreateTexture,J:_wgpuQueueSubmit,ka:_wgpuQueueWriteBuffer,qb:_wgpuQueueWriteTexture,ya:_wgpuRenderPassEncoderDraw,xa:_wgpuRenderPassEncoderEnd,wa:_wgpuRenderPassEncoderSetBindGroup,va:_wgpuRenderPassEncoderSetPipeline,Ra:_wgpuRenderPipelineGetBindGroupLayout,z:_wgpuTextureCreateView,Qa:_wgpuTextureDestroy,aa:_wgpuTextureGetFormat};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}-;return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=ModuleFactory;module.exports.default=ModuleFactory}else if(typeof define==="function"&&define["amd"])define([],()=>ModuleFactory);+// This code implements the `-sMODULARIZE` settings by taking the generated+// JS program code (INNER_JS_CODE) and wrapping it in a factory function.++// Single threaded MINIMAL_RUNTIME programs do not need access to+// document.currentScript, so a simple export declaration is enough.+var ModuleFactory = (() => {+ // When MODULARIZE this JS may be executed later,+ // after document.currentScript is gone, so we save it.+ // In EXPORT_ES6 mode we can just use 'import.meta.url'.+ var _scriptName = globalThis.document?.currentScript?.src;+ return async function(moduleArg = {}) {+ var Module = moduleArg;+// include: shell.js+// include: minimum_runtime_check.js+// end include: minimum_runtime_check.js+// The Module object: Our interface to the outside world. We import+// and export values on it. There are various ways Module can be used:+// 1. Not defined. We create it here+// 2. A function parameter, function(moduleArg) => Promise<Module>+// 3. pre-run appended it, var Module = {}; ..generated code..+// 4. External script tag defines var Module.+// We need to check if Module already exists (e.g. case 3 above).+// Substitution will be replaced with actual code on later stage of the build,+// this way Closure Compiler will not mangle it (e.g. case 4. above).+// Note that if you want to run closure, and also to use Module+// after the generated code, you will need to define var Module = {};+// before the code. Then that object will be used in the code, and you+// can continue to use Module afterwards as well.+// Determine the runtime environment we are in. You can customize this by+// setting the ENVIRONMENT setting at compile time (see settings.js).+// Attempt to auto-detect the environment+var ENVIRONMENT_IS_WEB = !!globalThis.window;++var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope;++// N.b. Electron.js environment is simultaneously a NODE-environment, but+// also a web environment.+var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != "renderer";++// --pre-jses are emitted after the Module integration code, so that they can+// refer to Module (if they choose; they can also define Module)+var programArgs = [];++var thisProgram = "./this.program";++var quit_ = (status, toThrow) => {+ throw toThrow;+};++if (typeof __filename != "undefined") {+ // Node+ _scriptName = __filename;+} else if (ENVIRONMENT_IS_WORKER) {+ _scriptName = self.location.href;+}++// `/` should be present at the end if `scriptDirectory` is not empty+var scriptDirectory = "";++function locateFile(path) {+ if (Module["locateFile"]) {+ return Module["locateFile"](path, scriptDirectory);+ }+ return scriptDirectory + path;+}++// Hooks that are implemented differently in different runtime environments.+var readAsync, readBinary;++if (ENVIRONMENT_IS_NODE) {+ // These modules will usually be used on Node.js. Load them eagerly to avoid+ // the complexity of lazy-loading.+ var fs = require("node:fs");+ scriptDirectory = __dirname + "/";+ // include: node_shell_read.js+ readBinary = filename => {+ // We need to re-wrap `file://` strings to URLs.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename);+ return ret;+ };+ readAsync = async (filename, binary = true) => {+ // See the comment in the `readBinary` function.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename, binary ? undefined : "utf8");+ return ret;+ };+ // end include: node_shell_read.js+ if (process.argv.length > 1) {+ thisProgram = process.argv[1].replace(/\\/g, "/");+ }+ programArgs = process.argv.slice(2);+ quit_ = (status, toThrow) => {+ process.exitCode = status;+ throw toThrow;+ };+} else // Note that this includes Node.js workers when relevant (pthreads is enabled).+// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and+// ENVIRONMENT_IS_NODE.+if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {+ try {+ scriptDirectory = new URL(".", _scriptName).href;+ } catch {}+ {+ // include: web_or_worker_shell_read.js+ if (ENVIRONMENT_IS_WORKER) {+ readBinary = url => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ xhr.responseType = "arraybuffer";+ xhr.send(null);+ return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response));+ };+ }+ readAsync = async url => {+ // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.+ // See https://github.com/github/fetch/pull/92#issuecomment-140665932+ // Cordova or Electron apps are typically loaded from a file:// url.+ // So use XHR on webview if URL is a file URL.+ if (isFileURI(url)) {+ return new Promise((resolve, reject) => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, true);+ xhr.responseType = "arraybuffer";+ xhr.onload = () => {+ if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {+ // file URLs can return 0+ resolve(xhr.response);+ return;+ }+ reject(xhr.status);+ };+ xhr.onerror = reject;+ xhr.send(null);+ });+ }+ var response = await fetch(url, {+ credentials: "same-origin"+ });+ if (response.ok) {+ return response.arrayBuffer();+ }+ throw new Error(response.status + " : " + response.url);+ };+ }+} else {}++var out = console.log.bind(console);++var err = console.error.bind(console);++// end include: shell.js+// include: preamble.js+// === Preamble library stuff ===+// Documentation for the public APIs defined in this file must be updated in:+// site/source/docs/api_reference/preamble.js.rst+// A prebuilt local version of the documentation is available at:+// site/build/text/docs/api_reference/preamble.js.txt+// You can also build docs locally as HTML or other formats in site/+// An online HTML version (which may be of a different version of Emscripten)+// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html+var wasmBinary;++// Wasm globals+//========================================+// Runtime essentials+//========================================+// whether we are quitting the application. no code should run after this.+// set in exit() and abort()+var ABORT = false;++// set by exit() and abort(). Passed to 'onExit' handler.+// NOTE: This is also used as the process return code in shell environments+// but only when noExitRuntime is false.+var EXITSTATUS;++// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we+// don't define it at all in release modes. This matches the behaviour of+// MINIMAL_RUNTIME.+// TODO(sbc): Make this the default even without STRICT enabled.+/** @type {function(*, string=)} */ function assert(condition, text) {+ if (!condition) {+ // This build was created without ASSERTIONS defined. `assert()` should not+ // ever be called in this configuration but in case there are callers in+ // the wild leave this simple abort() implementation here for now.+ abort(text);+ }+}++/**+ * Indicates whether filename is delivered via file protocol (as opposed to http/https)+ * @noinline+ */ var isFileURI = filename => filename.startsWith("file://");++// include: runtime_common.js+// include: runtime_exceptions.js+// Base Emscripten EH error class+class EmscriptenEH {}++class EmscriptenSjLj extends EmscriptenEH {}++// end include: runtime_exceptions.js+// include: runtime_debug.js+// end include: runtime_debug.js+// Memory management+var runtimeInitialized = false;++// When ALLOW_MEMORY_GROWTH is enabled, the conversion from Wasm+// memory to ArrayBuffer requires some additional logic.+function getMemoryBuffer() {+ return wasmMemory.buffer;+}++function updateMemoryViews() {+ // If we already have a heap that is resizeable/growable buffer we don't+ // need to do anything in updateMemoryViews.+ if (HEAP8?.buffer?.resizable) return;+ var b = getMemoryBuffer();+ HEAP8 = new Int8Array(b);+ HEAP16 = new Int16Array(b);+ Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);+ HEAPU16 = new Uint16Array(b);+ HEAP32 = new Int32Array(b);+ Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);+ Module["HEAPF32"] = HEAPF32 = new Float32Array(b);+ Module["HEAPF64"] = HEAPF64 = new Float64Array(b);+}++// include: memoryprofiler.js+// end include: memoryprofiler.js+// end include: runtime_common.js+function preRun() {+ var preRun = Module["preRun"];+ if (preRun) {+ if (typeof preRun == "function") preRun = [ preRun ];+ onPreRuns.push(...preRun);+ }+ // Begin ATPRERUNS hooks+ callRuntimeCallbacks(onPreRuns);+}++function initRuntime() {+ runtimeInitialized = true;+ // Begin ATINITS hooks+ if (!Module["noFSInit"] && !FS.initialized) FS.init();+ TTY.init();+ // End ATINITS hooks+ wasmExports["td"]();+ // Begin ATPOSTCTORS hooks+ FS.ignorePermissions = false;+}++function postRun() {+ var postRun = Module["postRun"];+ if (postRun) {+ if (typeof postRun == "function") postRun = [ postRun ];+ onPostRuns.push(...postRun);+ }+ // Begin ATPOSTRUNS hooks+ callRuntimeCallbacks(onPostRuns);+}++/**+ * @param {string|number=} what+ */ function abort(what) {+ Module["onAbort"]?.(what);+ what = `Aborted(${what})`;+ // TODO(sbc): Should we remove printing and leave it up to whoever+ // catches the exception?+ err(what);+ ABORT = true;+ what += ". Build with -sASSERTIONS for more info.";+ // Use a wasm runtime error, because a JS error might be seen as a foreign+ // exception, which means we'd run destructors on it. We need the error to+ // simply make the program stop.+ // FIXME This approach does not work in Wasm EH because it currently does not assume+ // all RuntimeErrors are from traps; it decides whether a RuntimeError is from+ // a trap or not based on a hidden field within the object. So at the moment+ // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that+ // allows this in the wasm spec.+ // Suppress closure compiler warning here. Closure compiler's builtin extern+ // definition for WebAssembly.RuntimeError claims it takes no arguments even+ // though it can.+ // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.+ /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what);+ // Throw the error whether or not MODULARIZE is set because abort is used+ // in code paths apart from instantiation where an exception is expected+ // to be thrown when abort is called.+ throw e;+}++var wasmBinaryFile;++function findWasmBinary() {+ return locateFile("vision_wasm_internal.wasm");+}++function getBinarySync(file) {+ if (readBinary) {+ return readBinary(file);+ }+ // Throwing a plain string here, even though it not normally advisable since+ // this gets turning into an `abort` in instantiateArrayBuffer.+ throw "both async and sync fetching of the wasm failed";+}++async function getWasmBinary(binaryFile) {+ // If we don't have the binary yet, load it asynchronously using readAsync.+ if (!wasmBinary) {+ // Fetch the binary using readAsync+ try {+ var response = await readAsync(binaryFile);+ return new Uint8Array(response);+ } catch {}+ }+ // Otherwise, getBinarySync should be able to get it synchronously+ return getBinarySync(binaryFile);+}++async function instantiateArrayBuffer(binaryFile, imports) {+ try {+ var binary = await getWasmBinary(binaryFile);+ var instance = await WebAssembly.instantiate(binary, imports);+ return instance;+ } catch (reason) {+ err(`failed to asynchronously prepare wasm: ${reason}`);+ abort(reason);+ }+}++async function instantiateAsync(binary, binaryFile, imports) {+ if (!binary && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {+ try {+ var response = fetch(binaryFile, {+ credentials: "same-origin"+ });+ var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);+ return instantiationResult;+ } catch (reason) {+ // We expect the most common failure cause to be a bad MIME type for the binary,+ // in which case falling back to ArrayBuffer instantiation should work.+ err(`wasm streaming compile failed: ${reason}`);+ err("falling back to ArrayBuffer instantiation");+ }+ }+ return instantiateArrayBuffer(binaryFile, imports);+}++function getWasmImports() {+ // prepare imports+ var imports = {+ "a": wasmImports+ };+ return imports;+}++// Create the wasm instance.+// Receives the wasm imports, returns the exports.+async function createWasm() {+ // Load the wasm module and create an instance of using native support in the JS engine.+ // handle a generated wasm instance, receiving its exports and+ // performing other necessary setup+ function receiveInstance(instance) {+ wasmExports = instance.exports;+ assignWasmExports(wasmExports);+ updateMemoryViews();+ return wasmExports;+ }+ // Prefer streaming instantiation if available.+ function receiveInstantiationResult(result) {+ // 'result' is a ResultObject object which has both the module and instance.+ // receiveInstance() will swap in the exports (to Module.asm) so they can be called+ // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.+ // When the regression is fixed, can restore the above PTHREADS-enabled path.+ return receiveInstance(result["instance"]);+ }+ var info = getWasmImports();+ // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback+ // to manually instantiate the Wasm module themselves. This allows pages to+ // run the instantiation parallel to any other async startup actions they are+ // performing.+ // Also pthreads and wasm workers initialize the wasm instance through this+ // path.+ var instantiateWasm = Module["instantiateWasm"];+ if (instantiateWasm) {+ return new Promise(resolve => {+ instantiateWasm(info, inst => resolve(receiveInstance(inst)));+ });+ }+ wasmBinaryFile ??= findWasmBinary();+ var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);+ var exports = receiveInstantiationResult(result);+ return exports;+}++// Globals used by JS i64 conversions (see makeSetValue)+var tempDouble;++var tempI64;++// end include: preamble.js+// Begin JS library code+var handleException = e => {+ // Certain exception types we do not treat as errors since they are used for+ // internal control flow.+ // 1. ExitStatus, which is thrown by exit()+ // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others+ // that wish to return to JS event loop.+ if (e instanceof ExitStatus || e == "unwind") {+ return EXITSTATUS;+ }+ quit_(1, e);+};++class ExitStatus {+ name="ExitStatus";+ constructor(status) {+ this.message = `Program terminated with exit(${status})`;+ this.status = status;+ }+}++var runtimeKeepaliveCounter = 0;++var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;++var _proc_exit = code => {+ EXITSTATUS = code;+ if (!keepRuntimeAlive()) {+ Module["onExit"]?.(code);+ ABORT = true;+ }+ quit_(code, new ExitStatus(code));+};++/** @param {boolean|number=} implicit */ var exitJS = (status, implicit) => {+ EXITSTATUS = status;+ _proc_exit(status);+};++var _exit = exitJS;++var maybeExit = () => {+ if (!keepRuntimeAlive()) {+ try {+ _exit(EXITSTATUS);+ } catch (e) {+ handleException(e);+ }+ }+};++var callUserCallback = func => {+ if (ABORT) {+ return;+ }+ try {+ return func();+ } catch (e) {+ handleException(e);+ } finally {+ maybeExit();+ }+};++function getFullscreenElement() {+ return document.fullscreenElement ?? document.webkitFullscreenElement;+}++/** @param {number=} timeout */ var safeSetTimeout = (func, timeout) => setTimeout(() => {+ callUserCallback(func);+}, timeout);++var warnOnce = text => {+ warnOnce.shown ||= {};+ if (!warnOnce.shown[text]) {+ warnOnce.shown[text] = 1;+ if (ENVIRONMENT_IS_NODE) text = "warning: " + text;+ err(text);+ }+};++var preloadPlugins = [];++/** @type {!Int32Array} */ var HEAP32;++/** @type {!Uint32Array} */ var HEAPU32;++var Browser = {+ useWebGL: false,+ isFullscreen: false,+ pointerLock: false,+ moduleContextCreatedCallbacks: [],+ preloadedImages: {},+ preloadedAudios: {},+ getCanvas: () => Module["canvas"],+ init() {+ if (Browser.initted) return;+ Browser.initted = true;+ // Support for plugins that can process preloaded files. You can add more of these to+ // your app by creating and appending to preloadPlugins.+ // Each plugin is asked if it can handle a file based on the file's name. If it can,+ // it is given the file's raw data. When it is done, it calls a callback with the file's+ // (possibly modified) data. For example, a plugin might decompress a file, or it+ // might create some side data structure for use later (like an Image element, etc.).+ var imagePlugin = {};+ imagePlugin["canHandle"] = name => !Module["noImageDecoding"] && /\.(jpg|jpeg|png|bmp|webp)$/i.test(name);+ imagePlugin["handle"] = async (byteArray, name) => {+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ if (b.size !== byteArray.length) {+ // Safari bug #118630+ // Safari's Blob can only take an ArrayBuffer+ b = new Blob([ (new Uint8Array(byteArray)).buffer ], {+ type: Browser.getMimetype(name)+ });+ }+ var url = URL.createObjectURL(b);+ return new Promise((resolve, reject) => {+ var img = new Image;+ img.onload = () => {+ var canvas = /** @type {!HTMLCanvasElement} */ (document.createElement("canvas"));+ canvas.width = img.width;+ canvas.height = img.height;+ var ctx = canvas.getContext("2d");+ ctx.drawImage(img, 0, 0);+ Browser.preloadedImages[name] = canvas;+ URL.revokeObjectURL(url);+ resolve(byteArray);+ };+ img.onerror = event => {+ err(`Image ${url} could not be decoded`);+ reject();+ };+ img.src = url;+ });+ };+ preloadPlugins.push(imagePlugin);+ var audioPlugin = {};+ audioPlugin["canHandle"] = name => !Module["noAudioDecoding"] && name.slice(-4) in {+ ".ogg": 1,+ ".wav": 1,+ ".mp3": 1+ };+ audioPlugin["handle"] = async (byteArray, name) => new Promise((resolve, reject) => {+ var done = false;+ function finish(audio) {+ if (done) return;+ done = true;+ Browser.preloadedAudios[name] = audio;+ resolve(byteArray);+ }+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ var url = URL.createObjectURL(b);+ // XXX we never revoke this!+ var audio = new Audio;+ audio.addEventListener("canplaythrough", () => finish(audio));+ // use addEventListener due to chromium bug 124926+ audio.onerror = event => {+ if (done) return;+ err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`);+ function encode64(data) {+ var BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ var PAD = "=";+ var ret = "";+ var leftchar = 0;+ var leftbits = 0;+ for (var byte of data) {+ leftchar = (leftchar << 8) | byte;+ leftbits += 8;+ while (leftbits >= 6) {+ var curr = (leftchar >> (leftbits - 6)) & 63;+ leftbits -= 6;+ ret += BASE[curr];+ }+ }+ if (leftbits == 2) {+ ret += BASE[(leftchar & 3) << 4];+ ret += PAD + PAD;+ } else if (leftbits == 4) {+ ret += BASE[(leftchar & 15) << 2];+ ret += PAD;+ }+ return ret;+ }+ audio.src = "data:audio/x-" + name.slice(-3) + ";base64," + encode64(byteArray);+ finish(audio);+ };+ audio.src = url;+ // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror+ safeSetTimeout(() => {+ finish(audio);+ }, 1e4);+ });+ preloadPlugins.push(audioPlugin);+ // Canvas event setup+ function pointerLockChange() {+ var canvas = Browser.getCanvas();+ Browser.pointerLock = document.pointerLockElement === canvas;+ }+ var canvas = Browser.getCanvas();+ if (canvas) {+ // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module+ // Module['forcedAspectRatio'] = 4 / 3;+ document.addEventListener("pointerlockchange", pointerLockChange);+ if (Module["elementPointerLock"]) {+ canvas.addEventListener("click", ev => {+ if (!Browser.pointerLock && Browser.getCanvas().requestPointerLock) {+ Browser.getCanvas().requestPointerLock();+ ev.preventDefault();+ }+ });+ }+ }+ },+ createContext(/** @type {HTMLCanvasElement} */ canvas, useWebGL, setInModule, webGLContextAttributes) {+ if (useWebGL && Module["ctx"] && canvas == Browser.getCanvas()) return Module["ctx"];+ // no need to recreate GL context if it's already been created for this canvas.+ var ctx;+ var contextHandle;+ if (useWebGL) {+ // For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults.+ var contextAttributes = {+ antialias: false,+ alpha: false,+ majorVersion: (typeof WebGL2RenderingContext != "undefined") ? 2 : 1+ };+ if (webGLContextAttributes) {+ for (var attribute in webGLContextAttributes) {+ contextAttributes[attribute] = webGLContextAttributes[attribute];+ }+ }+ // This check of existence of GL is here to satisfy Closure compiler, which yells if variable GL is referenced below but GL object is not+ // actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function+ // Browser.createContext() should not even be emitted.+ if (typeof GL != "undefined") {+ contextHandle = GL.createContext(canvas, contextAttributes);+ if (contextHandle) {+ ctx = GL.getContext(contextHandle).GLctx;+ }+ }+ } else {+ ctx = canvas.getContext("2d");+ }+ if (!ctx) return null;+ if (setInModule) {+ Module["ctx"] = ctx;+ if (useWebGL) GL.makeContextCurrent(contextHandle);+ Browser.useWebGL = useWebGL;+ Browser.moduleContextCreatedCallbacks.forEach(callback => callback());+ Browser.init();+ }+ return ctx;+ },+ fullscreenHandlersInstalled: false,+ lockPointer: undefined,+ resizeCanvas: undefined,+ requestFullscreen(lockPointer, resizeCanvas) {+ Browser.lockPointer = lockPointer;+ Browser.resizeCanvas = resizeCanvas;+ if (typeof Browser.lockPointer == "undefined") Browser.lockPointer = true;+ if (typeof Browser.resizeCanvas == "undefined") Browser.resizeCanvas = false;+ var canvas = Browser.getCanvas();+ function fullscreenChange() {+ Browser.isFullscreen = false;+ var canvasContainer = canvas.parentNode;+ if (getFullscreenElement() === canvasContainer) {+ canvas.exitFullscreen = Browser.exitFullscreen;+ if (Browser.lockPointer) canvas.requestPointerLock();+ Browser.isFullscreen = true;+ if (Browser.resizeCanvas) {+ Browser.setFullscreenCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ } else {+ // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen+ canvasContainer.parentNode.insertBefore(canvas, canvasContainer);+ canvasContainer.parentNode.removeChild(canvasContainer);+ if (Browser.resizeCanvas) {+ Browser.setWindowedCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ }+ }+ if (!Browser.fullscreenHandlersInstalled) {+ Browser.fullscreenHandlersInstalled = true;+ document.addEventListener("fullscreenchange", fullscreenChange);+ document.addEventListener("webkitfullscreenchange", fullscreenChange);+ }+ // create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root+ var canvasContainer = document.createElement("div");+ canvas.parentNode.insertBefore(canvasContainer, canvas);+ canvasContainer.appendChild(canvas);+ // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)+ // Safari didn't support Element.requestFullscreen until 16.4+ // See: https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen+ /** @suppress {checkTypes} */ canvasContainer.requestFullscreen ??= (canvasContainer["webkitRequestFullscreen"] ? () => canvasContainer["webkitRequestFullscreen"](Element.ALLOW_KEYBOARD_INPUT) : null) ?? (canvasContainer["webkitRequestFullScreen"] ? () => canvasContainer["webkitRequestFullScreen"](Element.ALLOW_KEYBOARD_INPUT) : null);+ canvasContainer.requestFullscreen();+ },+ exitFullscreen() {+ // This is workaround for chrome. Trying to exit from fullscreen+ // not in fullscreen state will cause 'TypeError: Document not active'+ // in chrome. See https://github.com/emscripten-core/emscripten/pull/8236+ if (!Browser.isFullscreen) {+ return false;+ }+ var CFS = document.exitFullscreen ?? document["webkitCancelFullScreen"];+ CFS.apply(document, []);+ return true;+ },+ safeSetTimeout(func, timeout) {+ // Legacy function, this is used by the SDL2 port so we need to keep it+ // around at least until that is updated.+ // See https://github.com/libsdl-org/SDL/pull/6304+ return safeSetTimeout(func, timeout);+ },+ getMimetype(name) {+ return {+ "jpg": "image/jpeg",+ "jpeg": "image/jpeg",+ "png": "image/png",+ "bmp": "image/bmp",+ "ogg": "audio/ogg",+ "wav": "audio/wav",+ "mp3": "audio/mpeg"+ }[name.slice(name.lastIndexOf(".") + 1)];+ },+ getUserMedia(func) {+ return navigator.mediaDevices.getUserMedia(func);+ },+ getMouseWheelDelta(event) {+ var delta = 0;+ switch (event.type) {+ case "DOMMouseScroll":+ // 3 lines make up a step+ delta = event.detail / 3;+ break;++ case "mousewheel":+ // 120 units make up a step+ delta = event.wheelDelta / 120;+ break;++ case "wheel":+ delta = event.deltaY;+ switch (event.deltaMode) {+ case 0:+ // DOM_DELTA_PIXEL: 100 pixels make up a step+ delta /= 100;+ break;++ case 1:+ // DOM_DELTA_LINE: 3 lines make up a step+ delta /= 3;+ break;++ case 2:+ // DOM_DELTA_PAGE: A page makes up 80 steps+ delta *= 80;+ break;++ default:+ abort("unrecognized mouse wheel delta mode: " + event.deltaMode);+ }+ break;++ default:+ abort("unrecognized mouse wheel event: " + event.type);+ }+ return delta;+ },+ mouseX: 0,+ mouseY: 0,+ mouseMovementX: 0,+ mouseMovementY: 0,+ touches: {},+ lastTouches: {},+ calculateMouseCoords(pageX, pageY) {+ // Calculate the movement based on the changes+ // in the coordinates.+ var canvas = Browser.getCanvas();+ var rect = canvas.getBoundingClientRect();+ var adjustedX = pageX - (window.scrollX + rect.left);+ var adjustedY = pageY - (window.scrollY + rect.top);+ // the canvas might be CSS-scaled compared to its backbuffer;+ // SDL-using content will want mouse coordinates in terms+ // of backbuffer units.+ adjustedX = adjustedX * (canvas.width / rect.width);+ adjustedY = adjustedY * (canvas.height / rect.height);+ return {+ x: adjustedX,+ y: adjustedY+ };+ },+ setMouseCoords(pageX, pageY) {+ const {x, y} = Browser.calculateMouseCoords(pageX, pageY);+ Browser.mouseMovementX = x - Browser.mouseX;+ Browser.mouseMovementY = y - Browser.mouseY;+ Browser.mouseX = x;+ Browser.mouseY = y;+ },+ calculateMouseEvent(event) {+ // event should be mousemove, mousedown or mouseup+ if (Browser.pointerLock) {+ // When the pointer is locked, calculate the coordinates+ // based on the movement of the mouse.+ Browser.mouseMovementX = event.movementX;+ Browser.mouseMovementY = event.movementY;+ // add the mouse delta to the current absolute mouse position+ Browser.mouseX += Browser.mouseMovementX;+ Browser.mouseY += Browser.mouseMovementY;+ } else {+ if (event.type === "touchstart" || event.type === "touchend" || event.type === "touchmove") {+ var touch = event.touch;+ if (touch === undefined) {+ return;+ }+ var coords = Browser.calculateMouseCoords(touch.pageX, touch.pageY);+ if (event.type === "touchstart") {+ Browser.lastTouches[touch.identifier] = coords;+ Browser.touches[touch.identifier] = coords;+ } else if (event.type === "touchend" || event.type === "touchmove") {+ var last = Browser.touches[touch.identifier];+ last ||= coords;+ Browser.lastTouches[touch.identifier] = last;+ Browser.touches[touch.identifier] = coords;+ }+ return;+ }+ Browser.setMouseCoords(event.pageX, event.pageY);+ }+ },+ resizeListeners: [],+ updateResizeListeners() {+ var canvas = Browser.getCanvas();+ Browser.resizeListeners.forEach(listener => listener(canvas.width, canvas.height));+ },+ setCanvasSize(width, height, noUpdates) {+ var canvas = Browser.getCanvas();+ Browser.updateCanvasDimensions(canvas, width, height);+ if (!noUpdates) Browser.updateResizeListeners();+ },+ windowedWidth: 0,+ windowedHeight: 0,+ setFullscreenCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags | 8388608;+ // set SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ setWindowedCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags & ~8388608;+ // clear SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ updateCanvasDimensions(canvas, wNative, hNative) {+ if (wNative && hNative) {+ canvas.widthNative = wNative;+ canvas.heightNative = hNative;+ } else {+ wNative = canvas.widthNative;+ hNative = canvas.heightNative;+ }+ var w = wNative;+ var h = hNative;+ if ((getFullscreenElement() === canvas.parentNode) && (typeof screen != "undefined")) {+ var factor = Math.min(screen.width / w, screen.height / h);+ w = Math.round(w * factor);+ h = Math.round(h * factor);+ }+ if (Browser.resizeCanvas) {+ if (canvas.width != w) canvas.width = w;+ if (canvas.height != h) canvas.height = h;+ if (typeof canvas.style != "undefined") {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ } else {+ if (canvas.width != wNative) canvas.width = wNative;+ if (canvas.height != hNative) canvas.height = hNative;+ if (typeof canvas.style != "undefined") {+ if (w != wNative || h != hNative) {+ canvas.style.setProperty("width", w + "px", "important");+ canvas.style.setProperty("height", h + "px", "important");+ } else {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ }+ }+ }+};++/** @type {!Int8Array} */ var HEAP8;++var callRuntimeCallbacks = callbacks => {+ while (callbacks.length > 0) {+ // Pass the module as the first argument.+ callbacks.shift()(Module);+ }+};++var onPostRuns = [];++var onPreRuns = [];++var noExitRuntime = true;++var stackRestore = val => __emscripten_stack_restore(val);++var stackSave = () => _emscripten_stack_get_current();++class ExceptionInfo {+ // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it.+ constructor(excPtr) {+ this.excPtr = excPtr;+ this.ptr = excPtr - 24;+ }+ set_type(type) {+ HEAPU32[(((this.ptr) + (4)) >> 2)] = type;+ }+ get_type() {+ return HEAPU32[(((this.ptr) + (4)) >> 2)];+ }+ set_destructor(destructor) {+ HEAPU32[(((this.ptr) + (8)) >> 2)] = destructor;+ }+ get_destructor() {+ return HEAPU32[(((this.ptr) + (8)) >> 2)];+ }+ set_caught(caught) {+ caught = caught ? 1 : 0;+ HEAP8[(this.ptr) + (12)] = caught;+ }+ get_caught() {+ return HEAP8[(this.ptr) + (12)] != 0;+ }+ set_rethrown(rethrown) {+ rethrown = rethrown ? 1 : 0;+ HEAP8[(this.ptr) + (13)] = rethrown;+ }+ get_rethrown() {+ return HEAP8[(this.ptr) + (13)] != 0;+ }+ // Initialize native structure fields. Should be called once after allocated.+ init(type, destructor) {+ this.set_adjusted_ptr(0);+ this.set_type(type);+ this.set_destructor(destructor);+ }+ set_adjusted_ptr(adjustedPtr) {+ HEAPU32[(((this.ptr) + (16)) >> 2)] = adjustedPtr;+ }+ get_adjusted_ptr() {+ return HEAPU32[(((this.ptr) + (16)) >> 2)];+ }+}++var uncaughtExceptionCount = 0;++var __Unwind_RaiseException = ex => {+ abort();+};++var ___cxa_throw = (ptr, type, destructor) => {+ var info = new ExceptionInfo(ptr);+ // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.+ info.init(type, destructor);+ uncaughtExceptionCount++;+ __Unwind_RaiseException(ptr);+};++var PATH = {+ isAbs: path => path.charAt(0) === "/",+ splitPath: filename => {+ var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;+ return splitPathRe.exec(filename).slice(1);+ },+ normalizeArray: (parts, allowAboveRoot) => {+ // if the path tries to go above the root, `up` ends up > 0+ var up = 0;+ for (var i = parts.length - 1; i >= 0; i--) {+ var last = parts[i];+ if (last === ".") {+ parts.splice(i, 1);+ } else if (last === "..") {+ parts.splice(i, 1);+ up++;+ } else if (up) {+ parts.splice(i, 1);+ up--;+ }+ }+ // if the path is allowed to go above the root, restore leading ..s+ if (allowAboveRoot) {+ for (;up; up--) {+ parts.unshift("..");+ }+ }+ return parts;+ },+ normalize: path => {+ var isAbsolute = PATH.isAbs(path), trailingSlash = path.slice(-1) === "/";+ // Normalize the path+ path = PATH.normalizeArray(path.split("/").filter(p => !!p), !isAbsolute).join("/");+ if (!path && !isAbsolute) {+ path = ".";+ }+ if (path && trailingSlash) {+ path += "/";+ }+ return (isAbsolute ? "/" : "") + path;+ },+ dirname: path => {+ var result = PATH.splitPath(path), root = result[0], dir = result[1];+ if (!root && !dir) {+ // No dirname whatsoever+ return ".";+ }+ if (dir) {+ // It has a dirname, strip trailing slash+ dir = dir.slice(0, -1);+ }+ return root + dir;+ },+ basename: path => path && path.match(/([^\/]+|\/)\/*$/)[1],+ join: (...paths) => PATH.normalize(paths.join("/")),+ join2: (l, r) => PATH.normalize(l + "/" + r)+};++var initRandomFill = () => {+ // This block is not needed on v19+ since crypto.getRandomValues is builtin+ if (ENVIRONMENT_IS_NODE) {+ var nodeCrypto = require("node:crypto");+ return view => (nodeCrypto.randomFillSync(view), 0);+ }+ return view => (crypto.getRandomValues(view), 0);+};++var randomFill = view => (randomFill = initRandomFill())(view);++var PATH_FS = {+ resolve: (...args) => {+ var resolvedPath = "", resolvedAbsolute = false;+ for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {+ var path = (i >= 0) ? args[i] : FS.cwd();+ // Skip empty and invalid entries+ if (typeof path != "string") {+ throw new TypeError("Arguments to path.resolve must be strings");+ } else if (!path) {+ return "";+ }+ resolvedPath = path + "/" + resolvedPath;+ resolvedAbsolute = PATH.isAbs(path);+ }+ // At this point the path should be resolved to a full absolute path, but+ // handle relative paths to be safe (might happen when process.cwd() fails)+ resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(p => !!p), !resolvedAbsolute).join("/");+ return ((resolvedAbsolute ? "/" : "") + resolvedPath) || ".";+ },+ relative: (from, to) => {+ from = PATH_FS.resolve(from).slice(1);+ to = PATH_FS.resolve(to).slice(1);+ function trim(arr) {+ var start = 0;+ for (;start < arr.length; start++) {+ if (arr[start] !== "") break;+ }+ var end = arr.length - 1;+ for (;end >= 0; end--) {+ if (arr[end] !== "") break;+ }+ if (start > end) return [];+ return arr.slice(start, end - start + 1);+ }+ var fromParts = trim(from.split("/"));+ var toParts = trim(to.split("/"));+ var length = Math.min(fromParts.length, toParts.length);+ var samePartsLength = length;+ for (var i = 0; i < length; i++) {+ if (fromParts[i] !== toParts[i]) {+ samePartsLength = i;+ break;+ }+ }+ var outputParts = [];+ for (var i = samePartsLength; i < fromParts.length; i++) {+ outputParts.push("..");+ }+ outputParts = outputParts.concat(toParts.slice(samePartsLength));+ return outputParts.join("/");+ }+};++var UTF8Decoder = new TextDecoder;++/**+ * heapOrArray is either a regular array, or a JavaScript typed array view.+ * @param {number} idx+ * @param {number=} maxBytesToRead+ * @param {boolean=} ignoreNul+ * @return {number}+ */ var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {+ var maxIdx = idx + maxBytesToRead;+ if (ignoreNul) return maxIdx;+ // TextDecoder needs to know the byte length in advance, it doesn't stop on+ // null terminator by itself.+ // As a tiny code save trick, compare idx against maxIdx using a negation,+ // so that maxBytesToRead=undefined/NaN means Infinity.+ while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;+ return idx;+};++/**+ * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given+ * array that contains uint8 values, returns a copy of that string as a+ * Javascript String object.+ * heapOrArray is either a regular array, or a JavaScript typed array view.+ * @param {number=} idx+ * @param {number=} maxBytesToRead+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(heapOrArray.buffer ? heapOrArray.subarray(idx, endPtr) : new Uint8Array(heapOrArray.slice(idx, endPtr)));+};++var FS_stdin_getChar_buffer = [];++var lengthBytesUTF8 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code+ // unit, not a Unicode code point of the character! So decode+ // UTF16->UTF32->UTF8.+ // See http://unicode.org/faq/utf_bom.html#utf16-3+ var c = str.charCodeAt(i);+ // possibly a lead surrogate+ if (c <= 127) {+ len++;+ } else if (c <= 2047) {+ len += 2;+ } else if (c >= 55296 && c <= 57343) {+ len += 4;+ ++i;+ } else {+ len += 3;+ }+ }+ return len;+};++var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {+ // Parameter maxBytesToWrite is not optional. Negative values, 0, null,+ // undefined and false each don't write out any bytes.+ if (!(maxBytesToWrite > 0)) return 0;+ var startIdx = outIdx;+ var endIdx = outIdx + maxBytesToWrite - 1;+ // -1 for string null terminator.+ for (var i = 0; i < str.length; ++i) {+ // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description+ // and https://www.ietf.org/rfc/rfc2279.txt+ // and https://tools.ietf.org/html/rfc3629+ var u = str.codePointAt(i);+ if (u <= 127) {+ if (outIdx >= endIdx) break;+ heap[outIdx++] = u;+ } else if (u <= 2047) {+ if (outIdx + 1 >= endIdx) break;+ heap[outIdx++] = 192 | (u >> 6);+ heap[outIdx++] = 128 | (u & 63);+ } else if (u <= 65535) {+ if (outIdx + 2 >= endIdx) break;+ heap[outIdx++] = 224 | (u >> 12);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ } else {+ if (outIdx + 3 >= endIdx) break;+ heap[outIdx++] = 240 | (u >> 18);+ heap[outIdx++] = 128 | ((u >> 12) & 63);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ i++;+ }+ }+ // Null-terminate the pointer to the buffer.+ heap[outIdx] = 0;+ return outIdx - startIdx;+};++/** @type {function(string, boolean=, number=)} */ var intArrayFromString = (stringy, dontAddNull, length) => {+ var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;+ var u8array = new Array(len);+ var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);+ if (dontAddNull) u8array.length = numBytesWritten;+ return u8array;+};++var FS_stdin_getChar = () => {+ if (!FS_stdin_getChar_buffer.length) {+ var result = null;+ if (ENVIRONMENT_IS_NODE) {+ // we will read data by chunks of BUFSIZE+ var BUFSIZE = 256;+ var buf = Buffer.alloc(BUFSIZE);+ var bytesRead = 0;+ // For some reason we must suppress a closure warning here, even though+ // fd definitely exists on process.stdin, and is even the proper way to+ // get the fd of stdin,+ // https://github.com/nodejs/help/issues/2136#issuecomment-523649904+ // This started to happen after moving this logic out of library_tty.js,+ // so it is related to the surrounding code in some unclear manner.+ /** @suppress {missingProperties} */ var fd = process.stdin.fd;+ try {+ bytesRead = fs.readSync(fd, buf, 0, BUFSIZE);+ } catch (e) {+ // Cross-platform differences: on Windows, reading EOF throws an+ // exception, but on other OSes, reading EOF returns 0. Uniformize+ // behavior by treating the EOF exception to return 0.+ if (e.toString().includes("EOF")) bytesRead = 0; else throw e;+ }+ if (bytesRead > 0) {+ result = buf.slice(0, bytesRead).toString("utf-8");+ }+ } else if (globalThis.window?.prompt) {+ // Browser.+ result = window.prompt("Input: ");+ // returns null on cancel+ if (result !== null) {+ result += "\n";+ }+ } else {}+ if (!result) {+ return null;+ }+ FS_stdin_getChar_buffer = intArrayFromString(result, true);+ }+ return FS_stdin_getChar_buffer.shift();+};++var TTY = {+ ttys: [],+ init() {},+ shutdown() {},+ register(dev, ops) {+ TTY.ttys[dev] = {+ input: [],+ output: [],+ ops+ };+ FS.registerDevice(dev, TTY.stream_ops);+ },+ stream_ops: {+ open(stream) {+ var tty = TTY.ttys[stream.node.rdev];+ if (!tty) {+ throw new FS.ErrnoError(43);+ }+ stream.tty = tty;+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ stream.tty.ops.fsync(stream.tty);+ },+ fsync(stream) {+ stream.tty.ops.fsync(stream.tty);+ },+ read(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.get_char) {+ throw new FS.ErrnoError(60);+ }+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = stream.tty.ops.get_char(stream.tty);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && !bytesRead) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ // We currently only support canonical mode (ICANON), where+ // read(2) returns as soon as a line delimiter is read.+ if (result === 10) break;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.put_char) {+ throw new FS.ErrnoError(60);+ }+ try {+ for (var i = 0; i < length; i++) {+ stream.tty.ops.put_char(stream.tty, buffer[offset + i]);+ }+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ },+ default_tty_ops: {+ get_char(tty) {+ return FS_stdin_getChar();+ },+ put_char(tty, val) {+ if (val === null || val === 10) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ },+ ioctl_tcgets(tty) {+ // typical setting+ return {+ c_iflag: 25856,+ c_oflag: 5,+ c_cflag: 191,+ c_lflag: 35387,+ c_cc: [ 3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]+ };+ },+ ioctl_tcsets(tty, optional_actions, data) {+ // currently just ignore+ return 0;+ },+ ioctl_tiocgwinsz(tty) {+ return [ 24, 80 ];+ }+ },+ default_tty1_ops: {+ put_char(tty, val) {+ if (val === null || val === 10) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ }+ }+};++/** @type {!Uint8Array} */ var HEAPU8;++var zeroMemory = (ptr, size) => HEAPU8.fill(0, ptr, ptr + size);++var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;++var mmapAlloc = size => {+ size = alignMemory(size, 65536);+ var ptr = _emscripten_builtin_memalign(65536, size);+ if (ptr) zeroMemory(ptr, size);+ return ptr;+};++var MEMFS = {+ ops_table: null,+ mount(mount) {+ return MEMFS.createNode(null, "/", 16895, 0);+ },+ createNode(parent, name, mode, dev) {+ if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {+ // not supported+ throw new FS.ErrnoError(63);+ }+ MEMFS.ops_table ||= {+ dir: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ lookup: MEMFS.node_ops.lookup,+ mknod: MEMFS.node_ops.mknod,+ rename: MEMFS.node_ops.rename,+ unlink: MEMFS.node_ops.unlink,+ rmdir: MEMFS.node_ops.rmdir,+ readdir: MEMFS.node_ops.readdir,+ symlink: MEMFS.node_ops.symlink+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek+ }+ },+ file: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek,+ read: MEMFS.stream_ops.read,+ write: MEMFS.stream_ops.write,+ mmap: MEMFS.stream_ops.mmap,+ msync: MEMFS.stream_ops.msync+ }+ },+ link: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ readlink: MEMFS.node_ops.readlink+ },+ stream: {}+ },+ chrdev: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: FS.chrdev_stream_ops+ }+ };+ var node = FS.createNode(parent, name, mode, dev);+ if (FS.isDir(node.mode)) {+ node.node_ops = MEMFS.ops_table.dir.node;+ node.stream_ops = MEMFS.ops_table.dir.stream;+ node.contents = {};+ } else if (FS.isFile(node.mode)) {+ node.node_ops = MEMFS.ops_table.file.node;+ node.stream_ops = MEMFS.ops_table.file.stream;+ // The actual number of bytes used in the typed array, as opposed to+ // contents.length which gives the whole capacity.+ node.usedBytes = 0;+ // The byte data of the file is stored in a typed array.+ // Note: typed arrays are not resizable like normal JS arrays are, so+ // there is a small penalty involved for appending file writes that+ // continuously grow a file similar to std::vector capacity vs used.+ node.contents = MEMFS.emptyFileContents ??= new Uint8Array(0);+ } else if (FS.isLink(node.mode)) {+ node.node_ops = MEMFS.ops_table.link.node;+ node.stream_ops = MEMFS.ops_table.link.stream;+ } else if (FS.isChrdev(node.mode)) {+ node.node_ops = MEMFS.ops_table.chrdev.node;+ node.stream_ops = MEMFS.ops_table.chrdev.stream;+ }+ node.atime = node.mtime = node.ctime = Date.now();+ // add the new node to the parent+ if (parent) {+ parent.contents[name] = node;+ parent.atime = parent.mtime = parent.ctime = node.atime;+ }+ return node;+ },+ getFileDataAsTypedArray(node) {+ return node.contents.subarray(0, node.usedBytes);+ },+ expandFileStorage(node, newCapacity) {+ var prevCapacity = node.contents.length;+ if (prevCapacity >= newCapacity) return;+ // No need to expand, the storage was already large enough.+ // Don't expand strictly to the given requested limit if it's only a very+ // small increase, but instead geometrically grow capacity.+ // For small filesizes (<1MB), perform size*2 geometric increase, but for+ // large sizes, do a much more conservative size*1.125 increase to avoid+ // overshooting the allocation cap by a very large margin.+ var CAPACITY_DOUBLING_MAX = 1024 * 1024;+ newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> 0);+ if (prevCapacity) newCapacity = Math.max(newCapacity, 256);+ // At minimum allocate 256b for each file when expanding.+ var oldContents = MEMFS.getFileDataAsTypedArray(node);+ node.contents = new Uint8Array(newCapacity);+ // Allocate new storage.+ node.contents.set(oldContents);+ },+ resizeFileStorage(node, newSize) {+ if (node.usedBytes == newSize) return;+ var oldContents = node.contents;+ node.contents = new Uint8Array(newSize);+ // Allocate new storage.+ node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));+ // Copy old data over to the new storage.+ node.usedBytes = newSize;+ },+ node_ops: {+ getattr(node) {+ var attr = {};+ // device numbers reuse inode numbers.+ attr.dev = FS.isChrdev(node.mode) ? node.id : 1;+ attr.ino = node.id;+ attr.mode = node.mode;+ attr.nlink = 1;+ attr.uid = 0;+ attr.gid = 0;+ attr.rdev = node.rdev;+ if (FS.isDir(node.mode)) {+ attr.size = 4096;+ } else if (FS.isFile(node.mode)) {+ attr.size = node.usedBytes;+ } else if (FS.isLink(node.mode)) {+ attr.size = node.link.length;+ } else {+ attr.size = 0;+ }+ attr.atime = new Date(node.atime);+ attr.mtime = new Date(node.mtime);+ attr.ctime = new Date(node.ctime);+ // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),+ // but this is not required by the standard.+ attr.blksize = 4096;+ attr.blocks = Math.ceil(attr.size / attr.blksize);+ return attr;+ },+ setattr(node, attr) {+ for (const key of [ "mode", "atime", "mtime", "ctime" ]) {+ if (attr[key] != null) {+ node[key] = attr[key];+ }+ }+ if (attr.size !== undefined) {+ MEMFS.resizeFileStorage(node, attr.size);+ }+ },+ lookup(parent, name) {+ // This error may happen quite a bit. To avoid overhead we reuse it (and+ // suffer a lack of stack info).+ if (!MEMFS.doesNotExistError) {+ MEMFS.doesNotExistError = new FS.ErrnoError(44);+ /** @suppress {checkTypes} */ MEMFS.doesNotExistError.stack = "<generic error, no stack>";+ }+ throw MEMFS.doesNotExistError;+ },+ mknod(parent, name, mode, dev) {+ return MEMFS.createNode(parent, name, mode, dev);+ },+ rename(old_node, new_dir, new_name) {+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ if (new_node) {+ if (FS.isDir(old_node.mode)) {+ // if we're overwriting a directory at new_name, make sure it's empty.+ for (var i in new_node.contents) {+ throw new FS.ErrnoError(55);+ }+ }+ FS.hashRemoveNode(new_node);+ }+ // do the internal rewiring+ delete old_node.parent.contents[old_node.name];+ new_dir.contents[new_name] = old_node;+ old_node.name = new_name;+ new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now();+ },+ unlink(parent, name) {+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ rmdir(parent, name) {+ var node = FS.lookupNode(parent, name);+ for (var i in node.contents) {+ throw new FS.ErrnoError(55);+ }+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ readdir(node) {+ return [ ".", "..", ...Object.keys(node.contents) ];+ },+ symlink(parent, newname, oldpath) {+ var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);+ node.link = oldpath;+ return node;+ },+ readlink(node) {+ if (!FS.isLink(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ return node.link;+ }+ },+ stream_ops: {+ read(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= stream.node.usedBytes) return 0;+ var size = Math.min(stream.node.usedBytes - position, length);+ buffer.set(contents.subarray(position, position + size), offset);+ return size;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ // If the buffer is located in main memory (HEAP), and if+ // memory can grow, we can't hold on to references of the+ // memory buffer, as they may get invalidated. That means we+ // need to copy its contents.+ if (buffer.buffer === HEAP8.buffer) {+ canOwn = false;+ }+ if (!length) return 0;+ var node = stream.node;+ node.mtime = node.ctime = Date.now();+ if (canOwn) {+ node.contents = buffer.subarray(offset, offset + length);+ node.usedBytes = length;+ } else if (!node.usedBytes && !position) {+ // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.+ node.contents = buffer.slice(offset, offset + length);+ node.usedBytes = length;+ } else {+ MEMFS.expandFileStorage(node, position + length);+ // Use typed array write which is available.+ node.contents.set(buffer.subarray(offset, offset + length), position);+ node.usedBytes = Math.max(node.usedBytes, position + length);+ }+ return length;+ },+ llseek(stream, offset, whence) {+ var position = offset;+ if (whence === 1) {+ position += stream.position;+ } else if (whence === 2) {+ if (FS.isFile(stream.node.mode)) {+ position += stream.node.usedBytes;+ }+ }+ if (position < 0) {+ throw new FS.ErrnoError(28);+ }+ return position;+ },+ mmap(stream, length, position, prot, flags) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ var ptr;+ var allocated;+ var contents = stream.node.contents;+ // Only make a new copy when MAP_PRIVATE is specified.+ if (!(flags & 2) && contents.buffer === HEAP8.buffer) {+ // We can't emulate MAP_SHARED when the file is not backed by the+ // buffer we're mapping to (e.g. the HEAP buffer).+ allocated = false;+ ptr = contents.byteOffset;+ } else {+ allocated = true;+ ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ if (contents) {+ // Try to avoid unnecessary slices.+ if (position > 0 || position + length < contents.length) {+ if (contents.subarray) {+ contents = contents.subarray(position, position + length);+ } else {+ contents = Array.prototype.slice.call(contents, position, position + length);+ }+ }+ HEAP8.set(contents, ptr);+ }+ }+ return {+ ptr,+ allocated+ };+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);+ // should we check if bytesWritten and length are the same?+ return 0;+ }+ }+};++var FS_modeStringToFlags = str => {+ if (typeof str != "string") return str;+ var flagModes = {+ "r": 0,+ "r+": 2,+ "w": 512 | 64 | 1,+ "w+": 512 | 64 | 2,+ "a": 1024 | 64 | 1,+ "a+": 1024 | 64 | 2+ };+ var flags = flagModes[str];+ if (typeof flags == "undefined") {+ throw new Error(`Unknown file open mode: ${str}`);+ }+ return flags;+};++var FS_fileDataToTypedArray = data => {+ if (typeof data == "string") {+ data = intArrayFromString(data, true);+ }+ if (!data.subarray) {+ data = new Uint8Array(data);+ }+ return data;+};++var FS_getMode = (canRead, canWrite) => {+ var mode = 0;+ if (canRead) mode |= 292 | 73;+ if (canWrite) mode |= 146;+ return mode;+};++var asyncLoad = async url => {+ var arrayBuffer = await readAsync(url);+ return new Uint8Array(arrayBuffer);+};++var FS_createDataFile = (...args) => FS.createDataFile(...args);++var getUniqueRunDependency = id => id;++var dependenciesPromise = null;++var resolveRunDependencies = async () => dependenciesPromise;++var runDependencies = 0;++var dependenciesPromiseResolve = null;++var removeRunDependency = id => {+ runDependencies--;+ Module["monitorRunDependencies"]?.(runDependencies);+ if (!runDependencies) {+ dependenciesPromiseResolve();+ }+};++var addRunDependency = id => {+ if (!runDependencies) {+ dependenciesPromise = new Promise(resolve => dependenciesPromiseResolve = resolve);+ }+ runDependencies++;+ Module["monitorRunDependencies"]?.(runDependencies);+};++var FS_handledByPreloadPlugin = async (byteArray, fullname) => {+ // Ensure plugins are ready.+ if (typeof Browser != "undefined") Browser.init();+ for (var plugin of preloadPlugins) {+ if (plugin["canHandle"](fullname)) {+ return plugin["handle"](byteArray, fullname);+ }+ }+ // If no plugin handled this file then return the original/unmodified+ // byteArray.+ return byteArray;+};++var FS_preloadFile = async (parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish) => {+ // TODO we should allow people to just pass in a complete filename instead+ // of parent and name being that we just join them anyways+ var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;+ var dep = getUniqueRunDependency(`cp ${fullname}`);+ // might have several active requests for the same fullname+ addRunDependency(dep);+ try {+ var byteArray = url;+ if (typeof url == "string") {+ byteArray = await asyncLoad(url);+ }+ byteArray = await FS_handledByPreloadPlugin(byteArray, fullname);+ preFinish?.();+ if (!dontCreateFile) {+ FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);+ }+ } finally {+ removeRunDependency(dep);+ }+};++var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {+ FS_preloadFile(parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish).then(onload).catch(onerror);+};++var FS = {+ root: null,+ mounts: [],+ devices: {},+ streams: [],+ nextInode: 1,+ nameTable: null,+ currentPath: "/",+ initialized: false,+ ignorePermissions: true,+ filesystems: null,+ syncFSRequests: 0,+ ErrnoError: class {+ name="ErrnoError";+ // We set the `name` property to be able to identify `FS.ErrnoError`+ // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.+ // - when using PROXYFS, an error can come from an underlying FS+ // as different FS objects have their own FS.ErrnoError each,+ // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs.+ // we'll use the reliable test `err.name == "ErrnoError"` instead+ constructor(errno) {+ this.errno = errno;+ }+ },+ FSStream: class {+ shared={};+ get object() {+ return this.node;+ }+ set object(val) {+ this.node = val;+ }+ get isRead() {+ return (this.flags & 2097155) !== 1;+ }+ get isWrite() {+ return (this.flags & 2097155) !== 0;+ }+ get isAppend() {+ return (this.flags & 1024);+ }+ get flags() {+ return this.shared.flags;+ }+ set flags(val) {+ this.shared.flags = val;+ }+ get position() {+ return this.shared.position;+ }+ set position(val) {+ this.shared.position = val;+ }+ },+ FSNode: class {+ node_ops={};+ stream_ops={};+ readMode=292 | 73;+ writeMode=146;+ mounted=null;+ constructor(parent, name, mode, rdev) {+ if (!parent) {+ parent = this;+ }+ this.parent = parent;+ this.mount = parent.mount;+ this.id = FS.nextInode++;+ this.name = name;+ this.mode = mode;+ this.rdev = rdev;+ this.atime = this.mtime = this.ctime = Date.now();+ }+ get read() {+ return (this.mode & this.readMode) === this.readMode;+ }+ set read(val) {+ val ? this.mode |= this.readMode : this.mode &= ~this.readMode;+ }+ get write() {+ return (this.mode & this.writeMode) === this.writeMode;+ }+ set write(val) {+ val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;+ }+ get isFolder() {+ return FS.isDir(this.mode);+ }+ get isDevice() {+ return FS.isChrdev(this.mode);+ }+ // The per-inode readiness wait-queue. The node carries a Set of listener+ // entries {cb}; producers (SOCKFS, PIPEFS) call notifyListeners on a+ // readiness transition, and poll()/epoll consume it. It lives on the node+ // (not the fd) so dup'd fds share one queue. Only nodes that derive real+ // readiness (sockets, pipes, and an epoll's own node) ever use this -+ // always-ready types (regular files, ttys) never register or notify.+ addListener(cb, exclusive = false) {+ var entry = {+ cb,+ exclusive+ };+ var listeners = (this.listeners ??= new Set);+ listeners.add(entry);+ return {+ listeners,+ entry+ };+ }+ notifyListeners(flags) {+ // Iterates the set without copying, which is safe ONLY under a+ // load-bearing contract that every internal listener must honour:+ // 1. A listener must not run user code synchronously (a poll waiter only+ // resolves a Promise; an epoll registration only re-lists ++ // re-notifies; the epoll callback only schedules a tick). User code+ // runs on a later tick, never inside this loop.+ // 2. A listener may delete entries only from ITS OWN waiter, never from+ // a sibling node's set that may be mid-iteration. (Deleting an entry+ // of the set being iterated here is fine - a Set tolerates removal of+ // a not-yet-visited entry mid-iteration; mutating a *different* node's+ // set is fine because that set is not being iterated.)+ // Violating either gives silently skipped wakeups that are near-impossible+ // to reproduce. Any new producer/listener must preserve it.+ if (!this.listeners) return;+ // Fire every non-exclusive listener. Among EPOLLEXCLUSIVE registrations+ // (one fd watched by several epolls) wake only one, rotating round-robin+ // per node, to avoid a thundering herd. (Only epoll registrations are ever+ // exclusive; poll waiters and a node's own consumers are not.)+ var excl;+ for (var entry of this.listeners) {+ if (entry.exclusive) (excl ||= []).push(entry); else entry.cb(flags);+ }+ if (excl) {+ var i = (this.exclTurn || 0) % excl.length;+ this.exclTurn = i + 1;+ excl[i].cb(flags);+ }+ }+ },+ lookupPath(path, opts = {}) {+ if (!path) {+ throw new FS.ErrnoError(44);+ }+ opts.follow_mount ??= true;+ if (!PATH.isAbs(path)) {+ path = FS.cwd() + "/" + path;+ }+ // limit max consecutive symlinks to SYMLOOP_MAX.+ linkloop: for (var nlinks = 0; nlinks < 40; nlinks++) {+ // split the absolute path+ var parts = path.split("/").filter(p => !!p);+ // start at the root+ var current = FS.root;+ var current_path = "/";+ for (var i = 0; i < parts.length; i++) {+ var islast = (i === parts.length - 1);+ if (islast && opts.parent) {+ // stop resolving+ break;+ }+ if (parts[i] === ".") {+ continue;+ }+ if (parts[i] === "..") {+ current_path = PATH.dirname(current_path);+ if (FS.isRoot(current)) {+ path = current_path + "/" + parts.slice(i + 1).join("/");+ // We're making progress here, don't let many consecutive ..'s+ // lead to ELOOP+ nlinks--;+ continue linkloop;+ } else {+ current = current.parent;+ }+ continue;+ }+ current_path = PATH.join2(current_path, parts[i]);+ try {+ current = FS.lookupNode(current, parts[i]);+ } catch (e) {+ // if noent_okay is true, suppress a ENOENT in the last component+ // and return an object with an undefined node. This is needed for+ // resolving symlinks in the path when creating a file.+ if ((e?.errno === 44) && islast && opts.noent_okay) {+ return {+ path: current_path+ };+ }+ throw e;+ }+ // jump to the mount's root node if this is a mountpoint+ if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) {+ current = current.mounted.root;+ }+ // by default, lookupPath will not follow a symlink if it is the final path component.+ // setting opts.follow = true will override this behavior.+ if (FS.isLink(current.mode) && (!islast || opts.follow)) {+ if (!current.node_ops.readlink) {+ throw new FS.ErrnoError(52);+ }+ var link = current.node_ops.readlink(current);+ if (!PATH.isAbs(link)) {+ link = PATH.dirname(current_path) + "/" + link;+ }+ path = link + "/" + parts.slice(i + 1).join("/");+ continue linkloop;+ }+ }+ return {+ path: current_path,+ node: current+ };+ }+ throw new FS.ErrnoError(32);+ },+ getPath(node) {+ var path;+ while (true) {+ if (FS.isRoot(node)) {+ var mount = node.mount.mountpoint;+ if (!path) return mount;+ return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;+ }+ path = path ? `${node.name}/${path}` : node.name;+ node = node.parent;+ }+ },+ hashName(parentid, name) {+ var hash = 0;+ for (var i = 0; i < name.length; i++) {+ hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;+ }+ return ((parentid + hash) >>> 0) % FS.nameTable.length;+ },+ hashAddNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ node.name_next = FS.nameTable[hash];+ FS.nameTable[hash] = node;+ },+ hashRemoveNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ if (FS.nameTable[hash] === node) {+ FS.nameTable[hash] = node.name_next;+ } else {+ var current = FS.nameTable[hash];+ while (current) {+ if (current.name_next === node) {+ current.name_next = node.name_next;+ break;+ }+ current = current.name_next;+ }+ }+ },+ lookupNode(parent, name) {+ var errCode = FS.mayLookup(parent);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ var hash = FS.hashName(parent.id, name);+ for (var node = FS.nameTable[hash]; node; node = node.name_next) {+ var nodeName = node.name;+ if (node.parent.id === parent.id && nodeName === name) {+ return node;+ }+ }+ // if we failed to find it in the cache, call into the VFS+ return FS.lookup(parent, name);+ },+ createNode(parent, name, mode, rdev) {+ var node = new FS.FSNode(parent, name, mode, rdev);+ FS.hashAddNode(node);+ return node;+ },+ destroyNode(node) {+ FS.hashRemoveNode(node);+ },+ isRoot(node) {+ return node === node.parent;+ },+ isMountpoint(node) {+ return !!node.mounted;+ },+ isFile(mode) {+ return (mode & 61440) === 32768;+ },+ isDir(mode) {+ return (mode & 61440) === 16384;+ },+ isLink(mode) {+ return (mode & 61440) === 40960;+ },+ isChrdev(mode) {+ return (mode & 61440) === 8192;+ },+ isBlkdev(mode) {+ return (mode & 61440) === 24576;+ },+ isFIFO(mode) {+ return (mode & 61440) === 4096;+ },+ isSocket(mode) {+ return (mode & 49152) === 49152;+ },+ flagsToPermissionString(flag) {+ var perms = [ "r", "w", "rw" ][flag & 3];+ if ((flag & 512)) {+ perms += "w";+ }+ return perms;+ },+ nodePermissions(node, perms) {+ if (FS.ignorePermissions) {+ return 0;+ }+ // return 0 if any user, group or owner bits are set.+ if (perms.includes("r") && !(node.mode & 292)) {+ return 2;+ }+ if (perms.includes("w") && !(node.mode & 146)) {+ return 2;+ }+ if (perms.includes("x") && !(node.mode & 73)) {+ return 2;+ }+ return 0;+ },+ mayLookup(dir) {+ if (!FS.isDir(dir.mode)) return 54;+ var errCode = FS.nodePermissions(dir, "x");+ if (errCode) return errCode;+ if (!dir.node_ops.lookup) return 2;+ return 0;+ },+ mayCreate(dir, name) {+ if (!FS.isDir(dir.mode)) {+ return 54;+ }+ try {+ var node = FS.lookupNode(dir, name);+ return 20;+ } catch (e) {}+ return FS.nodePermissions(dir, "wx");+ },+ mayDelete(dir, name, isdir) {+ var node;+ try {+ node = FS.lookupNode(dir, name);+ } catch (e) {+ return e.errno;+ }+ var errCode = FS.nodePermissions(dir, "wx");+ if (errCode) {+ return errCode;+ }+ if (isdir) {+ if (!FS.isDir(node.mode)) {+ return 54;+ }+ if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {+ return 10;+ }+ } else if (FS.isDir(node.mode)) {+ return 31;+ }+ return 0;+ },+ mayOpen(node, flags) {+ if (!node) {+ return 44;+ }+ if (FS.isLink(node.mode)) {+ return 32;+ }+ var mode = FS.flagsToPermissionString(flags);+ if (FS.isDir(node.mode)) {+ // opening for write+ // TODO: check for O_SEARCH? (== search for dir only)+ if (mode !== "r" || (flags & (512 | 64))) {+ return 31;+ }+ }+ return FS.nodePermissions(node, mode);+ },+ checkOpExists(op, err) {+ if (!op) {+ throw new FS.ErrnoError(err);+ }+ return op;+ },+ MAX_OPEN_FDS: 4096,+ nextfd() {+ for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {+ if (!FS.streams[fd]) {+ return fd;+ }+ }+ throw new FS.ErrnoError(33);+ },+ getStreamChecked(fd) {+ var stream = FS.getStream(fd);+ if (!stream) {+ throw new FS.ErrnoError(8);+ }+ return stream;+ },+ getStream: fd => FS.streams[fd],+ createStream(stream, fd = -1) {+ // clone it, so we can return an instance of FSStream+ stream = Object.assign(new FS.FSStream, stream);+ if (fd == -1) {+ fd = FS.nextfd();+ }+ stream.fd = fd;+ FS.streams[fd] = stream;+ return stream;+ },+ closeStream(fd) {+ FS.streams[fd] = null;+ },+ dupStream(origStream, fd = -1) {+ var stream = FS.createStream(origStream, fd);+ stream.stream_ops?.dup?.(stream);+ return stream;+ },+ doSetAttr(stream, node, attr) {+ var setattr = stream?.stream_ops.setattr;+ var arg = setattr ? stream : node;+ setattr ??= node.node_ops.setattr;+ FS.checkOpExists(setattr, 63);+ try {+ setattr(arg, attr);+ } catch (e) {+ if (e instanceof RangeError) {+ throw new FS.ErrnoError(22);+ }+ throw e;+ }+ },+ chrdev_stream_ops: {+ open(stream) {+ var device = FS.getDevice(stream.node.rdev);+ // override node's stream ops with the device's+ stream.stream_ops = device.stream_ops;+ // forward the open call+ stream.stream_ops.open?.(stream);+ },+ llseek() {+ throw new FS.ErrnoError(70);+ }+ },+ major: dev => ((dev) >> 8),+ minor: dev => ((dev) & 255),+ makedev: (ma, mi) => ((ma) << 8 | (mi)),+ registerDevice(dev, ops) {+ FS.devices[dev] = {+ stream_ops: ops+ };+ },+ getDevice: dev => FS.devices[dev],+ getMounts(mount) {+ var mounts = [];+ var check = [ mount ];+ while (check.length) {+ var m = check.pop();+ mounts.push(m);+ check.push(...m.mounts);+ }+ return mounts;+ },+ syncfs(populate, callback) {+ if (typeof populate == "function") {+ callback = populate;+ populate = false;+ }+ FS.syncFSRequests++;+ if (FS.syncFSRequests > 1) {+ err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);+ }+ var mounts = FS.getMounts(FS.root.mount);+ var completed = 0;+ function doCallback(errCode) {+ FS.syncFSRequests--;+ return callback(errCode);+ }+ function done(errCode) {+ if (errCode) {+ if (!done.errored) {+ done.errored = true;+ return doCallback(errCode);+ }+ return;+ }+ if (++completed >= mounts.length) {+ doCallback(null);+ }+ }+ // sync all mounts+ for (var mount of mounts) {+ if (mount.type.syncfs) {+ mount.type.syncfs(mount, populate, done);+ } else {+ done(null);+ }+ }+ },+ mount(type, opts, mountpoint) {+ var root = mountpoint === "/";+ var pseudo = !mountpoint;+ var node;+ if (root && FS.root) {+ throw new FS.ErrnoError(10);+ } else if (!root && !pseudo) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ mountpoint = lookup.path;+ // use the absolute path+ node = lookup.node;+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ if (!FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ }+ var mount = {+ type,+ opts,+ mountpoint,+ mounts: []+ };+ // create a root node for the fs+ var mountRoot = type.mount(mount);+ mountRoot.mount = mount;+ mount.root = mountRoot;+ if (root) {+ FS.root = mountRoot;+ } else if (node) {+ // set as a mountpoint+ node.mounted = mount;+ // add the new mount to the current mount's children+ if (node.mount) {+ node.mount.mounts.push(mount);+ }+ }+ return mountRoot;+ },+ unmount(mountpoint) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ if (!FS.isMountpoint(lookup.node)) {+ throw new FS.ErrnoError(28);+ }+ // destroy the nodes for this mount, and all its child mounts+ var node = lookup.node;+ var mount = node.mounted;+ var mounts = FS.getMounts(mount);+ for (var [hash, current] of Object.entries(FS.nameTable)) {+ while (current) {+ var next = current.name_next;+ if (mounts.includes(current.mount)) {+ FS.destroyNode(current);+ }+ current = next;+ }+ }+ // no longer a mountpoint+ node.mounted = null;+ // remove this mount from the child mounts+ var idx = node.mount.mounts.indexOf(mount);+ node.mount.mounts.splice(idx, 1);+ },+ lookup(parent, name) {+ return parent.node_ops.lookup(parent, name);+ },+ mknod(path, mode, dev) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ if (!name) {+ throw new FS.ErrnoError(28);+ }+ if (name === "." || name === "..") {+ throw new FS.ErrnoError(20);+ }+ var errCode = FS.mayCreate(parent, name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.mknod) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.mknod(parent, name, mode, dev);+ },+ statfs(path) {+ return FS.statfsNode(FS.lookupPath(path, {+ follow: true+ }).node);+ },+ statfsStream(stream) {+ // We keep a separate statfsStream function because noderawfs overrides+ // it. In noderawfs, stream.node is sometimes null. Instead, we need to+ // look at stream.path.+ return FS.statfsNode(stream.node);+ },+ statfsNode(node) {+ // NOTE: None of the defaults here are true. We're just returning safe and+ // sane values. Currently nodefs and rawfs replace these defaults,+ // other file systems leave them alone.+ var rtn = {+ bsize: 4096,+ frsize: 4096,+ blocks: 1e6,+ bfree: 5e5,+ bavail: 5e5,+ files: FS.nextInode,+ ffree: FS.nextInode - 1,+ fsid: 42,+ flags: 2,+ namelen: 255+ };+ if (node.node_ops.statfs) {+ Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root));+ }+ return rtn;+ },+ create(path, mode = 438) {+ mode &= 4095;+ mode |= 32768;+ return FS.mknod(path, mode, 0);+ },+ mkdir(path, mode = 511) {+ mode &= 511 | 512;+ mode |= 16384;+ return FS.mknod(path, mode, 0);+ },+ mkdirTree(path, mode) {+ var dirs = path.split("/");+ var d = "";+ for (var dir of dirs) {+ if (!dir) continue;+ if (d || PATH.isAbs(path)) d += "/";+ d += dir;+ try {+ FS.mkdir(d, mode);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ }+ },+ mkdev(path, mode, dev) {+ if (typeof dev == "undefined") {+ dev = mode;+ mode = 438;+ }+ mode |= 8192;+ return FS.mknod(path, mode, dev);+ },+ symlink(oldpath, newpath) {+ if (!PATH_FS.resolve(oldpath)) {+ throw new FS.ErrnoError(44);+ }+ var lookup = FS.lookupPath(newpath, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var newname = PATH.basename(newpath);+ var errCode = FS.mayCreate(parent, newname);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.symlink) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.symlink(parent, newname, oldpath);+ },+ link(oldpath, newpath, flags) {+ var lookup = FS.lookupPath(newpath, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var newname = PATH.basename(newpath);+ var errCode = FS.mayCreate(parent, newname);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ // Hardlinks are only supported by filesystem backends that provide a+ // `link` node op (e.g. NODERAWFS backed by the host). NODEFS omits it:+ // a host hardlink cannot be confined to the mount root.+ if (!parent.node_ops.link) {+ throw new FS.ErrnoError(34);+ }+ return parent.node_ops.link(parent, newname, oldpath, flags);+ },+ rename(old_path, new_path) {+ var old_dirname = PATH.dirname(old_path);+ var new_dirname = PATH.dirname(new_path);+ var old_name = PATH.basename(old_path);+ var new_name = PATH.basename(new_path);+ // parents must exist+ var lookup, old_dir, new_dir;+ // let the errors from non existent directories percolate up+ lookup = FS.lookupPath(old_path, {+ parent: true+ });+ old_dir = lookup.node;+ lookup = FS.lookupPath(new_path, {+ parent: true+ });+ new_dir = lookup.node;+ if (!old_dir || !new_dir) throw new FS.ErrnoError(44);+ // need to be part of the same mount+ if (old_dir.mount !== new_dir.mount) {+ throw new FS.ErrnoError(75);+ }+ // source must exist+ var old_node = FS.lookupNode(old_dir, old_name);+ // old path should not be an ancestor of the new path+ var relative = PATH_FS.relative(old_path, new_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(28);+ }+ // new path should not be an ancestor of the old path+ relative = PATH_FS.relative(new_path, old_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(55);+ }+ // see if the new path already exists+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ // early out if nothing needs to change+ if (old_node === new_node) {+ return;+ }+ // we'll need to delete the old entry+ var isdir = FS.isDir(old_node.mode);+ var errCode = FS.mayDelete(old_dir, old_name, isdir);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ // need delete permissions if we'll be overwriting.+ // need create permissions if new doesn't already exist.+ errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!old_dir.node_ops.rename) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {+ throw new FS.ErrnoError(10);+ }+ // if we are going to change the parent, check write permissions+ if (new_dir !== old_dir) {+ errCode = FS.nodePermissions(old_dir, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // remove the node from the lookup hash+ FS.hashRemoveNode(old_node);+ // do the underlying fs rename+ try {+ old_dir.node_ops.rename(old_node, new_dir, new_name);+ // update old node (we do this here to avoid each backend+ // needing to)+ old_node.parent = new_dir;+ } catch (e) {+ throw e;+ } finally {+ // add the node back to the hash (in case node_ops.rename+ // changed its name)+ FS.hashAddNode(old_node);+ }+ },+ rmdir(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, true);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.rmdir) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.rmdir(parent, name);+ FS.destroyNode(node);+ },+ readdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ var readdir = FS.checkOpExists(node.node_ops.readdir, 54);+ return readdir(node);+ },+ unlink(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, false);+ if (errCode) {+ // According to POSIX, we should map EISDIR to EPERM, but+ // we instead do what Linux does (and we must, as we use+ // the musl linux libc).+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.unlink) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.unlink(parent, name);+ FS.destroyNode(node);+ },+ readlink(path) {+ var lookup = FS.lookupPath(path);+ var link = lookup.node;+ if (!link) {+ throw new FS.ErrnoError(44);+ }+ if (!link.node_ops.readlink) {+ throw new FS.ErrnoError(28);+ }+ return link.node_ops.readlink(link);+ },+ stat(path, dontFollow) {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ var node = lookup.node;+ var getattr = FS.checkOpExists(node.node_ops.getattr, 63);+ return getattr(node);+ },+ fstat(fd) {+ var stream = FS.getStreamChecked(fd);+ var node = stream.node;+ var getattr = stream.stream_ops.getattr;+ var arg = getattr ? stream : node;+ getattr ??= node.node_ops.getattr;+ FS.checkOpExists(getattr, 63);+ return getattr(arg);+ },+ lstat(path) {+ return FS.stat(path, true);+ },+ doChmod(stream, node, mode, dontFollow) {+ FS.doSetAttr(stream, node, {+ mode: (mode & 4095) | (node.mode & ~4095),+ ctime: Date.now(),+ dontFollow+ });+ },+ chmod(path, mode, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChmod(null, node, mode, dontFollow);+ },+ lchmod(path, mode) {+ FS.chmod(path, mode, true);+ },+ fchmod(fd, mode) {+ var stream = FS.getStreamChecked(fd);+ FS.doChmod(stream, stream.node, mode, false);+ },+ doChown(stream, node, dontFollow) {+ FS.doSetAttr(stream, node, {+ timestamp: Date.now(),+ dontFollow+ });+ },+ chown(path, uid, gid, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChown(null, node, dontFollow);+ },+ lchown(path, uid, gid) {+ FS.chown(path, uid, gid, true);+ },+ fchown(fd, uid, gid) {+ var stream = FS.getStreamChecked(fd);+ FS.doChown(stream, stream.node, false);+ },+ doTruncate(stream, node, len) {+ if (FS.isDir(node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!FS.isFile(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ var errCode = FS.nodePermissions(node, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.doSetAttr(stream, node, {+ size: len,+ timestamp: Date.now()+ });+ },+ truncate(path, len) {+ if (len < 0) {+ throw new FS.ErrnoError(28);+ }+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doTruncate(null, node, len);+ },+ ftruncate(fd, len) {+ var stream = FS.getStreamChecked(fd);+ if (len < 0 || (stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(28);+ }+ FS.doTruncate(stream, stream.node, len);+ },+ utime(path, atime, mtime, dontFollow) {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ FS.doSetAttr(null, lookup.node, {+ atime,+ mtime,+ dontFollow+ });+ },+ open(path, flags, mode = 438) {+ if (path === "") {+ throw new FS.ErrnoError(44);+ }+ flags = FS_modeStringToFlags(flags);+ if ((flags & 64)) {+ mode = (mode & 4095) | 32768;+ } else {+ mode = 0;+ }+ var node;+ var isDirPath;+ if (typeof path == "object") {+ node = path;+ } else {+ isDirPath = path.endsWith("/");+ // noent_okay makes it so that if the final component of the path+ // doesn't exist, lookupPath returns `node: undefined`. `path` will be+ // updated to point to the target of all symlinks.+ var lookup = FS.lookupPath(path, {+ follow: !(flags & 131072),+ noent_okay: true+ });+ node = lookup.node;+ path = lookup.path;+ }+ // perhaps we need to create the node+ var created = false;+ if ((flags & 64)) {+ if (node) {+ // if O_CREAT and O_EXCL are set, error out if the node already exists+ if ((flags & 128)) {+ throw new FS.ErrnoError(20);+ }+ } else if (isDirPath) {+ throw new FS.ErrnoError(31);+ } else {+ // node doesn't exist, try to create it+ // Ignore the permission bits here to ensure we can `open` this new+ // file below. We use chmod below to apply the permissions once the+ // file is open.+ node = FS.mknod(path, mode | 511, 0);+ created = true;+ }+ }+ if (!node) {+ throw new FS.ErrnoError(44);+ }+ // can't truncate a device+ if (FS.isChrdev(node.mode)) {+ flags &= ~512;+ }+ // if asked only for a directory, then this must be one+ if ((flags & 65536) && !FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ // check permissions, if this is not a file we just created now (it is ok to+ // create and write to a file with read-only permissions; it is read-only+ // for later use)+ if (!created) {+ var errCode = FS.mayOpen(node, flags);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // do truncation if necessary+ if ((flags & 512) && !created) {+ FS.truncate(node, 0);+ }+ // we've already handled these, don't pass down to the underlying vfs+ flags &= ~(128 | 512 | 131072);+ // register the stream with the filesystem+ var stream = FS.createStream({+ node,+ path: FS.getPath(node),+ // we want the absolute path to the node+ flags,+ seekable: true,+ position: 0,+ stream_ops: node.stream_ops,+ // used by the file family libc calls (fopen, fwrite, ferror, etc.)+ ungotten: [],+ error: false+ });+ // call the new stream's open function+ if (stream.stream_ops.open) {+ stream.stream_ops.open(stream);+ }+ if (created) {+ FS.chmod(node, mode & 511);+ }+ return stream;+ },+ close(stream) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (stream.getdents) stream.getdents = null;+ // free readdir state+ // The fd is going away: wake anything waiting on it (poll/epoll) with+ // POLLNVAL so a blocking wait unblocks and an epoll registration is evicted+ // on its next derive. Only sockets/pipes/epoll ever carry a wait-queue, so+ // for every other stream (incl. nodeless noderawfs stdio) this is a no-op.+ stream.node?.notifyListeners(32);+ try {+ if (stream.stream_ops.close) {+ stream.stream_ops.close(stream);+ }+ } catch (e) {+ throw e;+ } finally {+ FS.closeStream(stream.fd);+ }+ stream.fd = null;+ },+ isClosed(stream) {+ return stream.fd === null;+ },+ llseek(stream, offset, whence) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (!stream.seekable || !stream.stream_ops.llseek) {+ throw new FS.ErrnoError(70);+ }+ if (whence != 0 && whence != 1 && whence != 2) {+ throw new FS.ErrnoError(28);+ }+ stream.position = stream.stream_ops.llseek(stream, offset, whence);+ stream.ungotten = [];+ return stream.position;+ },+ read(stream, buffer, offset, length, position) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.read) {+ throw new FS.ErrnoError(28);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);+ if (!seeking) stream.position += bytesRead;+ return bytesRead;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.write) {+ throw new FS.ErrnoError(28);+ }+ if (stream.seekable && stream.flags & 1024) {+ // seek to the end before writing in append mode+ FS.llseek(stream, 0, 2);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);+ if (!seeking) stream.position += bytesWritten;+ return bytesWritten;+ },+ mmap(stream, length, position, prot, flags) {+ // User requests writing to file (prot & PROT_WRITE != 0).+ // Checking if we have permissions to write to the file unless+ // MAP_PRIVATE flag is set. According to POSIX spec it is possible+ // to write to file opened in read-only mode with MAP_PRIVATE flag,+ // as all modifications will be visible only in the memory of+ // the current process.+ if ((prot & 2) && !(flags & 2) && (stream.flags & 2097155) !== 2) {+ throw new FS.ErrnoError(2);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(2);+ }+ if (!stream.stream_ops.mmap) {+ throw new FS.ErrnoError(43);+ }+ if (!length) {+ throw new FS.ErrnoError(28);+ }+ return stream.stream_ops.mmap(stream, length, position, prot, flags);+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ if (!stream.stream_ops.msync) {+ return 0;+ }+ return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);+ },+ ioctl(stream, cmd, arg) {+ if (!stream.stream_ops.ioctl) {+ throw new FS.ErrnoError(59);+ }+ return stream.stream_ops.ioctl(stream, cmd, arg);+ },+ readFile(path, opts = {}) {+ opts.flags = opts.flags ?? 0;+ opts.encoding = opts.encoding ?? "binary";+ if (opts.encoding !== "utf8" && opts.encoding !== "binary") {+ abort(`Invalid encoding type "${opts.encoding}"`);+ }+ var stream = FS.open(path, opts.flags);+ var stat = FS.stat(path);+ var length = stat.size;+ var buf = new Uint8Array(length);+ FS.read(stream, buf, 0, length, 0);+ if (opts.encoding === "utf8") {+ buf = UTF8ArrayToString(buf);+ }+ FS.close(stream);+ return buf;+ },+ writeFile(path, data, opts = {}) {+ opts.flags = opts.flags ?? 577;+ var stream = FS.open(path, opts.flags, opts.mode);+ data = FS_fileDataToTypedArray(data);+ FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);+ FS.close(stream);+ },+ cwd: () => FS.currentPath,+ chdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ if (lookup.node === null) {+ throw new FS.ErrnoError(44);+ }+ if (!FS.isDir(lookup.node.mode)) {+ throw new FS.ErrnoError(54);+ }+ var errCode = FS.nodePermissions(lookup.node, "x");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.currentPath = lookup.path;+ },+ createDefaultDirectories() {+ FS.mkdir("/tmp");+ FS.mkdir("/home");+ FS.mkdir("/home/web_user");+ },+ createDefaultDevices() {+ // create /dev+ FS.mkdir("/dev");+ // setup /dev/null+ FS.registerDevice(FS.makedev(1, 3), {+ read: () => 0,+ write: (stream, buffer, offset, length, pos) => length,+ llseek: () => 0+ });+ FS.mkdev("/dev/null", FS.makedev(1, 3));+ // setup /dev/tty and /dev/tty1+ // stderr needs to print output using err() rather than out()+ // so we register a second tty just for it.+ TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);+ TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);+ FS.mkdev("/dev/tty", FS.makedev(5, 0));+ FS.mkdev("/dev/tty1", FS.makedev(6, 0));+ // setup /dev/[u]random+ // use a buffer to avoid overhead of individual crypto calls per byte+ var randomBuffer = new Uint8Array(1024), randomLeft = 0;+ var randomByte = () => {+ if (!randomLeft) {+ randomFill(randomBuffer);+ randomLeft = randomBuffer.byteLength;+ }+ return randomBuffer[--randomLeft];+ };+ FS.createDevice("/dev", "random", randomByte);+ FS.createDevice("/dev", "urandom", randomByte);+ // we're not going to emulate the actual shm device,+ // just create the tmp dirs that reside in it commonly+ FS.mkdir("/dev/shm");+ FS.mkdir("/dev/shm/tmp");+ },+ createSpecialDirectories() {+ // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the+ // name of the stream for fd 6 (see test_unistd_ttyname)+ FS.mkdir("/proc");+ var proc_self = FS.mkdir("/proc/self");+ FS.mkdir("/proc/self/fd");+ FS.mount({+ mount() {+ var node = FS.createNode(proc_self, "fd", 16895, 73);+ node.stream_ops = {+ llseek: MEMFS.stream_ops.llseek+ };+ node.node_ops = {+ lookup(parent, name) {+ var fd = +name;+ var stream = FS.getStreamChecked(fd);+ var ret = {+ parent: null,+ mount: {+ mountpoint: "fake"+ },+ node_ops: {+ readlink: () => stream.path+ },+ id: fd + 1+ };+ ret.parent = ret;+ // make it look like a simple root node+ return ret;+ },+ readdir() {+ return Array.from(FS.streams.entries()).filter(([k, v]) => v).map(([k, v]) => k.toString());+ }+ };+ return node;+ }+ }, {}, "/proc/self/fd");+ },+ createStandardStreams(input, output, error) {+ // TODO deprecate the old functionality of a single+ // input / output callback and that utilizes FS.createDevice+ // and instead require a unique set of stream ops+ // by default, we symlink the standard streams to the+ // default tty devices. however, if the standard streams+ // have been overwritten we create a unique device for+ // them instead.+ if (input) {+ FS.createDevice("/dev", "stdin", input);+ } else {+ FS.symlink("/dev/tty", "/dev/stdin");+ }+ if (output) {+ FS.createDevice("/dev", "stdout", null, output);+ } else {+ FS.symlink("/dev/tty", "/dev/stdout");+ }+ if (error) {+ FS.createDevice("/dev", "stderr", null, error);+ } else {+ FS.symlink("/dev/tty1", "/dev/stderr");+ }+ // open default streams for the stdin, stdout and stderr devices+ var stdin = FS.open("/dev/stdin", 0);+ var stdout = FS.open("/dev/stdout", 1);+ var stderr = FS.open("/dev/stderr", 1);+ },+ staticInit() {+ FS.nameTable = new Array(4096);+ FS.mount(MEMFS, {}, "/");+ FS.createDefaultDirectories();+ FS.createDefaultDevices();+ FS.createSpecialDirectories();+ FS.filesystems = {+ "MEMFS": MEMFS+ };+ },+ init(input, output, error) {+ FS.initialized = true;+ // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here+ input ??= Module["stdin"];+ output ??= Module["stdout"];+ error ??= Module["stderr"];+ FS.createStandardStreams(input, output, error);+ },+ quit() {+ FS.initialized = false;+ // force-flush all streams, so we get musl std streams printed out+ // close all of our streams+ for (var stream of FS.streams) {+ if (stream) {+ FS.close(stream);+ }+ }+ },+ findObject(path, dontResolveLastLink) {+ var ret = FS.analyzePath(path, dontResolveLastLink);+ if (!ret.exists) {+ return null;+ }+ return ret.object;+ },+ analyzePath(path, dontResolveLastLink) {+ // operate from within the context of the symlink's target+ try {+ var lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ path = lookup.path;+ } catch (e) {}+ var ret = {+ isRoot: false,+ exists: false,+ error: 0,+ name: null,+ path: null,+ object: null,+ parentExists: false,+ parentPath: null,+ parentObject: null+ };+ try {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ ret.parentExists = true;+ ret.parentPath = lookup.path;+ ret.parentObject = lookup.node;+ ret.name = PATH.basename(path);+ lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ ret.exists = true;+ ret.path = lookup.path;+ ret.object = lookup.node;+ ret.name = lookup.node.name;+ ret.isRoot = lookup.path === "/";+ } catch (e) {+ ret.error = e.errno;+ }+ return ret;+ },+ createPath(parent, path, canRead, canWrite) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ var parts = path.split("/").reverse();+ while (parts.length) {+ var part = parts.pop();+ if (!part) continue;+ var current = PATH.join2(parent, part);+ try {+ FS.mkdir(current);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ parent = current;+ }+ return current;+ },+ createFile(parent, name, properties, canRead, canWrite) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(canRead, canWrite);+ return FS.create(path, mode);+ },+ createDataFile(parent, name, data, canRead, canWrite, canOwn) {+ var path = name;+ if (parent) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ path = name ? PATH.join2(parent, name) : parent;+ }+ var mode = FS_getMode(canRead, canWrite);+ var node = FS.create(path, mode);+ if (data) {+ data = FS_fileDataToTypedArray(data);+ // make sure we can write to the file+ FS.chmod(node, mode | 146);+ var stream = FS.open(node, 577);+ FS.write(stream, data, 0, data.length, 0, canOwn);+ FS.close(stream);+ FS.chmod(node, mode);+ }+ },+ createDevice(parent, name, input, output) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(!!input, !!output);+ FS.createDevice.major ??= 64;+ var dev = FS.makedev(FS.createDevice.major++, 0);+ // Create a fake device that a set of stream ops to emulate+ // the old behavior.+ FS.registerDevice(dev, {+ open(stream) {+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ if (output?.buffer?.length) {+ output(10);+ }+ },+ read(stream, buffer, offset, length, pos) {+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = input();+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && !bytesRead) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ for (var i = 0; i < length; i++) {+ try {+ output(buffer[offset + i]);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ });+ return FS.mkdev(path, mode, dev);+ },+ forceLoadFile(obj) {+ if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;+ if (globalThis.XMLHttpRequest) {+ abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");+ } else {+ // Command-line.+ try {+ obj.contents = readBinary(obj.url);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ },+ createLazyFile(parent, name, url, canRead, canWrite) {+ // Lazy chunked Uint8Array (implements get and length from Uint8Array).+ // Actual getting is abstracted away for eventual reuse.+ class LazyUint8Array {+ lengthKnown=false;+ chunks=[];+ // Loaded chunks. Index is the chunk number+ get(idx) {+ if (idx > this.length - 1 || idx < 0) {+ return undefined;+ }+ var chunkOffset = idx % this.chunkSize;+ var chunkNum = (idx / this.chunkSize) | 0;+ return this.getter(chunkNum)[chunkOffset];+ }+ setDataGetter(getter) {+ this.getter = getter;+ }+ cacheLength() {+ // Find length+ var xhr = new XMLHttpRequest;+ xhr.open("HEAD", url, false);+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort(`Couldn't load ${url}. Status: ${xhr.status}`);+ var datalength = Number(xhr.getResponseHeader("Content-length"));+ var header;+ var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";+ var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";+ var chunkSize = 1024 * 1024;+ // Chunk size in bytes+ if (!hasByteServing) chunkSize = datalength;+ // Function to get a range from the remote URL.+ var doXHR = (from, to) => {+ if (from > to) abort(`invalid range (${from}, ${to}) or no bytes requested!`);+ if (to > datalength - 1) abort(`only ${datalength} bytes available! programmer error!`);+ // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ if (datalength !== chunkSize) xhr.setRequestHeader("Range", `bytes=${from}-${to}`);+ // Some hints to the browser that we want binary data.+ xhr.responseType = "arraybuffer";+ if (xhr.overrideMimeType) {+ xhr.overrideMimeType("text/plain; charset=x-user-defined");+ }+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort(`Couldn't load ${url}. Status: ${xhr.status}`);+ if (xhr.response !== undefined) {+ return new Uint8Array(/** @type{Array<number>} */ (xhr.response || []));+ }+ return intArrayFromString(xhr.responseText ?? "", true);+ };+ var lazyArray = this;+ lazyArray.setDataGetter(chunkNum => {+ var start = chunkNum * chunkSize;+ var end = (chunkNum + 1) * chunkSize - 1;+ // including this byte+ end = Math.min(end, datalength - 1);+ // if datalength-1 is selected, this is the last block+ if (typeof lazyArray.chunks[chunkNum] == "undefined") {+ lazyArray.chunks[chunkNum] = doXHR(start, end);+ }+ if (typeof lazyArray.chunks[chunkNum] == "undefined") abort("doXHR failed!");+ return lazyArray.chunks[chunkNum];+ });+ if (usesGzip || !datalength) {+ // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length+ chunkSize = datalength = 1;+ // this will force getter(0)/doXHR do download the whole file+ datalength = this.getter(0).length;+ chunkSize = datalength;+ out("LazyFiles on gzip forces download of the whole file when length is accessed");+ }+ this._length = datalength;+ this._chunkSize = chunkSize;+ this.lengthKnown = true;+ }+ get length() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._length;+ }+ get chunkSize() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._chunkSize;+ }+ }+ if (globalThis.XMLHttpRequest) {+ if (!ENVIRONMENT_IS_WORKER) abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");+ var lazyArray = new LazyUint8Array;+ var properties = {+ isDevice: false,+ contents: lazyArray+ };+ } else {+ var properties = {+ isDevice: false,+ url+ };+ }+ var node = FS.createFile(parent, name, properties, canRead, canWrite);+ // This is a total hack, but I want to get this lazy file code out of the+ // core of MEMFS. If we want to keep this lazy file concept I feel it should+ // be its own thin LAZYFS proxying calls to MEMFS.+ if (properties.contents) {+ node.contents = properties.contents;+ } else if (properties.url) {+ node.contents = null;+ node.url = properties.url;+ }+ // Add a function that defers querying the file size until it is asked the first time.+ Object.defineProperties(node, {+ usedBytes: {+ get: function() {+ return this.contents.length;+ }+ }+ });+ // override each stream op with one that tries to force load the lazy file first+ var stream_ops = {};+ for (const [key, fn] of Object.entries(node.stream_ops)) {+ stream_ops[key] = (...args) => {+ FS.forceLoadFile(node);+ return fn(...args);+ };+ }+ function writeChunks(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= contents.length) return 0;+ var size = Math.min(contents.length - position, length);+ if (contents.slice) {+ // normal array+ for (var i = 0; i < size; i++) {+ buffer[offset + i] = contents[position + i];+ }+ } else {+ for (var i = 0; i < size; i++) {+ // LazyUint8Array from sync binary XHR+ buffer[offset + i] = contents.get(position + i);+ }+ }+ return size;+ }+ // use a custom read function+ stream_ops.read = (stream, buffer, offset, length, position) => {+ FS.forceLoadFile(node);+ return writeChunks(stream, buffer, offset, length, position);+ };+ // use a custom mmap function+ stream_ops.mmap = (stream, length, position, prot, flags) => {+ FS.forceLoadFile(node);+ var ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ writeChunks(stream, HEAP8, ptr, length, position);+ return {+ ptr,+ allocated: true+ };+ };+ node.stream_ops = stream_ops;+ return node;+ }+};++/**+ * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the+ * emscripten HEAP, returns a copy of that string as a Javascript String object.+ *+ * @param {number} ptr+ * @param {number=} maxBytesToRead - An optional length that specifies the+ * maximum number of bytes to read. You can omit this parameter to scan the+ * string until the first 0 byte. If maxBytesToRead is passed, and the string+ * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the+ * string will cut short at that byte index.+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => {+ if (!ptr) return "";+ var end = findStringEnd(HEAPU8, ptr, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end));+};++var SYSCALLS = {+ currentUmask: 18,+ calculateAt(dirfd, path, allowEmpty) {+ if (PATH.isAbs(path)) {+ return path;+ }+ // relative path+ var dir;+ if (dirfd === -100) {+ dir = FS.cwd();+ } else {+ var dirstream = SYSCALLS.getStreamFromFD(dirfd);+ dir = dirstream.path;+ }+ if (path.length == 0) {+ if (!allowEmpty) {+ throw new FS.ErrnoError(44);+ }+ return dir;+ }+ return dir + "/" + path;+ },+ writeStat(buf, stat) {+ HEAPU32[((buf) >> 2)] = stat.dev;+ HEAPU32[(((buf) + (4)) >> 2)] = stat.mode;+ HEAPU32[(((buf) + (8)) >> 2)] = stat.nlink;+ HEAPU32[(((buf) + (12)) >> 2)] = stat.uid;+ HEAPU32[(((buf) + (16)) >> 2)] = stat.gid;+ HEAPU32[(((buf) + (20)) >> 2)] = stat.rdev;+ (tempI64 = [ stat.size >>> 0, (tempDouble = stat.size, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ HEAP32[(((buf) + (32)) >> 2)] = 4096;+ HEAP32[(((buf) + (36)) >> 2)] = stat.blocks;+ var atime = stat.atime.getTime();+ var mtime = stat.mtime.getTime();+ var ctime = stat.ctime.getTime();+ (tempI64 = [ Math.floor(atime / 1e3) >>> 0, (tempDouble = Math.floor(atime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = (atime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(mtime / 1e3) >>> 0, (tempDouble = Math.floor(mtime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (56)) >> 2)] = tempI64[0], HEAP32[(((buf) + (60)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (64)) >> 2)] = (mtime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(ctime / 1e3) >>> 0, (tempDouble = Math.floor(ctime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (72)) >> 2)] = tempI64[0], HEAP32[(((buf) + (76)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (80)) >> 2)] = (ctime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ stat.ino >>> 0, (tempDouble = stat.ino, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (88)) >> 2)] = tempI64[0], HEAP32[(((buf) + (92)) >> 2)] = tempI64[1]);+ return 0;+ },+ writeStatFs(buf, stats) {+ HEAPU32[(((buf) + (4)) >> 2)] = stats.bsize;+ HEAPU32[(((buf) + (60)) >> 2)] = stats.bsize;+ (tempI64 = [ stats.blocks >>> 0, (tempDouble = stats.blocks, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (8)) >> 2)] = tempI64[0], HEAP32[(((buf) + (12)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bfree >>> 0, (tempDouble = stats.bfree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (16)) >> 2)] = tempI64[0], HEAP32[(((buf) + (20)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bavail >>> 0, (tempDouble = stats.bavail, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.files >>> 0, (tempDouble = stats.files, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (32)) >> 2)] = tempI64[0], HEAP32[(((buf) + (36)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.ffree >>> 0, (tempDouble = stats.ffree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = stats.fsid;+ HEAPU32[(((buf) + (64)) >> 2)] = stats.flags;+ // ST_NOSUID+ HEAPU32[(((buf) + (56)) >> 2)] = stats.namelen;+ },+ doMsync(addr, stream, len, flags, offset) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ if (flags & 2) {+ // MAP_PRIVATE calls need not to be synced back to underlying fs+ return 0;+ }+ var buffer = HEAPU8.subarray(addr, addr + len);+ FS.msync(stream, buffer, offset, len, flags);+ },+ getStreamFromFD(fd) {+ var stream = FS.getStreamChecked(fd);+ return stream;+ },+ varargs: undefined,+ getStr(ptr) {+ var ret = UTF8ToString(ptr);+ return ret;+ }+};++function ___syscall_dup(fd) {+ try {+ var old = SYSCALLS.getStreamFromFD(fd);+ return FS.dupStream(old).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_faccessat(dirfd, path, amode, flags) {+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ if (amode & ~7) {+ // need a valid mode+ return -28;+ }+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ if (!node) {+ return -44;+ }+ var perms = "";+ if (amode & 4) perms += "r";+ if (amode & 2) perms += "w";+ if (amode & 1) perms += "x";+ if (perms && FS.nodePermissions(node, perms)) {+ return -2;+ }+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var syscallGetVarargI = () => {+ // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number.+ var ret = HEAP32[((+SYSCALLS.varargs) >> 2)];+ SYSCALLS.varargs += 4;+ return ret;+};++var syscallGetVarargP = syscallGetVarargI;++/** @type {!Int16Array} */ var HEAP16;++function ___syscall_fcntl64(fd, cmd, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (cmd) {+ case 0:+ {+ var arg = syscallGetVarargI();+ if (arg < 0) {+ return -28;+ }+ while (FS.streams[arg]) {+ arg++;+ }+ var newStream;+ newStream = FS.dupStream(stream, arg);+ return newStream.fd;+ }++ case 1:+ case 2:+ return 0;++ // FD_CLOEXEC makes no sense for a single process.+ case 3:+ return stream.flags;++ case 4:+ {+ var arg = syscallGetVarargI();+ var mask = 289792;+ stream.flags = (stream.flags & ~mask) | (arg & mask);+ return 0;+ }++ case 12:+ {+ var arg = syscallGetVarargP();+ var offset = 0;+ // We're always unlocked.+ HEAP16[(((arg) + (offset)) >> 1)] = 2;+ return 0;+ }++ case 13:+ case 14:+ // Pretend that the locking is successful. These are process-level locks,+ // and Emscripten programs are a single process. If we supported linking a+ // filesystem between programs, we'd need to do more here.+ // See https://github.com/emscripten-core/emscripten/issues/23697+ return 0;+ }+ return -28;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_fstat64(fd, buf) {+ try {+ return SYSCALLS.writeStat(buf, FS.fstat(fd));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var convertI32PairToI53Checked = (lo, hi) => ((hi + 2097152) >>> 0 < 4194305 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;++function ___syscall_ftruncate64(fd, length_low, length_high) {+ var length = convertI32PairToI53Checked(length_low, length_high);+ try {+ if (isNaN(length)) return -22;+ FS.ftruncate(fd, length);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);++function ___syscall_getcwd(buf, size) {+ try {+ if (!size) return -28;+ var cwd = FS.cwd();+ var cwdLengthInBytes = lengthBytesUTF8(cwd) + 1;+ if (size < cwdLengthInBytes) return -68;+ stringToUTF8(cwd, buf, size);+ return cwdLengthInBytes;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_getdents64(fd, dirp, count) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ stream.getdents ||= FS.readdir(stream.path);+ var struct_size = 280;+ var pos = 0;+ var off = FS.llseek(stream, 0, 1);+ var startIdx = Math.floor(off / struct_size);+ var endIdx = Math.min(stream.getdents.length, startIdx + Math.floor(count / struct_size));+ for (var idx = startIdx; idx < endIdx; idx++) {+ var id;+ var type;+ var name = stream.getdents[idx];+ if (name === ".") {+ id = stream.node.id;+ type = 4;+ } else if (name === "..") {+ var lookup = FS.lookupPath(stream.path, {+ parent: true+ });+ id = lookup.node.id;+ type = 4;+ } else {+ var child;+ try {+ child = FS.lookupNode(stream.node, name);+ } catch (e) {+ // If the entry is not a directory, file, or symlink, nodefs+ // lookupNode will raise EINVAL. Skip these and continue.+ if (e?.errno === 28) {+ continue;+ }+ throw e;+ }+ id = child.id;+ type = FS.isChrdev(child.mode) ? 2 : // character device.+ FS.isDir(child.mode) ? 4 : // directory+ FS.isLink(child.mode) ? 10 : // symbolic link.+ 8;+ }+ (tempI64 = [ id >>> 0, (tempDouble = id, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((dirp + pos) >> 2)] = tempI64[0], HEAP32[(((dirp + pos) + (4)) >> 2)] = tempI64[1]);+ (tempI64 = [ (idx + 1) * struct_size >>> 0, (tempDouble = (idx + 1) * struct_size,+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((dirp + pos) + (8)) >> 2)] = tempI64[0], HEAP32[(((dirp + pos) + (12)) >> 2)] = tempI64[1]);+ HEAP16[(((dirp + pos) + (16)) >> 1)] = 280;+ HEAP8[(dirp + pos) + (18)] = type;+ stringToUTF8(name, dirp + pos + 19, 256);+ pos += struct_size;+ }+ FS.llseek(stream, idx * struct_size, 0);+ return pos;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var ___syscall_getuid32 = () => 0;++function ___syscall_ioctl(fd, op, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (op) {+ case 21509:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21505:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcgets) {+ var termios = stream.tty.ops.ioctl_tcgets(stream);+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = termios.c_iflag || 0;+ HEAP32[(((argp) + (4)) >> 2)] = termios.c_oflag || 0;+ HEAP32[(((argp) + (8)) >> 2)] = termios.c_cflag || 0;+ HEAP32[(((argp) + (12)) >> 2)] = termios.c_lflag || 0;+ for (var i = 0; i < 32; i++) {+ HEAP8[(argp + i) + (17)] = termios.c_cc[i] || 0;+ }+ return 0;+ }+ return 0;+ }++ case 21510:+ case 21511:+ case 21512:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21506:+ case 21507:+ case 21508:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcsets) {+ var argp = syscallGetVarargP();+ var c_iflag = HEAP32[((argp) >> 2)];+ var c_oflag = HEAP32[(((argp) + (4)) >> 2)];+ var c_cflag = HEAP32[(((argp) + (8)) >> 2)];+ var c_lflag = HEAP32[(((argp) + (12)) >> 2)];+ var c_cc = [];+ for (var i = 0; i < 32; i++) {+ c_cc.push(HEAP8[(argp + i) + (17)]);+ }+ return stream.tty.ops.ioctl_tcsets(stream.tty, op, {+ c_iflag,+ c_oflag,+ c_cflag,+ c_lflag,+ c_cc+ });+ }+ return 0;+ }++ case 21519:+ {+ if (!stream.tty) return -59;+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = 0;+ return 0;+ }++ case 21520:+ {+ if (!stream.tty) return -59;+ return -28;+ }++ case 21537:+ case 21531:+ {+ var argp = syscallGetVarargP();+ return FS.ioctl(stream, op, argp);+ }++ case 21523:+ {+ // TODO: in theory we should write to the winsize struct that gets+ // passed in, but for now musl doesn't read anything on it+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tiocgwinsz) {+ var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);+ var argp = syscallGetVarargP();+ HEAP16[((argp) >> 1)] = winsize[0];+ HEAP16[(((argp) + (2)) >> 1)] = winsize[1];+ }+ return 0;+ }++ case 21524:+ {+ // TODO: technically, this ioctl call should change the window size.+ // but, since emscripten doesn't have any concept of a terminal window+ // yet, we'll just silently throw it away as we do TIOCGWINSZ+ if (!stream.tty) return -59;+ return 0;+ }++ case 21515:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ default:+ return -28;+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_lstat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.lstat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_mkdirat(dirfd, path, mode) {+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ mode &= ~SYSCALLS.currentUmask;+ FS.mkdir(path, mode, 0);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_newfstatat(dirfd, path, buf, flags) {+ try {+ path = SYSCALLS.getStr(path);+ var nofollow = flags & 256;+ var allowEmpty = flags & 4096;+ flags = flags & (~6400);+ path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);+ return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_openat(dirfd, path, flags, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ var mode = varargs ? syscallGetVarargI() : 0;+ if (flags & 64) {+ mode &= ~SYSCALLS.currentUmask;+ }+ return FS.open(path, flags, mode).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_readlinkat(dirfd, path, buf, bufsize) {+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ if (bufsize <= 0) return -28;+ var ret = FS.readlink(path);+ var len = Math.min(bufsize, lengthBytesUTF8(ret));+ var endChar = HEAP8[buf + len];+ stringToUTF8(ret, buf, bufsize + 1);+ // readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!)+ // stringToUTF8() always appends a null byte, so restore the character under the null byte after the write.+ HEAP8[buf + len] = endChar;+ return len;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_rmdir(path) {+ try {+ path = SYSCALLS.getStr(path);+ FS.rmdir(path);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_stat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_unlinkat(dirfd, path, flags) {+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ if (!flags) {+ FS.unlink(path);+ } else if (flags === 512) {+ FS.rmdir(path);+ } else {+ return -28;+ }+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var readI53FromI64 = ptr => HEAPU32[((ptr) >> 2)] + HEAP32[(((ptr) + (4)) >> 2)] * 4294967296;++function ___syscall_utimensat(dirfd, path, times, flags) {+ try {+ var nofollow = flags & 256;+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path, true);+ var now = Date.now(), atime, mtime;+ if (!times) {+ atime = now;+ mtime = now;+ } else {+ var seconds = readI53FromI64(times);+ var nanoseconds = HEAP32[(((times) + (8)) >> 2)];+ if (nanoseconds == 1073741823) {+ atime = now;+ } else if (nanoseconds == 1073741822) {+ atime = null;+ } else {+ atime = (seconds * 1e3) + (nanoseconds / (1e3 * 1e3));+ }+ times += 16;+ seconds = readI53FromI64(times);+ nanoseconds = HEAP32[(((times) + (8)) >> 2)];+ if (nanoseconds == 1073741823) {+ mtime = now;+ } else if (nanoseconds == 1073741822) {+ mtime = null;+ } else {+ mtime = (seconds * 1e3) + (nanoseconds / (1e3 * 1e3));+ }+ }+ // null here means UTIME_OMIT was passed. If both were set to UTIME_OMIT then+ // we can skip the call completely.+ if ((mtime ?? atime) !== null) {+ FS.utime(path, atime, mtime, nofollow);+ }+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __abort_js = () => abort("");++var __embind_register_bigint = (primitiveType, name, size, minRange, maxRange) => {};++var AsciiToString = ptr => {+ var str = "";+ while (1) {+ var ch = HEAPU8[ptr++];+ if (!ch) return str;+ str += String.fromCharCode(ch);+ }+};++var awaitingDependencies = {};++var registeredTypes = {};++var typeDependencies = {};++class BindingError extends Error {+ constructor(message) {+ super(message);+ this.name = "BindingError";+ }+}++var throwBindingError = message => {+ throw new BindingError(message);+};++/** @param {Object=} options */ function sharedRegisterType(rawType, registeredInstance, options = {}) {+ var name = registeredInstance.name;+ if (!rawType) {+ throwBindingError(`type "${name}" must have a positive integer typeid pointer`);+ }+ if (registeredTypes.hasOwnProperty(rawType)) {+ if (options.ignoreDuplicateRegistrations) {+ return;+ } else {+ throwBindingError(`Cannot register type '${name}' twice`);+ }+ }+ registeredTypes[rawType] = registeredInstance;+ delete typeDependencies[rawType];+ if (awaitingDependencies.hasOwnProperty(rawType)) {+ var callbacks = awaitingDependencies[rawType];+ delete awaitingDependencies[rawType];+ callbacks.forEach(cb => cb());+ }+}++/** @param {Object=} options */ function registerType(rawType, registeredInstance, options = {}) {+ return sharedRegisterType(rawType, registeredInstance, options);+}++/** @suppress {globalThis} */ var __embind_register_bool = (rawType, name, trueValue, falseValue) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: function(wt) {+ // ambiguous emscripten ABI: sometimes return values are+ // true or false, and sometimes integers (0 or 1)+ return !!wt;+ },+ toWireType: function(destructors, o) {+ return o ? trueValue : falseValue;+ },+ readValueFromPointer: function(pointer) {+ return this.fromWireType(HEAPU8[pointer]);+ },+ destructorFunction: null+ });+};++var emval_freelist = [];++var emval_handles = [ 0, 1, , 1, null, 1, true, 1, false, 1 ];++var __emval_decref = handle => {+ if (handle > 9 && 0 === --emval_handles[handle + 1]) {+ var value = emval_handles[handle];+ emval_handles[handle] = undefined;+ emval_freelist.push(handle);+ }+};++var Emval = {+ toValue: handle => {+ if (!handle) {+ throwBindingError(`Cannot use deleted val. handle = ${handle}`);+ }+ return emval_handles[handle];+ },+ toHandle: value => {+ switch (value) {+ case undefined:+ return 2;++ case null:+ return 4;++ case true:+ return 6;++ case false:+ return 8;++ default:+ {+ const handle = emval_freelist.pop() || emval_handles.length;+ emval_handles[handle] = value;+ emval_handles[handle + 1] = 1;+ return handle;+ }+ }+ }+};++/** @suppress {globalThis} */ function readPointer(pointer) {+ return this.fromWireType(HEAPU32[((pointer) >> 2)]);+}++var EmValType = {+ name: "emscripten::val",+ fromWireType: handle => {+ var rv = Emval.toValue(handle);+ __emval_decref(handle);+ return rv;+ },+ toWireType: (destructors, value) => Emval.toHandle(value),+ readValueFromPointer: readPointer,+ destructorFunction: null+};++var __embind_register_emval = rawType => registerType(rawType, EmValType);++/** @type {!Float32Array} */ var HEAPF32;++/** @type {!Float64Array} */ var HEAPF64;++var floatReadValueFromPointer = (name, width) => {+ switch (width) {+ case 4:+ return function(pointer) {+ return this.fromWireType(HEAPF32[((pointer) >> 2)]);+ };++ case 8:+ return function(pointer) {+ return this.fromWireType(HEAPF64[((pointer) >> 3)]);+ };++ default:+ throw new TypeError(`invalid float width (${width}): ${name}`);+ }+};++var __embind_register_float = (rawType, name, size) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: value => value,+ toWireType: (destructors, value) => value,+ readValueFromPointer: floatReadValueFromPointer(name, size),+ destructorFunction: null+ });+};++/** @type {!Uint16Array} */ var HEAPU16;++var integerReadValueFromPointer = (name, width, signed) => {+ // integers are quite common, so generate very specialized functions+ switch (width) {+ case 1:+ return signed ? pointer => HEAP8[pointer] : pointer => HEAPU8[pointer];++ case 2:+ return signed ? pointer => HEAP16[((pointer) >> 1)] : pointer => HEAPU16[((pointer) >> 1)];++ case 4:+ return signed ? pointer => HEAP32[((pointer) >> 2)] : pointer => HEAPU32[((pointer) >> 2)];++ default:+ throw new TypeError(`invalid integer width (${width}): ${name}`);+ }+};++/** @suppress {globalThis} */ var __embind_register_integer = (primitiveType, name, size, minRange, maxRange) => {+ name = AsciiToString(name);+ const isUnsignedType = minRange === 0;+ let fromWireType = value => value;+ if (isUnsignedType) {+ var bitshift = 32 - 8 * size;+ fromWireType = value => (value << bitshift) >>> bitshift;+ maxRange = fromWireType(maxRange);+ }+ registerType(primitiveType, {+ name,+ fromWireType,+ toWireType: (destructors, value) => value,+ readValueFromPointer: integerReadValueFromPointer(name, size, minRange !== 0),+ destructorFunction: null+ });+};++var __embind_register_memory_view = (rawType, dataTypeIndex, name) => {+ var typeMapping = [ Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];+ var TA = typeMapping[dataTypeIndex];+ function decodeMemoryView(handle) {+ var size = HEAPU32[((handle) >> 2)];+ var data = HEAPU32[(((handle) + (4)) >> 2)];+ return new TA(HEAP8.buffer, data, size);+ }+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: decodeMemoryView,+ readValueFromPointer: decodeMemoryView+ }, {+ ignoreDuplicateRegistrations: true+ });+};++var __embind_register_std_string = (rawType, name) => {+ name = AsciiToString(name);+ var stdStringIsUTF8 = true;+ registerType(rawType, {+ name,+ // For some method names we use string keys here since they are part of+ // the public/external API and/or used by the runtime-generated code.+ fromWireType(value) {+ var length = HEAPU32[((value) >> 2)];+ var payload = value + 4;+ var str;+ if (stdStringIsUTF8) {+ str = UTF8ToString(payload, length, true);+ } else {+ str = "";+ for (var i = 0; i < length; ++i) {+ str += String.fromCharCode(HEAPU8[payload + i]);+ }+ }+ _free(value);+ return str;+ },+ toWireType(destructors, value) {+ if (value instanceof ArrayBuffer) {+ value = new Uint8Array(value);+ }+ var length;+ var valueIsOfTypeString = (typeof value == "string");+ // We accept `string` or array views with single byte elements+ if (!(valueIsOfTypeString || (ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT == 1))) {+ throwBindingError("Cannot pass non-string to std::string");+ }+ if (stdStringIsUTF8 && valueIsOfTypeString) {+ length = lengthBytesUTF8(value);+ } else {+ length = value.length;+ }+ // assumes POINTER_SIZE alignment+ var base = _malloc(4 + length + 1);+ var ptr = base + 4;+ HEAPU32[((base) >> 2)] = length;+ if (valueIsOfTypeString) {+ if (stdStringIsUTF8) {+ stringToUTF8(value, ptr, length + 1);+ } else {+ for (var i = 0; i < length; ++i) {+ var charCode = value.charCodeAt(i);+ if (charCode > 255) {+ _free(base);+ throwBindingError("String has UTF-16 code units that do not fit in 8 bits");+ }+ HEAPU8[ptr + i] = charCode;+ }+ }+ } else {+ HEAPU8.set(value, ptr);+ }+ if (destructors !== null) {+ destructors.push(_free, base);+ }+ return base;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var UTF16Decoder = new TextDecoder("utf-16le");++var UTF16ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var idx = ((ptr) >> 1);+ var endIdx = findStringEnd(HEAPU16, idx, maxBytesToRead / 2, ignoreNul);+ return UTF16Decoder.decode(HEAPU16.subarray(idx, endIdx));+};++var stringToUTF16 = (str, outPtr, maxBytesToWrite = 2147483647) => {+ if (maxBytesToWrite < 2) return 0;+ maxBytesToWrite -= 2;+ // Null terminator.+ var startPtr = outPtr;+ var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length;+ for (var i = 0; i < numCharsToWrite; ++i) {+ // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.+ var codeUnit = str.charCodeAt(i);+ // possibly a lead surrogate+ HEAP16[((outPtr) >> 1)] = codeUnit;+ outPtr += 2;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP16[((outPtr) >> 1)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF16 = str => str.length * 2;++var UTF32ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var str = "";+ var startIdx = ((ptr) >> 2);+ // If maxBytesToRead is not passed explicitly, it will be undefined, and this+ // will always evaluate to true. This saves on code size.+ for (var i = 0; !(i >= maxBytesToRead / 4); i++) {+ var utf32 = HEAPU32[startIdx + i];+ if (!utf32 && !ignoreNul) break;+ str += String.fromCodePoint(utf32);+ }+ return str;+};++var stringToUTF32 = (str, outPtr, maxBytesToWrite = 2147483647) => {+ if (maxBytesToWrite < 4) return 0;+ var startPtr = outPtr;+ var endPtr = startPtr + maxBytesToWrite - 4;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ HEAP32[((outPtr) >> 2)] = codePoint;+ outPtr += 4;+ if (outPtr + 4 > endPtr) break;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP32[((outPtr) >> 2)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF32 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ len += 4;+ }+ return len;+};++var __embind_register_std_wstring = (rawType, charSize, name) => {+ name = AsciiToString(name);+ var decodeString, encodeString, lengthBytesUTF;+ if (charSize === 2) {+ decodeString = UTF16ToString;+ encodeString = stringToUTF16;+ lengthBytesUTF = lengthBytesUTF16;+ } else {+ decodeString = UTF32ToString;+ encodeString = stringToUTF32;+ lengthBytesUTF = lengthBytesUTF32;+ }+ registerType(rawType, {+ name,+ fromWireType: value => {+ // Code mostly taken from _embind_register_std_string fromWireType+ var length = HEAPU32[((value) >> 2)];+ var str = decodeString(value + 4, length * charSize, true);+ _free(value);+ return str;+ },+ toWireType: (destructors, value) => {+ if (!(typeof value == "string")) {+ throwBindingError(`Cannot pass non-string to C++ string type ${name}`);+ }+ // assumes POINTER_SIZE alignment+ var length = lengthBytesUTF(value);+ var ptr = _malloc(4 + length + charSize);+ HEAPU32[((ptr) >> 2)] = length / charSize;+ encodeString(value, ptr + 4, length + charSize);+ if (destructors !== null) {+ destructors.push(_free, ptr);+ }+ return ptr;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var __embind_register_void = (rawType, name) => {+ name = AsciiToString(name);+ registerType(rawType, {+ isVoid: true,+ // void return values can be optimized out sometimes+ name,+ fromWireType: () => undefined,+ // TODO: assert if anything else is given?+ toWireType: (destructors, o) => undefined+ });+};++var emval_methodCallers = [];++var emval_addMethodCaller = caller => {+ var id = emval_methodCallers.length;+ emval_methodCallers.push(caller);+ return id;+};++var getTypeName = type => {+ var ptr = ___getTypeName(type);+ var rv = AsciiToString(ptr);+ _free(ptr);+ return rv;+};++var requireRegisteredType = (rawType, humanName) => {+ var impl = registeredTypes[rawType];+ if (undefined === impl) {+ throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`);+ }+ return impl;+};++var emval_lookupTypes = (argCount, argTypes) => {+ var a = new Array(argCount);+ for (var i = 0; i < argCount; ++i) {+ a[i] = requireRegisteredType(HEAPU32[(((argTypes) + (i * 4)) >> 2)], `parameter ${i}`);+ }+ return a;+};++var createNamedFunction = (name, func) => Object.defineProperty(func, "name", {+ value: name+});++var emval_returnValue = (toReturnWire, destructorsRef, handle) => {+ var destructors = [];+ var result = toReturnWire(destructors, handle);+ if (destructors.length) {+ // void, primitives and any other types w/o destructors don't need to allocate a handle+ HEAPU32[((destructorsRef) >> 2)] = Emval.toHandle(destructors);+ }+ return result;+};++var emval_symbols = {};++var getStringOrSymbol = address => {+ var symbol = emval_symbols[address];+ if (symbol === undefined) {+ return AsciiToString(address);+ }+ return symbol;+};++var __emval_create_invoker = (argCount, argTypesPtr, kind) => {+ var GenericWireTypeSize = 8;+ var [retType, ...argTypes] = emval_lookupTypes(argCount, argTypesPtr);+ var toReturnWire = retType.toWireType.bind(retType);+ var argFromPtr = argTypes.map(type => type.readValueFromPointer.bind(type));+ argCount--;+ // remove the extracted return type+ var argN = new Array(argCount);+ var invokerFunction = (handle, methodName, destructorsRef, args) => {+ var offset = 0;+ for (var i = 0; i < argCount; ++i) {+ argN[i] = argFromPtr[i](args + offset);+ offset += GenericWireTypeSize;+ }+ var rv;+ switch (kind) {+ case 0:+ rv = Emval.toValue(handle).apply(null, argN);+ break;++ case 2:+ rv = Reflect.construct(Emval.toValue(handle), argN);+ break;++ case 3:+ // no-op, just return the argument+ rv = argN[0];+ break;++ case 1:+ rv = Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);+ break;+ }+ return emval_returnValue(toReturnWire, destructorsRef, rv);+ };+ var functionName = `methodCaller<(${argTypes.map(t => t.name)}) => ${retType.name}>`;+ return emval_addMethodCaller(createNamedFunction(functionName, invokerFunction));+};++var __emval_get_global = name => {+ if (!name) {+ return Emval.toHandle(globalThis);+ }+ name = getStringOrSymbol(name);+ return Emval.toHandle(globalThis[name]);+};++var __emval_get_property = (handle, key) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ return Emval.toHandle(handle[key]);+};++var __emval_incref = handle => {+ if (handle > 9) {+ emval_handles[handle + 1] += 1;+ }+};++var __emval_instanceof = (object, constructor) => {+ object = Emval.toValue(object);+ constructor = Emval.toValue(constructor);+ return object instanceof constructor;+};++var __emval_invoke = (caller, handle, methodName, destructorsRef, args) => emval_methodCallers[caller](handle, methodName, destructorsRef, args);++var __emval_new_cstring = v => Emval.toHandle(getStringOrSymbol(v));++var runDestructors = destructors => {+ while (destructors.length) {+ var ptr = destructors.pop();+ var del = destructors.pop();+ del(ptr);+ }+};++var __emval_run_destructors = handle => {+ var destructors = Emval.toValue(handle);+ runDestructors(destructors);+ __emval_decref(handle);+};++var __emval_set_property = (handle, key, value) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ value = Emval.toValue(value);+ handle[key] = value;+};++var __emval_typeof = handle => {+ handle = Emval.toValue(handle);+ return Emval.toHandle(typeof handle);+};++function __gmtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ if (isNaN(date.getTime())) {+ return 1;+ }+ HEAP32[((tmPtr) >> 2)] = date.getUTCSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getUTCMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getUTCHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getUTCDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getUTCMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getUTCFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getUTCDay();+ var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);+ var yday = ((date.getTime() - start) / (1e3 * 60 * 60 * 24)) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ return 0;+}++var isLeapYear = year => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);++var MONTH_DAYS_LEAP_CUMULATIVE = [ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 ];++var MONTH_DAYS_REGULAR_CUMULATIVE = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ];++var ydayFromDate = date => {+ var leap = isLeapYear(date.getFullYear());+ var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE);+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;+ // -1 since it's days since Jan 1+ return yday;+};++function __localtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ if (isNaN(date.getTime())) {+ return 1;+ }+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ HEAP32[(((tmPtr) + (36)) >> 2)] = -(date.getTimezoneOffset() * 60);+ // Attention: DST is in December in South, and some regions don't have DST at all.+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;+ HEAP32[(((tmPtr) + (32)) >> 2)] = dst;+ return 0;+}++var setTempRet0 = val => __emscripten_tempret_set(val);++var __mktime_js = function(tmPtr) {+ var ret = (() => {+ var date = new Date(HEAP32[(((tmPtr) + (20)) >> 2)] + 1900, HEAP32[(((tmPtr) + (16)) >> 2)], HEAP32[(((tmPtr) + (12)) >> 2)], HEAP32[(((tmPtr) + (8)) >> 2)], HEAP32[(((tmPtr) + (4)) >> 2)], HEAP32[((tmPtr) >> 2)], 0);+ if (isNaN(date.getTime())) {+ return -1;+ }+ // There's an ambiguous hour when the time goes back; the tm_isdst field is+ // used to disambiguate it. Date() basically guesses, so we fix it up if it+ // guessed wrong, or fill in tm_isdst with the guess if it's -1.+ var dst = HEAP32[(((tmPtr) + (32)) >> 2)];+ var guessedOffset = date.getTimezoneOffset();+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dstOffset = Math.min(winterOffset, summerOffset);+ // DST is in December in South+ if (dst < 0) {+ // Attention: some regions don't have DST at all.+ dst = Number(summerOffset != winterOffset && dstOffset == guessedOffset);+ } else if ((dst > 0) != (dstOffset == guessedOffset)) {+ var nonDstOffset = Math.max(winterOffset, summerOffset);+ var trueOffset = dst > 0 ? dstOffset : nonDstOffset;+ // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up.+ date.setTime(date.getTime() + (trueOffset - guessedOffset) * 6e4);+ if (isNaN(date.getTime())) {+ return -1;+ }+ }+ HEAP32[(((tmPtr) + (32)) >> 2)] = dst;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ // To match expected behavior, update fields from date+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getYear();+ // Return time in seconds+ return date.getTime() / 1e3;+ })();+ return (setTempRet0((tempDouble = ret, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0)),+ ret >>> 0);+};++function __mmap_js(len, prot, flags, fd, offset_low, offset_high, allocated, addr) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var res = FS.mmap(stream, len, offset, prot, flags);+ var ptr = res.ptr;+ HEAP32[((allocated) >> 2)] = res.allocated;+ HEAPU32[((addr) >> 2)] = ptr;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function __munmap_js(addr, len, prot, flags, fd, offset_low, offset_high) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ if (prot & 2) {+ SYSCALLS.doMsync(addr, stream, len, flags, offset);+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __tzset_js = (timezone, daylight, std_name, dst_name) => {+ // TODO: Use (malleable) environment variables instead of system settings.+ var currentYear = (new Date).getFullYear();+ var winter = new Date(currentYear, 0, 1);+ var summer = new Date(currentYear, 6, 1);+ var winterOffset = winter.getTimezoneOffset();+ var summerOffset = summer.getTimezoneOffset();+ // Local standard timezone offset. Local standard time is not adjusted for+ // daylight savings. This code uses the fact that getTimezoneOffset returns+ // a greater value during Standard Time versus Daylight Saving Time (DST).+ // Thus it determines the expected output during Standard Time, and it+ // compares whether the output of the given date the same (Standard) or less+ // (DST).+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);+ // timezone is specified as seconds west of UTC ("The external variable+ // `timezone` shall be set to the difference, in seconds, between+ // Coordinated Universal Time (UTC) and local standard time."), the same+ // as returned by stdTimezoneOffset.+ // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html+ HEAPU32[((timezone) >> 2)] = stdTimezoneOffset * 60;+ HEAP32[((daylight) >> 2)] = Number(winterOffset != summerOffset);+ var extractZone = timezoneOffset => {+ // Why inverse sign?+ // Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset+ var sign = timezoneOffset >= 0 ? "-" : "+";+ var absOffset = Math.abs(timezoneOffset);+ var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");+ var minutes = String(absOffset % 60).padStart(2, "0");+ return `UTC${sign}${hours}${minutes}`;+ };+ var winterName = extractZone(winterOffset);+ var summerName = extractZone(summerOffset);+ if (summerOffset < winterOffset) {+ // Northern hemisphere+ stringToUTF8(winterName, std_name, 17);+ stringToUTF8(summerName, dst_name, 17);+ } else {+ stringToUTF8(winterName, dst_name, 17);+ stringToUTF8(summerName, std_name, 17);+ }+};++var _emscripten_get_now = () => performance.now();++var _emscripten_date_now = () => Date.now();++var nowIsMonotonic = 1;++var checkWasiClock = clock_id => clock_id >= 0 && clock_id <= 3;++function _clock_time_get(clk_id, ignored_precision_low, ignored_precision_high, ptime) {+ var ignored_precision = convertI32PairToI53Checked(ignored_precision_low, ignored_precision_high);+ if (!checkWasiClock(clk_id)) {+ return 28;+ }+ var now;+ // all wasi clocks but realtime are monotonic+ if (clk_id === 0) {+ now = _emscripten_date_now();+ } else if (nowIsMonotonic) {+ now = _emscripten_get_now();+ } else {+ return 52;+ }+ // "now" is in ms, and wasi times are in ns.+ var nsec = Math.round(now * 1e3 * 1e3);+ (tempI64 = [ nsec >>> 0, (tempDouble = nsec, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((ptime) >> 2)] = tempI64[0], HEAP32[(((ptime) + (4)) >> 2)] = tempI64[1]);+ return 0;+}++var readEmAsmArgsArray = [];++var readEmAsmArgs = (sigPtr, buf) => {+ readEmAsmArgsArray.length = 0;+ var ch;+ // Most arguments are i32s, so shift the buffer pointer so it is a plain+ // index into HEAP32.+ while (ch = HEAPU8[sigPtr++]) {+ // Floats are always passed as doubles, so all types except for 'i'+ // are 8 bytes and require alignment.+ var wide = (ch != 105);+ wide &= (ch != 112);+ buf += wide && (buf % 8) ? 4 : 0;+ readEmAsmArgsArray.push(// Special case for pointers under wasm64 or CAN_ADDRESS_2GB mode.+ ch == 112 ? HEAPU32[((buf) >> 2)] : ch == 105 ? HEAP32[((buf) >> 2)] : HEAPF64[((buf) >> 3)]);+ buf += wide ? 8 : 4;+ }+ return readEmAsmArgsArray;+};++var runEmAsmFunction = (code, sigPtr, argbuf) => {+ var args = readEmAsmArgs(sigPtr, argbuf);+ return ASM_CONSTS[code](...args);+};++var _emscripten_asm_const_int = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_asm_const_ptr = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_errn = (str, len) => err(UTF8ToString(str, len));++var getHeapMax = () => // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate+// full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side+// for any code that deals with heap sizes, which would require special+// casing all heap size related code to treat 0 specially.+2147483648;++var _emscripten_get_heap_max = () => getHeapMax();++var _emscripten_has_asyncify = () => 0;++var _emscripten_outn = (str, len) => out(UTF8ToString(str, len));++var UNWIND_CACHE = {};++var stringToNewUTF8 = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = _malloc(size);+ if (ret) stringToUTF8(str, ret, size);+ return ret;+};++/** @returns {number} */ var convertFrameToPC = frame => {+ var match;+ if (match = /\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(frame)) {+ // Wasm engines give the binary offset directly, so we use that as return address+ return +match[1];+ } else if (match = /:(\d+):\d+(?:\)|$)/.exec(frame)) {+ // If we are in js, we can use the js line number as the "return address".+ // This should work for wasm2js. We tag the high bit to distinguish this+ // from wasm addresses.+ return 2147483648 | +match[1];+ }+ // return 0 if we can't find any+ return 0;+};++var saveInUnwindCache = callstack => {+ for (var line of callstack) {+ var pc = convertFrameToPC(line);+ if (pc) {+ UNWIND_CACHE[pc] = line;+ }+ }+};++var jsStackTrace = () => (new Error).stack.toString();++var _emscripten_stack_snapshot = () => {+ var callstack = jsStackTrace().split("\n");+ if (callstack[0] == "Error") {+ callstack.shift();+ }+ saveInUnwindCache(callstack);+ // Caches the stack snapshot so that emscripten_stack_unwind_buffer() can+ // unwind from this spot.+ UNWIND_CACHE.last_addr = convertFrameToPC(callstack[3]);+ UNWIND_CACHE.last_stack = callstack;+ return UNWIND_CACHE.last_addr;+};++var _emscripten_pc_get_function = pc => {+ var frame = UNWIND_CACHE[pc];+ if (!frame) return 0;+ var name;+ var match;+ // First try to match foo.wasm.sym files explcitly. e.g.+ // at test_return_address.wasm.main (wasm://wasm/test_return_address.wasm-0012cc2a:wasm-function[26]:0x9f3+ // Then match JS symbols which don't include that module name:+ // at invokeEntryPoint (.../test_return_address.js:1500:42)+ // Finally match firefox format:+ // Object._main@http://server.com:4324:12'+ if (match = /^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^\s+at (.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^(.+?)@/.exec(frame)) {+ name = match[1];+ } else {+ return 0;+ }+ _free(_emscripten_pc_get_function.ret ?? 0);+ _emscripten_pc_get_function.ret = stringToNewUTF8(name);+ return _emscripten_pc_get_function.ret;+};++var growMemory = size => {+ var oldHeapSize = wasmMemory.buffer.byteLength;+ var pages = ((size - oldHeapSize + 65535) / 65536) | 0;+ try {+ // round size grow request up to wasm page size (fixed 64KB per spec)+ wasmMemory.grow(pages);+ // .grow() takes a delta compared to the previous size+ updateMemoryViews();+ return 1;+ } catch (e) {}+};++var _emscripten_resize_heap = requestedSize => {+ var oldSize = HEAPU8.length;+ // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.+ requestedSize >>>= 0;+ // With multithreaded builds, races can happen (another thread might increase the size+ // in between), so return a failure, and let the caller retry.+ // Memory resize rules:+ // 1. Always increase heap size to at least the requested size, rounded up+ // to next page multiple.+ // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap+ // geometrically: increase the heap size according to+ // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most+ // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).+ // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap+ // linearly: increase the heap size by at least+ // MEMORY_GROWTH_LINEAR_STEP bytes.+ // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by+ // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest+ // 4. If we were unable to allocate as much memory, it may be due to+ // over-eager decision to excessively reserve due to (3) above.+ // Hence if an allocation fails, cut down on the amount of excess+ // growth, in an attempt to succeed to perform a smaller allocation.+ // A limit is set for how much we can grow. We should not exceed that+ // (the wasm binary specifies it, so if we tried, we'd fail anyhow).+ var maxHeapSize = getHeapMax();+ if (requestedSize > maxHeapSize) {+ return false;+ }+ // Loop through potential heap size increases. If we attempt a too eager+ // reservation that fails, cut down on the attempted size and reserve a+ // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {+ var overGrownHeapSize = oldSize * (1 + .2 / cutDown);+ // ensure geometric growth+ // but limit overreserving (default to capping at +96MB overgrowth at most)+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));+ var replacement = growMemory(newSize);+ if (replacement) {+ return true;+ }+ }+ return false;+};++var _emscripten_stack_unwind_buffer = (addr, buffer, count) => {+ var stack;+ if (UNWIND_CACHE.last_addr == addr) {+ stack = UNWIND_CACHE.last_stack;+ } else {+ stack = jsStackTrace().split("\n");+ if (stack[0] == "Error") {+ stack.shift();+ }+ saveInUnwindCache(stack);+ }+ var offset = 3;+ while (stack[offset] && convertFrameToPC(stack[offset]) != addr) {+ ++offset;+ }+ for (var i = 0; i < count && stack[i + offset]; ++i) {+ HEAPU32[(((buffer) + (i * 4)) >> 2)] = convertFrameToPC(stack[i + offset]);+ }+ return i;+};++var GLctx;++var webgl_enable_ANGLE_instanced_arrays = ctx => {+ // Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("ANGLE_instanced_arrays");+ // Because this extension is a core function in WebGL 2, assign the extension entry points in place of+ // where the core functions will reside in WebGL 2. This way the calling code can call these without+ // having to dynamically branch depending if running against WebGL 1 or WebGL 2.+ if (ext) {+ ctx["vertexAttribDivisor"] = (index, divisor) => ext["vertexAttribDivisorANGLE"](index, divisor);+ ctx["drawArraysInstanced"] = (mode, first, count, primcount) => ext["drawArraysInstancedANGLE"](mode, first, count, primcount);+ ctx["drawElementsInstanced"] = (mode, count, type, indices, primcount) => ext["drawElementsInstancedANGLE"](mode, count, type, indices, primcount);+ return 1;+ }+};++var webgl_enable_OES_vertex_array_object = ctx => {+ // Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("OES_vertex_array_object");+ if (ext) {+ ctx["createVertexArray"] = () => ext["createVertexArrayOES"]();+ ctx["deleteVertexArray"] = vao => ext["deleteVertexArrayOES"](vao);+ ctx["bindVertexArray"] = vao => ext["bindVertexArrayOES"](vao);+ ctx["isVertexArray"] = vao => ext["isVertexArrayOES"](vao);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_buffers = ctx => {+ // Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("WEBGL_draw_buffers");+ if (ext) {+ ctx["drawBuffers"] = (n, bufs) => ext["drawBuffersWEBGL"](n, bufs);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance = ctx => // Closure is expected to be allowed to minify the '.dibvbi' property, so not accessing it quoted.+!!(ctx.dibvbi = ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));++var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance = ctx => !!(ctx.mdibvbi = ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));++var webgl_enable_EXT_polygon_offset_clamp = ctx => !!(ctx.extPolygonOffsetClamp = ctx.getExtension("EXT_polygon_offset_clamp"));++var webgl_enable_EXT_clip_control = ctx => !!(ctx.extClipControl = ctx.getExtension("EXT_clip_control"));++var webgl_enable_WEBGL_polygon_mode = ctx => !!(ctx.webglPolygonMode = ctx.getExtension("WEBGL_polygon_mode"));++var webgl_enable_WEBGL_multi_draw = ctx => // Closure is expected to be allowed to minify the '.multiDrawWebgl' property, so not accessing it quoted.+!!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw"));++var getEmscriptenSupportedExtensions = ctx => {+ // Restrict the list of advertised extensions to those that we actually+ // support.+ var supportedExtensions = [ // WebGL 1 extensions+ "ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_disjoint_timer_query", "EXT_frag_depth", "EXT_shader_texture_lod", "EXT_sRGB", "OES_element_index_uint", "OES_fbo_render_mipmap", "OES_standard_derivatives", "OES_texture_float", "OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object", "WEBGL_color_buffer_float", "WEBGL_depth_texture", "WEBGL_draw_buffers", // WebGL 2 extensions+ "EXT_color_buffer_float", "EXT_conservative_depth", "EXT_disjoint_timer_query_webgl2", "EXT_texture_norm16", "NV_shader_noperspective_interpolation", "WEBGL_clip_cull_distance", // WebGL 1 and WebGL 2 extensions+ "EXT_clip_control", "EXT_color_buffer_half_float", "EXT_depth_clamp", "EXT_float_blend", "EXT_polygon_offset_clamp", "EXT_texture_compression_bptc", "EXT_texture_compression_rgtc", "EXT_texture_filter_anisotropic", "KHR_parallel_shader_compile", "OES_texture_float_linear", "WEBGL_blend_func_extended", "WEBGL_compressed_texture_astc", "WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1", "WEBGL_compressed_texture_s3tc", "WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders", "WEBGL_lose_context", "WEBGL_multi_draw", "WEBGL_polygon_mode" ];+ // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.+ return ctx.getSupportedExtensions()?.filter(ext => supportedExtensions.includes(ext)) ?? [];+};++var registerPreMainLoop = f => {+ // Does nothing unless $MainLoop is included/used.+ typeof MainLoop != "undefined" && MainLoop.preMainLoop.push(f);+};++var webglBufferSubData = (target, offset, size, data, src = HEAPU8) => {+ if (GL.currentContext.version >= 2) {+ size && GLctx.bufferSubData(target, offset, src, data, size);+ return;+ }+ GLctx.bufferSubData(target, offset, src.subarray(data, data + size));+};++var GL = {+ counter: 1,+ buffers: [],+ mappedBuffers: {},+ programs: [],+ framebuffers: [],+ renderbuffers: [],+ textures: [],+ shaders: [],+ vaos: [],+ contexts: [],+ offscreenCanvases: {},+ queries: [],+ samplers: [],+ transformFeedbacks: [],+ syncs: [],+ byteSizeByTypeRoot: 5120,+ byteSizeByType: [ 1, 1, 2, 2, 4, 4, 4, 2, 3, 4, 8 ],+ stringCache: {},+ stringiCache: {},+ unpackAlignment: 4,+ unpackRowLength: 0,+ recordError: errorCode => {+ if (!GL.lastError) {+ GL.lastError = errorCode;+ }+ },+ getNewId: table => {+ var ret = GL.counter++;+ for (var i = table.length; i < ret; i++) {+ table[i] = null;+ }+ // Skip over any non-null elements that might have been created by+ // glBindBuffer.+ while (table[ret]) {+ ret = GL.counter++;+ }+ return ret;+ },+ genObject: (n, buffers, createFunction, objectTable) => {+ for (var i = 0; i < n; i++) {+ var buffer = GLctx[createFunction]();+ var id = buffer && GL.getNewId(objectTable);+ if (buffer) {+ buffer.name = id;+ objectTable[id] = buffer;+ } else {+ GL.recordError(1282);+ }+ HEAP32[(((buffers) + (i * 4)) >> 2)] = id;+ }+ },+ MAX_TEMP_BUFFER_SIZE: 2097152,+ numTempVertexBuffersPerSize: 64,+ log2ceilLookup: i => 32 - Math.clz32(i ? i - 1 : 0),+ generateTempBuffers: (quads, context) => {+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ context.tempVertexBufferCounters1 = [];+ context.tempVertexBufferCounters2 = [];+ context.tempVertexBufferCounters1.length = context.tempVertexBufferCounters2.length = largestIndex + 1;+ context.tempVertexBuffers1 = [];+ context.tempVertexBuffers2 = [];+ context.tempVertexBuffers1.length = context.tempVertexBuffers2.length = largestIndex + 1;+ context.tempIndexBuffers = [];+ context.tempIndexBuffers.length = largestIndex + 1;+ for (var i = 0; i <= largestIndex; ++i) {+ context.tempIndexBuffers[i] = null;+ // Created on-demand+ context.tempVertexBufferCounters1[i] = context.tempVertexBufferCounters2[i] = 0;+ var ringbufferLength = GL.numTempVertexBuffersPerSize;+ context.tempVertexBuffers1[i] = [];+ context.tempVertexBuffers2[i] = [];+ var ringbuffer1 = context.tempVertexBuffers1[i];+ var ringbuffer2 = context.tempVertexBuffers2[i];+ ringbuffer1.length = ringbuffer2.length = ringbufferLength;+ for (var j = 0; j < ringbufferLength; ++j) {+ ringbuffer1[j] = ringbuffer2[j] = null;+ }+ }+ if (quads) {+ // GL_QUAD indexes can be precalculated+ context.tempQuadIndexBuffer = GLctx.createBuffer();+ context.GLctx.bindBuffer(34963, context.tempQuadIndexBuffer);+ var numIndexes = GL.MAX_TEMP_BUFFER_SIZE >> 1;+ var quadIndexes = new Uint16Array(numIndexes);+ var i = 0, v = 0;+ while (1) {+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 1;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 3;+ if (i >= numIndexes) break;+ v += 4;+ }+ context.GLctx.bufferData(34963, quadIndexes, 35044);+ context.GLctx.bindBuffer(34963, null);+ }+ },+ getTempVertexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ringbuffer = GL.currentContext.tempVertexBuffers1[idx];+ var nextFreeBufferIndex = GL.currentContext.tempVertexBufferCounters1[idx];+ GL.currentContext.tempVertexBufferCounters1[idx] = (GL.currentContext.tempVertexBufferCounters1[idx] + 1) & (GL.numTempVertexBuffersPerSize - 1);+ var vbo = ringbuffer[nextFreeBufferIndex];+ if (vbo) {+ return vbo;+ }+ var prevVBO = GLctx.getParameter(34964);+ ringbuffer[nextFreeBufferIndex] = GLctx.createBuffer();+ GLctx.bindBuffer(34962, ringbuffer[nextFreeBufferIndex]);+ GLctx.bufferData(34962, 1 << idx, 35048);+ GLctx.bindBuffer(34962, prevVBO);+ return ringbuffer[nextFreeBufferIndex];+ },+ getTempIndexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ibo = GL.currentContext.tempIndexBuffers[idx];+ if (ibo) {+ return ibo;+ }+ var prevIBO = GLctx.getParameter(34965);+ GL.currentContext.tempIndexBuffers[idx] = GLctx.createBuffer();+ GLctx.bindBuffer(34963, GL.currentContext.tempIndexBuffers[idx]);+ GLctx.bufferData(34963, 1 << idx, 35048);+ GLctx.bindBuffer(34963, prevIBO);+ return GL.currentContext.tempIndexBuffers[idx];+ },+ newRenderingFrameStarted: () => {+ if (!GL.currentContext) {+ return;+ }+ var vb = GL.currentContext.tempVertexBuffers1;+ GL.currentContext.tempVertexBuffers1 = GL.currentContext.tempVertexBuffers2;+ GL.currentContext.tempVertexBuffers2 = vb;+ vb = GL.currentContext.tempVertexBufferCounters1;+ GL.currentContext.tempVertexBufferCounters1 = GL.currentContext.tempVertexBufferCounters2;+ GL.currentContext.tempVertexBufferCounters2 = vb;+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ for (var i = 0; i <= largestIndex; ++i) {+ GL.currentContext.tempVertexBufferCounters1[i] = 0;+ }+ },+ getSource: (shader, count, string, length) => {+ var source = "";+ for (var i = 0; i < count; ++i) {+ var len = length ? HEAPU32[(((length) + (i * 4)) >> 2)] : undefined;+ source += UTF8ToString(HEAPU32[(((string) + (i * 4)) >> 2)], len);+ }+ return source;+ },+ calcBufLength: (size, type, stride, count) => {+ if (stride > 0) {+ return count * stride;+ }+ var typeSize = GL.byteSizeByType[type - GL.byteSizeByTypeRoot];+ return size * typeSize * count;+ },+ usedTempBuffers: [],+ preDrawHandleClientVertexAttribBindings: count => {+ GL.resetBufferBinding = false;+ // TODO: initial pass to detect ranges we need to upload, might not need+ // an upload per attrib+ for (var i = 0; i < GL.currentContext.maxVertexAttribs; ++i) {+ var cb = GL.currentContext.clientBuffers[i];+ if (!cb.clientside || !cb.enabled) continue;+ GL.resetBufferBinding = true;+ var size = GL.calcBufLength(cb.size, cb.type, cb.stride, count);+ var buf = GL.getTempVertexBuffer(size);+ GLctx.bindBuffer(34962, buf);+ webglBufferSubData(34962, 0, size, cb.ptr);+ cb.vertexAttribPointerAdaptor.call(GLctx, i, cb.size, cb.type, cb.normalized, cb.stride, 0);+ }+ },+ postDrawHandleClientVertexAttribBindings: () => {+ if (GL.resetBufferBinding) {+ GLctx.bindBuffer(34962, GL.buffers[GLctx.currentArrayBufferBinding]);+ }+ },+ createContext: (/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) => {+ // BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL+ // context on a canvas, calling .getContext() will always return that+ // context independent of which 'webgl' or 'webgl2'+ // context version was passed. See:+ // https://webkit.org/b/222758+ // and:+ // https://github.com/emscripten-core/emscripten/issues/13295.+ // TODO: Once the bug is fixed and shipped in Safari, adjust the Safari+ // version field in above check.+ if (!canvas.getContextSafariWebGL2Fixed) {+ canvas.getContextSafariWebGL2Fixed = canvas.getContext;+ /** @type {function(this:HTMLCanvasElement, string, (Object|null)=): (Object|null)} */ function fixedGetContext(ver, attrs) {+ var gl = canvas.getContextSafariWebGL2Fixed(ver, attrs);+ return ((ver == "webgl") == (gl instanceof WebGLRenderingContext)) ? gl : null;+ }+ canvas.getContext = fixedGetContext;+ }+ var ctx = (webGLContextAttributes.majorVersion > 1) ? canvas.getContext("webgl2", webGLContextAttributes) : canvas.getContext("webgl", webGLContextAttributes);+ if (!ctx) return 0;+ var handle = GL.registerContext(ctx, webGLContextAttributes);+ return handle;+ },+ registerContext: (ctx, webGLContextAttributes) => {+ // without pthreads a context is just an integer ID+ var handle = GL.getNewId(GL.contexts);+ var context = {+ handle,+ attributes: webGLContextAttributes,+ version: webGLContextAttributes.majorVersion,+ GLctx: ctx+ };+ // Store the created context object so that we can access the context+ // given a canvas without having to pass the parameters again.+ if (ctx.canvas) ctx.canvas.GLctxObject = context;+ GL.contexts[handle] = context;+ if (typeof webGLContextAttributes.enableExtensionsByDefault == "undefined" || webGLContextAttributes.enableExtensionsByDefault) {+ GL.initExtensions(context);+ }+ context.maxVertexAttribs = context.GLctx.getParameter(34921);+ context.clientBuffers = [];+ for (var i = 0; i < context.maxVertexAttribs; i++) {+ context.clientBuffers[i] = {+ enabled: false,+ clientside: false,+ size: 0,+ type: 0,+ normalized: 0,+ stride: 0,+ ptr: 0,+ vertexAttribPointerAdaptor: null+ };+ }+ GL.generateTempBuffers(false, context);+ return handle;+ },+ makeContextCurrent: contextHandle => {+ // Active Emscripten GL layer context object.+ GL.currentContext = GL.contexts[contextHandle];+ // Active WebGL context object.+ Module["ctx"] = GLctx = GL.currentContext?.GLctx;+ return !(contextHandle && !GLctx);+ },+ getContext: contextHandle => GL.contexts[contextHandle],+ deleteContext: contextHandle => {+ if (GL.currentContext === GL.contexts[contextHandle]) {+ GL.currentContext = null;+ }+ if (typeof JSEvents == "object") {+ // Release all JS event handlers on the DOM element that the GL context is+ // associated with since the context is now deleted.+ JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas);+ }+ // Make sure the canvas object no longer refers to the context object so+ // there are no GC surprises.+ if (GL.contexts[contextHandle]?.GLctx.canvas) {+ GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined;+ }+ GL.contexts[contextHandle] = null;+ },+ initExtensions: context => {+ // If this function is called without a specific context object, init the+ // extensions of the currently active context.+ context ||= GL.currentContext;+ if (context.initExtensionsDone) return;+ context.initExtensionsDone = true;+ var GLctx = context.GLctx;+ // Detect the presence of a few extensions manually, since the GL interop+ // layer itself will need to know if they exist.+ // Extensions that are available in both WebGL 1 and WebGL 2+ webgl_enable_WEBGL_multi_draw(GLctx);+ webgl_enable_EXT_polygon_offset_clamp(GLctx);+ webgl_enable_EXT_clip_control(GLctx);+ webgl_enable_WEBGL_polygon_mode(GLctx);+ // Extensions that are only available in WebGL 1 (the calls will be no-ops+ // if called on a WebGL 2 context active)+ webgl_enable_ANGLE_instanced_arrays(GLctx);+ webgl_enable_OES_vertex_array_object(GLctx);+ webgl_enable_WEBGL_draw_buffers(GLctx);+ // Extensions that are available from WebGL >= 2 (no-op if called on a WebGL 1 context active)+ webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);+ webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);+ // On WebGL 2, EXT_disjoint_timer_query is replaced with an alternative+ // that's based on core APIs, and exposes only the queryCounterEXT()+ // entrypoint.+ if (context.version >= 2) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query_webgl2");+ }+ // However, Firefox exposes the WebGL 1 version on WebGL 2 as well and+ // thus we look for the WebGL 1 version again if the WebGL 2 version+ // isn't present. https://bugzil.la/1328882+ if (context.version < 2 || !GLctx.disjointTimerQueryExt) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query");+ }+ for (var ext of getEmscriptenSupportedExtensions(GLctx)) {+ // WEBGL_lose_context, WEBGL_debug_renderer_info and WEBGL_debug_shaders+ // are not enabled by default.+ if (!ext.includes("lose_context") && !ext.includes("debug")) {+ // Call .getExtension() to enable that extension permanently.+ GLctx.getExtension(ext);+ }+ }+ }+};++var webglPowerPreferences = [ "default", "low-power", "high-performance" ];++/** @type {Object} */ var specialHTMLTargets = [ 0, globalThis.document ?? 0, globalThis.window ?? 0 ];++var findEventTarget = target => {+ // The sensible 'default' target varies between events, but use window as the default+ // since DOM events mostly can default to that. Specific callback registrations+ // override their own defaults.+ if (!target) return window;+ if (typeof target == "number") target = specialHTMLTargets[target] || UTF8ToString(target);+ if (target === "#window") return window; else if (target === "#document") return document; else if (target === "#screen") return screen; else if (target === "#canvas") return Module["canvas"]; else if (typeof target == "string") return globalThis.document?.getElementById(target);+ return target;+};++var findCanvasEventTarget = target => {+ if (typeof target == "number") target = UTF8ToString(target);+ if (!target || target === "#canvas") {+ if (typeof GL != "undefined" && GL.offscreenCanvases["canvas"]) return GL.offscreenCanvases["canvas"];+ // TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line.+ return Module["canvas"];+ }+ if (typeof GL != "undefined" && GL.offscreenCanvases[target]) return GL.offscreenCanvases[target];+ return findEventTarget(target);+};++var _emscripten_webgl_do_create_context = (target, attributes) => {+ var attr32 = ((attributes) >> 2);+ var powerPreference = HEAP32[attr32 + (8 >> 2)];+ var contextAttributes = {+ "alpha": !!HEAP8[attributes + 0],+ "depth": !!HEAP8[attributes + 1],+ "stencil": !!HEAP8[attributes + 2],+ "antialias": !!HEAP8[attributes + 3],+ "premultipliedAlpha": !!HEAP8[attributes + 4],+ "preserveDrawingBuffer": !!HEAP8[attributes + 5],+ "powerPreference": webglPowerPreferences[powerPreference],+ "failIfMajorPerformanceCaveat": !!HEAP8[attributes + 12],+ "desynchronized": !!HEAP8[attributes + 33],+ // The following are not predefined WebGL context attributes in the WebGL specification, so the property names can be minified by Closure.+ majorVersion: HEAP32[attr32 + (16 >> 2)],+ minorVersion: HEAP32[attr32 + (20 >> 2)],+ enableExtensionsByDefault: HEAP8[attributes + 24],+ explicitSwapControl: HEAP8[attributes + 25],+ proxyContextToMainThread: HEAP32[attr32 + (28 >> 2)],+ renderViaOffscreenBackBuffer: HEAP8[attributes + 32]+ };+ var canvas = findCanvasEventTarget(target);+ if (!canvas) {+ return 0;+ }+ if (contextAttributes.explicitSwapControl) {+ return 0;+ }+ var contextHandle = GL.createContext(canvas, contextAttributes);+ return contextHandle;+};++var _emscripten_webgl_create_context = _emscripten_webgl_do_create_context;++var _emscripten_webgl_destroy_context = contextHandle => {+ if (GL.currentContext == contextHandle) GL.currentContext = 0;+ GL.deleteContext(contextHandle);+};++var _emscripten_webgl_get_context_attributes = (c, a) => {+ if (!a) return -5;+ c = GL.contexts[c];+ if (!c) return -3;+ var t = c.GLctx?.getContextAttributes();+ if (!t) return -3;+ HEAP8[a] = t.alpha;+ HEAP8[(a) + (1)] = t.depth;+ HEAP8[(a) + (2)] = t.stencil;+ HEAP8[(a) + (3)] = t.antialias;+ HEAP8[(a) + (4)] = t.premultipliedAlpha;+ HEAP8[(a) + (5)] = t.preserveDrawingBuffer;+ var power = t["powerPreference"] && webglPowerPreferences.indexOf(t["powerPreference"]);+ HEAP32[(((a) + (8)) >> 2)] = power;+ HEAP8[(a) + (12)] = t.failIfMajorPerformanceCaveat;+ HEAP8[(a) + (33)] = t.desynchronized;+ HEAP32[(((a) + (16)) >> 2)] = c.version;+ HEAP32[(((a) + (20)) >> 2)] = 0;+ HEAP8[(a) + (24)] = c.attributes.enableExtensionsByDefault;+ return 0;+};++var _emscripten_webgl_do_get_current_context = () => GL.currentContext ? GL.currentContext.handle : 0;++var _emscripten_webgl_get_current_context = _emscripten_webgl_do_get_current_context;++var _emscripten_webgl_make_context_current = contextHandle => {+ var success = GL.makeContextCurrent(contextHandle);+ return success ? 0 : -5;+};++var stackAlloc = sz => __emscripten_stack_alloc(sz);++var stringToUTF8OnStack = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = stackAlloc(size);+ stringToUTF8(str, ret, size);+ return ret;+};++var writeI53ToI64 = (ptr, num) => {+ HEAPU32[((ptr) >> 2)] = num;+ var lower = HEAPU32[((ptr) >> 2)];+ HEAPU32[(((ptr) + (4)) >> 2)] = (num - lower) / 4294967296;+};++var wasmTableMirror = [];++var getWasmTableEntry = funcPtr => {+ var func = wasmTableMirror[funcPtr];+ if (!func) {+ /** @suppress {checkTypes} */ wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);+ }+ return func;+};++var WebGPU = {+ Internals: {+ jsObjects: [],+ jsObjectInsert: (ptr, jsObject) => {+ ptr >>>= 0;+ WebGPU.Internals.jsObjects[ptr] = jsObject;+ },+ bufferOnUnmaps: [],+ futures: [],+ futureInsert: (futureId, promise) => {}+ },+ getJsObject: ptr => {+ if (!ptr) return undefined;+ ptr >>>= 0;+ return WebGPU.Internals.jsObjects[ptr];+ },+ importJsAdapter: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateAdapter(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroup: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroup(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroupLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroupLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBuffer: (buffer, parentPtr = 0) => {+ // At the moment, we do not allow importing pending buffers.+ assert(buffer.mapState === "unmapped");+ var bufferPtr = _emwgpuImportBuffer(parentPtr);+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ return bufferPtr;+ },+ importJsCommandBuffer: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandBuffer(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsCommandEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsDevice: (device, parentPtr = 0) => {+ var queuePtr = _emwgpuCreateQueue(parentPtr);+ var devicePtr = _emwgpuCreateDevice(parentPtr, queuePtr);+ WebGPU.Internals.jsObjectInsert(queuePtr, device.queue);+ WebGPU.Internals.jsObjectInsert(devicePtr, device);+ return devicePtr;+ },+ importJsExternalTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateExternalTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsPipelineLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreatePipelineLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQuerySet: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQuerySet(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQueue: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQueue(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundle: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundle(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundleEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundleEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSampler: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSampler(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsShaderModule: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateShaderModule(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSurface: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSurface(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTextureView: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTextureView(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ errorCallback: (callback, type, message, userdata) => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(message);+ getWasmTableEntry(callback)(type, messagePtr, userdata);+ stackRestore(sp);+ },+ iterateExtensions: (root, handlers) => {+ for (var ptr = HEAPU32[((root) >> 2)]; ptr; ptr = HEAPU32[((ptr) >> 2)]) {+ var sType = HEAP32[(((ptr) + (4)) >> 2)];+ // This will crash if there's no handler indicating either a bogus+ // sType, or one we haven't implemented yet.+ var handler = handlers[sType](ptr);+ }+ },+ setStringView: (ptr, data, length) => {+ HEAPU32[((ptr) >> 2)] = data;+ HEAPU32[(((ptr) + (4)) >> 2)] = length;+ },+ makeStringFromStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeStringFromOptionalStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // If we don't have a valid string pointer, just return undefined when+ // optional.+ if (!ptr) {+ if (length === 0) {+ return "";+ }+ return undefined;+ }+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeColor: ptr => ({+ "r": HEAPF64[((ptr) >> 3)],+ "g": HEAPF64[(((ptr) + (8)) >> 3)],+ "b": HEAPF64[(((ptr) + (16)) >> 3)],+ "a": HEAPF64[(((ptr) + (24)) >> 3)]+ }),+ makeExtent3D: ptr => ({+ "width": HEAPU32[((ptr) >> 2)],+ "height": HEAPU32[(((ptr) + (4)) >> 2)],+ "depthOrArrayLayers": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeOrigin3D: ptr => ({+ "x": HEAPU32[((ptr) >> 2)],+ "y": HEAPU32[(((ptr) + (4)) >> 2)],+ "z": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeTexelCopyTextureInfo: ptr => ({+ "texture": WebGPU.getJsObject(HEAPU32[((ptr) >> 2)]),+ "mipLevel": HEAPU32[(((ptr) + (4)) >> 2)],+ "origin": WebGPU.makeOrigin3D(ptr + 8),+ "aspect": WebGPU.TextureAspect[HEAP32[(((ptr) + (20)) >> 2)]]+ }),+ makeTexelCopyBufferLayout: ptr => {+ var bytesPerRow = HEAPU32[(((ptr) + (8)) >> 2)];+ var rowsPerImage = HEAPU32[(((ptr) + (12)) >> 2)];+ return {+ "offset": readI53FromI64(ptr),+ "bytesPerRow": bytesPerRow === 4294967295 ? undefined : bytesPerRow,+ "rowsPerImage": rowsPerImage === 4294967295 ? undefined : rowsPerImage+ };+ },+ makeTexelCopyBufferInfo: ptr => {+ var layoutPtr = ptr + 0;+ var bufferCopyView = WebGPU.makeTexelCopyBufferLayout(layoutPtr);+ bufferCopyView["buffer"] = WebGPU.getJsObject(HEAPU32[(((ptr) + (16)) >> 2)]);+ return bufferCopyView;+ },+ makePassTimestampWrites: ptr => {+ if (ptr === 0) return undefined;+ return {+ "querySet": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "beginningOfPassWriteIndex": HEAPU32[(((ptr) + (8)) >> 2)],+ "endOfPassWriteIndex": HEAPU32[(((ptr) + (12)) >> 2)]+ };+ },+ makePipelineConstants: (constantCount, constantsPtr) => {+ if (!constantCount) return;+ var constants = {};+ for (var i = 0; i < constantCount; ++i) {+ var entryPtr = constantsPtr + 24 * i;+ var key = WebGPU.makeStringFromStringView(entryPtr + 4);+ constants[key] = HEAPF64[(((entryPtr) + (16)) >> 3)];+ }+ return constants;+ },+ makePipelineLayout: layoutPtr => {+ if (!layoutPtr) return "auto";+ return WebGPU.getJsObject(layoutPtr);+ },+ makeComputeState: ptr => {+ if (!ptr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((ptr) + (16)) >> 2)], HEAPU32[(((ptr) + (20)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(ptr + 8)+ };+ return desc;+ },+ makeComputePipelineDesc: descriptor => {+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "compute": WebGPU.makeComputeState(descriptor + 16)+ };+ return desc;+ },+ makeRenderPipelineDesc: descriptor => {+ function makePrimitiveState(psPtr) {+ if (!psPtr) return undefined;+ return {+ "topology": WebGPU.PrimitiveTopology[HEAP32[(((psPtr) + (4)) >> 2)]],+ "stripIndexFormat": WebGPU.IndexFormat[HEAP32[(((psPtr) + (8)) >> 2)]],+ "frontFace": WebGPU.FrontFace[HEAP32[(((psPtr) + (12)) >> 2)]],+ "cullMode": WebGPU.CullMode[HEAP32[(((psPtr) + (16)) >> 2)]],+ "unclippedDepth": !!(HEAPU32[(((psPtr) + (20)) >> 2)])+ };+ }+ function makeBlendComponent(bdPtr) {+ if (!bdPtr) return undefined;+ return {+ "operation": WebGPU.BlendOperation[HEAP32[((bdPtr) >> 2)]],+ "srcFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (4)) >> 2)]],+ "dstFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (8)) >> 2)]]+ };+ }+ function makeBlendState(bsPtr) {+ if (!bsPtr) return undefined;+ return {+ "alpha": makeBlendComponent(bsPtr + 12),+ "color": makeBlendComponent(bsPtr + 0)+ };+ }+ function makeColorState(csPtr) {+ var format = WebGPU.TextureFormat[HEAP32[(((csPtr) + (4)) >> 2)]];+ return format ? {+ "format": format,+ "blend": makeBlendState(HEAPU32[(((csPtr) + (8)) >> 2)]),+ "writeMask": HEAPU32[(((csPtr) + (16)) >> 2)]+ } : undefined;+ }+ function makeColorStates(count, csArrayPtr) {+ var states = [];+ for (var i = 0; i < count; ++i) {+ states.push(makeColorState(csArrayPtr + 24 * i));+ }+ return states;+ }+ function makeStencilStateFace(ssfPtr) {+ return {+ "compare": WebGPU.CompareFunction[HEAP32[((ssfPtr) >> 2)]],+ "failOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (4)) >> 2)]],+ "depthFailOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (8)) >> 2)]],+ "passOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (12)) >> 2)]]+ };+ }+ function makeDepthStencilState(dssPtr) {+ if (!dssPtr) return undefined;+ return {+ "format": WebGPU.TextureFormat[HEAP32[(((dssPtr) + (4)) >> 2)]],+ "depthWriteEnabled": !!(HEAPU32[(((dssPtr) + (8)) >> 2)]),+ "depthCompare": WebGPU.CompareFunction[HEAP32[(((dssPtr) + (12)) >> 2)]],+ "stencilFront": makeStencilStateFace(dssPtr + 16),+ "stencilBack": makeStencilStateFace(dssPtr + 32),+ "stencilReadMask": HEAPU32[(((dssPtr) + (48)) >> 2)],+ "stencilWriteMask": HEAPU32[(((dssPtr) + (52)) >> 2)],+ "depthBias": HEAP32[(((dssPtr) + (56)) >> 2)],+ "depthBiasSlopeScale": HEAPF32[(((dssPtr) + (60)) >> 2)],+ "depthBiasClamp": HEAPF32[(((dssPtr) + (64)) >> 2)]+ };+ }+ function makeVertexAttribute(vaPtr) {+ return {+ "format": WebGPU.VertexFormat[HEAP32[(((vaPtr) + (4)) >> 2)]],+ "offset": readI53FromI64((vaPtr) + (8)),+ "shaderLocation": HEAPU32[(((vaPtr) + (16)) >> 2)]+ };+ }+ function makeVertexAttributes(count, vaArrayPtr) {+ var vas = [];+ for (var i = 0; i < count; ++i) {+ vas.push(makeVertexAttribute(vaArrayPtr + i * 24));+ }+ return vas;+ }+ function makeVertexBuffer(vbPtr) {+ if (!vbPtr) return undefined;+ var stepMode = WebGPU.VertexStepMode[HEAP32[(((vbPtr) + (4)) >> 2)]];+ var attributeCount = HEAPU32[(((vbPtr) + (16)) >> 2)];+ if (!stepMode && !attributeCount) {+ return null;+ }+ return {+ "arrayStride": readI53FromI64((vbPtr) + (8)),+ "stepMode": stepMode,+ "attributes": makeVertexAttributes(attributeCount, HEAPU32[(((vbPtr) + (20)) >> 2)])+ };+ }+ function makeVertexBuffers(count, vbArrayPtr) {+ if (!count) return undefined;+ var vbs = [];+ for (var i = 0; i < count; ++i) {+ vbs.push(makeVertexBuffer(vbArrayPtr + i * 24));+ }+ return vbs;+ }+ function makeVertexState(viPtr) {+ if (!viPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((viPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((viPtr) + (16)) >> 2)], HEAPU32[(((viPtr) + (20)) >> 2)]),+ "buffers": makeVertexBuffers(HEAPU32[(((viPtr) + (24)) >> 2)], HEAPU32[(((viPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(viPtr + 8)+ };+ return desc;+ }+ function makeMultisampleState(msPtr) {+ if (!msPtr) return undefined;+ return {+ "count": HEAPU32[(((msPtr) + (4)) >> 2)],+ "mask": HEAPU32[(((msPtr) + (8)) >> 2)],+ "alphaToCoverageEnabled": !!(HEAPU32[(((msPtr) + (12)) >> 2)])+ };+ }+ function makeFragmentState(fsPtr) {+ if (!fsPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((fsPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((fsPtr) + (16)) >> 2)], HEAPU32[(((fsPtr) + (20)) >> 2)]),+ "targets": makeColorStates(HEAPU32[(((fsPtr) + (24)) >> 2)], HEAPU32[(((fsPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(fsPtr + 8)+ };+ return desc;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "vertex": makeVertexState(descriptor + 16),+ "primitive": makePrimitiveState(descriptor + 48),+ "depthStencil": makeDepthStencilState(HEAPU32[(((descriptor) + (72)) >> 2)]),+ "multisample": makeMultisampleState(descriptor + 76),+ "fragment": makeFragmentState(HEAPU32[(((descriptor) + (92)) >> 2)])+ };+ return desc;+ },+ fillLimitStruct: (limits, limitsOutPtr) => {+ var nextInChainPtr = HEAPU32[((limitsOutPtr) >> 2)];+ function setLimitValueU32(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ HEAPU32[(((basePtr) + (limitOffset)) >> 2)] = limitValue;+ }+ function setLimitValueU64(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ // Limits are integer-valued JS `Number`s, so they fit in 'i53'.+ writeI53ToI64((basePtr) + (limitOffset), limitValue);+ }+ setLimitValueU32("maxTextureDimension1D", limitsOutPtr, 4);+ setLimitValueU32("maxTextureDimension2D", limitsOutPtr, 8);+ setLimitValueU32("maxTextureDimension3D", limitsOutPtr, 12);+ setLimitValueU32("maxTextureArrayLayers", limitsOutPtr, 16);+ setLimitValueU32("maxBindGroups", limitsOutPtr, 20);+ setLimitValueU32("maxBindGroupsPlusVertexBuffers", limitsOutPtr, 24);+ setLimitValueU32("maxBindingsPerBindGroup", limitsOutPtr, 28);+ setLimitValueU32("maxDynamicUniformBuffersPerPipelineLayout", limitsOutPtr, 32);+ setLimitValueU32("maxDynamicStorageBuffersPerPipelineLayout", limitsOutPtr, 36);+ setLimitValueU32("maxSampledTexturesPerShaderStage", limitsOutPtr, 40);+ setLimitValueU32("maxSamplersPerShaderStage", limitsOutPtr, 44);+ setLimitValueU32("maxStorageBuffersPerShaderStage", limitsOutPtr, 48);+ setLimitValueU32("maxStorageTexturesPerShaderStage", limitsOutPtr, 52);+ setLimitValueU32("maxUniformBuffersPerShaderStage", limitsOutPtr, 56);+ setLimitValueU32("minUniformBufferOffsetAlignment", limitsOutPtr, 80);+ setLimitValueU32("minStorageBufferOffsetAlignment", limitsOutPtr, 84);+ setLimitValueU64("maxUniformBufferBindingSize", limitsOutPtr, 64);+ setLimitValueU64("maxStorageBufferBindingSize", limitsOutPtr, 72);+ setLimitValueU32("maxVertexBuffers", limitsOutPtr, 88);+ setLimitValueU64("maxBufferSize", limitsOutPtr, 96);+ setLimitValueU32("maxVertexAttributes", limitsOutPtr, 104);+ setLimitValueU32("maxVertexBufferArrayStride", limitsOutPtr, 108);+ setLimitValueU32("maxInterStageShaderVariables", limitsOutPtr, 112);+ setLimitValueU32("maxColorAttachments", limitsOutPtr, 116);+ setLimitValueU32("maxColorAttachmentBytesPerSample", limitsOutPtr, 120);+ setLimitValueU32("maxComputeWorkgroupStorageSize", limitsOutPtr, 124);+ setLimitValueU32("maxComputeInvocationsPerWorkgroup", limitsOutPtr, 128);+ setLimitValueU32("maxComputeWorkgroupSizeX", limitsOutPtr, 132);+ setLimitValueU32("maxComputeWorkgroupSizeY", limitsOutPtr, 136);+ setLimitValueU32("maxComputeWorkgroupSizeZ", limitsOutPtr, 140);+ setLimitValueU32("maxComputeWorkgroupsPerDimension", limitsOutPtr, 144);+ // Note this limit is new and won't be present in all browsers for a while. Fall back to 0.+ setLimitValueU32("maxImmediateSize", limitsOutPtr, 148);+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var compatibilityModeLimitsPtr = nextInChainPtr;+ // Note these limits are new and won't be present in all browsers for a while. Fall back to exposing the PerShaderStage limit.+ setLimitValueU32("maxStorageBuffersInVertexStage", compatibilityModeLimitsPtr, 8, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageBuffersInFragmentStage", compatibilityModeLimitsPtr, 16, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageTexturesInVertexStage", compatibilityModeLimitsPtr, 12, limits.maxStorageTexturesPerShaderStage);+ setLimitValueU32("maxStorageTexturesInFragmentStage", compatibilityModeLimitsPtr, 20, limits.maxStorageTexturesPerShaderStage);+ }+ },+ fillAdapterInfoStruct: (info, infoStruct) => {+ // Populate subgroup limits.+ HEAPU32[(((infoStruct) + (52)) >> 2)] = info.subgroupMinSize;+ HEAPU32[(((infoStruct) + (56)) >> 2)] = info.subgroupMaxSize;+ // Append all the strings together to condense into a single malloc.+ var strs = info.vendor + info.architecture + info.device + info.description;+ var strPtr = stringToNewUTF8(strs);+ var vendorLen = lengthBytesUTF8(info.vendor);+ WebGPU.setStringView(infoStruct + 4, strPtr, vendorLen);+ strPtr += vendorLen;+ var architectureLen = lengthBytesUTF8(info.architecture);+ WebGPU.setStringView(infoStruct + 12, strPtr, architectureLen);+ strPtr += architectureLen;+ var deviceLen = lengthBytesUTF8(info.device);+ WebGPU.setStringView(infoStruct + 20, strPtr, deviceLen);+ strPtr += deviceLen;+ var descriptionLen = lengthBytesUTF8(info.description);+ WebGPU.setStringView(infoStruct + 28, strPtr, descriptionLen);+ strPtr += descriptionLen;+ HEAP32[(((infoStruct) + (36)) >> 2)] = 2;+ var adapterType = info.isFallbackAdapter ? 3 : 4;+ HEAP32[(((infoStruct) + (40)) >> 2)] = adapterType;+ HEAPU32[(((infoStruct) + (44)) >> 2)] = 0;+ HEAPU32[(((infoStruct) + (48)) >> 2)] = 0;+ WebGPU.iterateExtensions(infoStruct, {+ 327739: ext => {+ let configCount = 0;+ let configsPtr = 0;+ if (info.subgroupMatrixConfigs) {+ configCount = info.subgroupMatrixConfigs.length;+ configsPtr = _malloc(configCount * 28);+ for (const [i, cfg] of info.subgroupMatrixConfigs.entries()) {+ const ptr = configsPtr + i * 28;+ const componentType = WebGPU.SubgroupMatrixComponentType.indexOf(cfg.componentType);+ const resultComponentType = WebGPU.SubgroupMatrixComponentType.indexOf(cfg.resultComponentType);+ HEAP32[((ptr) >> 2)] = componentType;+ HEAP32[(((ptr) + (4)) >> 2)] = resultComponentType;+ HEAPU32[(((ptr) + (8)) >> 2)] = cfg.M;+ HEAPU32[(((ptr) + (12)) >> 2)] = cfg.N;+ HEAPU32[(((ptr) + (16)) >> 2)] = cfg.K;+ }+ }+ HEAPU32[(((ext) + (12)) >> 2)] = configsPtr;+ HEAPU32[(((ext) + (8)) >> 2)] = configCount;+ }+ });+ },+ AddressMode: [ , "clamp-to-edge", "repeat", "mirror-repeat" ],+ BlendFactor: [ , "zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst", "one-minus-dst", "dst-alpha", "one-minus-dst-alpha", "src-alpha-saturated", "constant", "one-minus-constant", "src1", "one-minus-src1", "src1-alpha", "one-minus-src1-alpha" ],+ BlendOperation: [ , "add", "subtract", "reverse-subtract", "min", "max" ],+ BufferBindingType: [ , , "uniform", "storage", "read-only-storage" ],+ BufferMapState: [ , "unmapped", "pending", "mapped" ],+ CompareFunction: [ , "never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always" ],+ CompilationInfoRequestStatus: [ , "success", "callback-cancelled" ],+ ComponentSwizzle: [ , "0", "1", "r", "g", "b", "a" ],+ CompositeAlphaMode: [ , "opaque", "premultiplied", "unpremultiplied", "inherit" ],+ CullMode: [ , "none", "front", "back" ],+ ErrorFilter: [ , "validation", "out-of-memory", "internal" ],+ FeatureLevel: [ , "compatibility", "core" ],+ FeatureName: {+ 1: "core-features-and-limits",+ 2: "depth-clip-control",+ 3: "depth32float-stencil8",+ 4: "texture-compression-bc",+ 5: "texture-compression-bc-sliced-3d",+ 6: "texture-compression-etc2",+ 7: "texture-compression-astc",+ 8: "texture-compression-astc-sliced-3d",+ 9: "timestamp-query",+ 10: "indirect-first-instance",+ 11: "shader-f16",+ 12: "rg11b10ufloat-renderable",+ 13: "bgra8unorm-storage",+ 14: "float32-filterable",+ 15: "float32-blendable",+ 16: "clip-distances",+ 17: "dual-source-blending",+ 18: "subgroups",+ 19: "texture-formats-tier1",+ 20: "texture-formats-tier2",+ 21: "primitive-index",+ 22: "texture-component-swizzle",+ 23: "subgroup-size-control",+ 24: "texture-compression-unaligned",+ 25: "atomic-vec2u-min-max",+ 327692: "chromium-experimental-unorm16-texture-formats",+ 327729: "chromium-experimental-multi-draw-indirect",+ 327732: "chromium-experimental-subgroup-matrix"+ },+ FilterMode: [ , "nearest", "linear" ],+ FrontFace: [ , "ccw", "cw" ],+ IndexFormat: [ , "uint16", "uint32" ],+ InstanceFeatureName: [ , "timed-wait-any", "shader-source-spirv", "multiple-devices-per-adapter" ],+ LoadOp: [ , "load", "clear" ],+ MipmapFilterMode: [ , "nearest", "linear" ],+ OptionalBool: [ "false", "true" ],+ PowerPreference: [ , "low-power", "high-performance" ],+ PredefinedColorSpace: [ , "srgb", "display-p3" ],+ PrimitiveTopology: [ , "point-list", "line-list", "line-strip", "triangle-list", "triangle-strip" ],+ QueryType: [ , "occlusion", "timestamp" ],+ SamplerBindingType: [ , , "filtering", "non-filtering", "comparison" ],+ Status: [ , "success", "error" ],+ StencilOperation: [ , "keep", "zero", "replace", "invert", "increment-clamp", "decrement-clamp", "increment-wrap", "decrement-wrap" ],+ StorageTextureAccess: [ , , "write-only", "read-only", "read-write" ],+ StoreOp: [ , "store", "discard" ],+ SubgroupMatrixComponentType: [ , "f32", "f16", "u32", "i32", "u8", "i8" ],+ SurfaceGetCurrentTextureStatus: [ , "success-optimal", "success-suboptimal", "timeout", "outdated", "lost", "error" ],+ TextureAspect: [ , "all", "stencil-only", "depth-only" ],+ TextureDimension: [ , "1d", "2d", "3d" ],+ TextureFormat: [ , "r8unorm", "r8snorm", "r8uint", "r8sint", "r16unorm", "r16snorm", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32float", "r32uint", "r32sint", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rgb9e5ufloat", "rg32float", "rg32uint", "rg32sint", "rgba16unorm", "rgba16snorm", "rgba16uint", "rgba16sint", "rgba16float", "rgba32float", "rgba32uint", "rgba32sint", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb" ],+ TextureSampleType: [ , , "float", "unfilterable-float", "depth", "sint", "uint" ],+ TextureViewDimension: [ , "1d", "2d", "2d-array", "cube", "cube-array", "3d" ],+ ToneMappingMode: [ , "standard", "extended" ],+ VertexFormat: [ , "uint8", "uint8x2", "uint8x4", "sint8", "sint8x2", "sint8x4", "unorm8", "unorm8x2", "unorm8x4", "snorm8", "snorm8x2", "snorm8x4", "uint16", "uint16x2", "uint16x4", "sint16", "sint16x2", "sint16x4", "unorm16", "unorm16x2", "unorm16x4", "snorm16", "snorm16x2", "snorm16x4", "float16", "float16x2", "float16x4", "float32", "float32x2", "float32x3", "float32x4", "uint32", "uint32x2", "uint32x3", "uint32x4", "sint32", "sint32x2", "sint32x3", "sint32x4", "unorm10-10-10-2", "unorm8x4-bgra", "snorm10-10-10-2" ],+ VertexStepMode: [ , "vertex", "instance" ],+ WGSLLanguageFeatureName: [ , "readonly_and_readwrite_storage_textures", "packed_4x8_integer_dot_product", "unrestricted_pointer_parameters", "pointer_composite_access", "uniform_buffer_standard_layout", "subgroup_id", "texture_and_sampler_let", "subgroup_uniformity", "texture_formats_tier1", "linear_indexing", "immediate_address_space", "buffer_view", "swizzle_assignment", "fragment_depth" ]+};++var _emscripten_webgpu_get_device = () => {+ if (WebGPU.preinitializedDeviceId === undefined) {+ WebGPU.preinitializedDeviceId = WebGPU.importJsDevice(Module["preinitializedWebGPUDevice"]);+ // Some users depend on this keeping the device alive, so we add an+ // additional reference when we first initialize it.+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ }+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ return WebGPU.preinitializedDeviceId;+};++var _emwgpuBufferDestroy = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (onUnmap) {+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ }+ buffer.destroy();+};++var _emwgpuBufferGetMappedRange = (bufferPtr, offset, size) => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ if (size == -1) size = undefined;+ var mapped;+ try {+ mapped = buffer.getMappedRange(offset, size);+ } catch (ex) {+ return 0;+ }+ var data = _memalign(16, mapped.byteLength);+ HEAPU8.fill(0, data, mapped.byteLength);+ WebGPU.Internals.bufferOnUnmaps[bufferPtr].push(() => {+ new Uint8Array(mapped).set(HEAPU8.subarray(data, data + mapped.byteLength));+ _free(data);+ });+ return data;+};++var _emwgpuBufferUnmap = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (!onUnmap) {+ // Already unmapped+ return;+ }+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ buffer.unmap();+};++var _emwgpuDelete = ptr => {+ delete WebGPU.Internals.jsObjects[ptr];+};++var _emwgpuDeviceCreateBuffer = (devicePtr, descriptor, bufferPtr) => {+ var mappedAtCreation = !!(HEAPU32[(((descriptor) + (32)) >> 2)]);+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "size": readI53FromI64((descriptor) + (24)),+ "mappedAtCreation": mappedAtCreation+ };+ var device = WebGPU.getJsObject(devicePtr);+ var buffer;+ try {+ buffer = device.createBuffer(desc);+ } catch (ex) {+ // The only exception should be RangeError if mapping at creation ran out of memory.+ return false;+ }+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ if (mappedAtCreation) {+ WebGPU.Internals.bufferOnUnmaps[bufferPtr] = [];+ }+ return true;+};++var _emwgpuDeviceCreateComputePipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createComputePipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createComputePipelineAsync(desc).then(pipeline => {+ // createComputePipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateComputePipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createComputePipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateComputePipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateRenderPipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createRenderPipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createRenderPipelineAsync(desc).then(pipeline => {+ // createRenderPipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateRenderPipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createRenderPipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateRenderPipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateShaderModule = (devicePtr, descriptor, shaderModulePtr) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "code": ""+ };+ switch (sType) {+ case 2:+ {+ desc["code"] = WebGPU.makeStringFromStringView(nextInChainPtr + 8);+ break;+ }+ }+ var device = WebGPU.getJsObject(devicePtr);+ WebGPU.Internals.jsObjectInsert(shaderModulePtr, device.createShaderModule(desc));+};++var _emwgpuDeviceDestroy = devicePtr => {+ const device = WebGPU.getJsObject(devicePtr);+ // Remove the onuncapturederror handler which holds a pointer to the WGPUDevice.+ device.onuncapturederror = null;+ device.destroy();+};++var _emwgpuWaitAny = (futurePtr, futureCount, timeoutMSPtr) => {+ abort("TODO: Implement asyncify-free WaitAny for timeout=0");+};++var ENV = {};++var getExecutableName = () => thisProgram;++var getEnvStrings = () => {+ if (!getEnvStrings.strings) {+ // Default values.+ var lang = (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8";+ var env = {+ "USER": "web_user",+ "LOGNAME": "web_user",+ "PATH": "/",+ "PWD": "/",+ "HOME": "/home/web_user",+ "LANG": lang,+ "_": getExecutableName()+ };+ // Apply the user-provided values, if any.+ for (var x in ENV) {+ // x is a key in ENV; if ENV[x] is undefined, that means it was+ // explicitly set to be so. We allow user code to do that to+ // force variables with default values to remain unset.+ if (ENV[x] === undefined) delete env[x]; else env[x] = ENV[x];+ }+ var strings = [];+ for (var x in env) {+ strings.push(`${x}=${env[x]}`);+ }+ getEnvStrings.strings = strings;+ }+ return getEnvStrings.strings;+};++var _environ_get = (__environ, environ_buf) => {+ var bufSize = 0;+ var envp = 0;+ for (var string of getEnvStrings()) {+ var ptr = environ_buf + bufSize;+ HEAPU32[(((__environ) + (envp)) >> 2)] = ptr;+ bufSize += stringToUTF8(string, ptr, Infinity) + 1;+ envp += 4;+ }+ return 0;+};++var _environ_sizes_get = (penviron_count, penviron_buf_size) => {+ var strings = getEnvStrings();+ HEAPU32[((penviron_count) >> 2)] = strings.length;+ var bufSize = 0;+ for (var string of strings) {+ bufSize += lengthBytesUTF8(string) + 1;+ }+ HEAPU32[((penviron_buf_size) >> 2)] = bufSize;+ return 0;+};++function _fd_close(fd) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.close(stream);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doReadv = (stream, iov, iovcnt, offset) => {+ var ret = 0;+ for (var i = 0; i < iovcnt; i++) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ iov += 8;+ try {+ var curr = FS.read(stream, HEAP8, ptr, len, offset);+ } catch (e) {+ // On a non-blocking stream a subsequent read may would-block after we+ // already gathered data. POSIX readv is a single gather-read: return+ // what we have rather than failing the whole call.+ if (ret > 0 && e instanceof FS.ErrnoError && (e.errno == 6 || e.errno == 6)) {+ break;+ }+ throw e;+ }+ if (curr < 0) return -1;+ ret += curr;+ if (curr < len) break;+ // nothing more to read+ if (typeof offset != "undefined") {+ offset += curr;+ }+ }+ return ret;+};++function _fd_pread(fd, iov, iovcnt, offset_low, offset_high, pnum) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ if (isNaN(offset)) return 22;+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doReadv(stream, iov, iovcnt, offset);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++function _fd_read(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doReadv(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ if (isNaN(offset)) return 22;+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.llseek(stream, offset, whence);+ (tempI64 = [ stream.position >>> 0, (tempDouble = stream.position, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((newOffset) >> 2)] = tempI64[0], HEAP32[(((newOffset) + (4)) >> 2)] = tempI64[1]);+ if (stream.getdents && !offset && whence === 0) stream.getdents = null;+ // reset readdir state+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doWritev = (stream, iov, iovcnt, offset) => {+ // Gather all iovecs into one contiguous buffer and issue a single+ // FS.write, matching POSIX writev's single gather-write semantics (as+ // __syscall_sendmsg already does). Per-iovec writes fragment a stream+ // socket send into multiple segments, breaking stream byte semantics.+ if (iovcnt == 1) {+ // Single iovec: write directly from HEAP8, no gather buffer needed.+ return FS.write(stream, HEAP8, HEAPU32[((iov) >> 2)], HEAPU32[(((iov) + (4)) >> 2)], offset);+ }+ var total = 0;+ for (var i = 0, p = iov; i < iovcnt; i++, p += 8) {+ total += HEAPU32[(((p) + (4)) >> 2)];+ }+ var view = new Uint8Array(total);+ var voff = 0;+ for (var i = 0; i < iovcnt; i++, iov += 8) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ view.set(HEAPU8.subarray(ptr, ptr + len), voff);+ voff += len;+ }+ return FS.write(stream, view, 0, total, offset);+};++function _fd_write(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doWritev(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++var _emscripten_glActiveTexture = x0 => GLctx.activeTexture(x0);++var _glActiveTexture = _emscripten_glActiveTexture;++var _emscripten_glAttachShader = (program, shader) => {+ GLctx.attachShader(GL.programs[program], GL.shaders[shader]);+};++var _glAttachShader = _emscripten_glAttachShader;++var _emscripten_glBindAttribLocation = (program, index, name) => {+ GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name));+};++var _glBindAttribLocation = _emscripten_glBindAttribLocation;++var _emscripten_glBindBuffer = (target, buffer) => {+ // Calling glBindBuffer with an unknown buffer will implicitly create a+ // new one. Here we bypass `GL.counter` and directly using the ID passed+ // in.+ if (buffer && !GL.buffers[buffer]) {+ var b = GLctx.createBuffer();+ b.name = buffer;+ GL.buffers[buffer] = b;+ }+ if (target == 34962) {+ GLctx.currentArrayBufferBinding = buffer;+ } else if (target == 34963) {+ GLctx.currentElementArrayBufferBinding = buffer;+ }+ if (target == 35051) {+ // In WebGL 2 glReadPixels entry point, we need to use a different WebGL 2+ // API function call when a buffer is bound to+ // GL_PIXEL_PACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelPackBufferBinding = buffer;+ } else if (target == 35052) {+ // In WebGL 2 gl(Compressed)Tex(Sub)Image[23]D entry points, we need to+ // use a different WebGL 2 API function call when a buffer is bound to+ // GL_PIXEL_UNPACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelUnpackBufferBinding = buffer;+ }+ GLctx.bindBuffer(target, GL.buffers[buffer]);+};++var _glBindBuffer = _emscripten_glBindBuffer;++var _emscripten_glBindBufferBase = (target, index, buffer) => {+ GLctx.bindBufferBase(target, index, GL.buffers[buffer]);+};++var _glBindBufferBase = _emscripten_glBindBufferBase;++var _emscripten_glBindFramebuffer = (target, framebuffer) => {+ GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]);+};++var _glBindFramebuffer = _emscripten_glBindFramebuffer;++var _emscripten_glBindTexture = (target, texture) => {+ GLctx.bindTexture(target, GL.textures[texture]);+};++var _glBindTexture = _emscripten_glBindTexture;++var _emscripten_glBindVertexArray = vao => {+ GLctx.bindVertexArray(GL.vaos[vao]);+ var ibo = GLctx.getParameter(34965);+ GLctx.currentElementArrayBufferBinding = ibo ? (ibo.name | 0) : 0;+};++var _glBindVertexArray = _emscripten_glBindVertexArray;++var _emscripten_glBlendEquation = x0 => GLctx.blendEquation(x0);++var _glBlendEquation = _emscripten_glBlendEquation;++var _emscripten_glBlendFunc = (x0, x1) => GLctx.blendFunc(x0, x1);++var _glBlendFunc = _emscripten_glBlendFunc;++var _emscripten_glBufferData = (target, size, data, usage) => {+ if (GL.currentContext.version >= 2) {+ // If size is zero, WebGL would interpret uploading the whole input+ // arraybuffer (starting from given offset), which would not make sense in+ // WebAssembly, so avoid uploading if size is zero. However we must still+ // call bufferData to establish a backing storage of zero bytes.+ if (data && size) {+ GLctx.bufferData(target, HEAPU8, usage, data, size);+ } else {+ GLctx.bufferData(target, size, usage);+ }+ return;+ }+ // N.b. here first form specifies a heap subarray, second form an integer+ // size, so the ?: code here is polymorphic. It is advised to avoid+ // randomly mixing both uses in calling code, to avoid any potential JS+ // engine JIT issues.+ GLctx.bufferData(target, data ? HEAPU8.subarray(data, data + size) : size, usage);+};++var _glBufferData = _emscripten_glBufferData;++var _emscripten_glClear = x0 => GLctx.clear(x0);++var _glClear = _emscripten_glClear;++var _emscripten_glClearColor = (x0, x1, x2, x3) => GLctx.clearColor(x0, x1, x2, x3);++var _glClearColor = _emscripten_glClearColor;++var convertI32PairToI53 = (lo, hi) => (lo >>> 0) + hi * 4294967296;++var _emscripten_glClientWaitSync = (sync, flags, timeout_low, timeout_high) => {+ // WebGL2 vs GLES3 differences: in GLES3, the timeout parameter is a uint64, where 0xFFFFFFFFFFFFFFFFULL means GL_TIMEOUT_IGNORED.+ // In JS, there's no 64-bit value types, so instead timeout is taken to be signed, and GL_TIMEOUT_IGNORED is given value -1.+ // Inherently the value accepted in the timeout is lossy, and can't take in arbitrary u64 bit pattern (but most likely doesn't matter)+ // See https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.15+ var timeout = convertI32PairToI53(timeout_low, timeout_high);+ return GLctx.clientWaitSync(GL.syncs[sync], flags, timeout);+};++var _glClientWaitSync = _emscripten_glClientWaitSync;++var _emscripten_glColorMask = (red, green, blue, alpha) => {+ GLctx.colorMask(!!red, !!green, !!blue, !!alpha);+};++var _glColorMask = _emscripten_glColorMask;++var _emscripten_glCompileShader = shader => {+ GLctx.compileShader(GL.shaders[shader]);+};++var _glCompileShader = _emscripten_glCompileShader;++var _emscripten_glCreateProgram = () => {+ var id = GL.getNewId(GL.programs);+ var program = GLctx.createProgram();+ // Store additional information needed for each shader program:+ program.name = id;+ // Lazy cache results of+ // glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH)+ program.maxUniformLength = program.maxAttributeLength = program.maxUniformBlockNameLength = 0;+ program.uniformIdCounter = 1;+ GL.programs[id] = program;+ return id;+};++var _glCreateProgram = _emscripten_glCreateProgram;++var _emscripten_glCreateShader = shaderType => {+ var id = GL.getNewId(GL.shaders);+ GL.shaders[id] = GLctx.createShader(shaderType);+ return id;+};++var _glCreateShader = _emscripten_glCreateShader;++var _emscripten_glDeleteBuffers = (n, buffers) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((buffers) + (i * 4)) >> 2)];+ var buffer = GL.buffers[id];+ // From spec: "glDeleteBuffers silently ignores 0's and names that do not+ // correspond to existing buffer objects."+ if (!buffer) continue;+ GLctx.deleteBuffer(buffer);+ buffer.name = 0;+ GL.buffers[id] = null;+ if (id == GLctx.currentArrayBufferBinding) GLctx.currentArrayBufferBinding = 0;+ if (id == GLctx.currentElementArrayBufferBinding) GLctx.currentElementArrayBufferBinding = 0;+ if (id == GLctx.currentPixelPackBufferBinding) GLctx.currentPixelPackBufferBinding = 0;+ if (id == GLctx.currentPixelUnpackBufferBinding) GLctx.currentPixelUnpackBufferBinding = 0;+ }+};++var _glDeleteBuffers = _emscripten_glDeleteBuffers;++var _emscripten_glDeleteFramebuffers = (n, framebuffers) => {+ for (var i = 0; i < n; ++i) {+ var id = HEAP32[(((framebuffers) + (i * 4)) >> 2)];+ var framebuffer = GL.framebuffers[id];+ if (!framebuffer) continue;+ // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects".+ GLctx.deleteFramebuffer(framebuffer);+ framebuffer.name = 0;+ GL.framebuffers[id] = null;+ }+};++var _glDeleteFramebuffers = _emscripten_glDeleteFramebuffers;++var _emscripten_glDeleteProgram = id => {+ if (!id) return;+ var program = GL.programs[id];+ if (!program) {+ // glDeleteProgram actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteProgram(program);+ program.name = 0;+ GL.programs[id] = null;+};++var _glDeleteProgram = _emscripten_glDeleteProgram;++var _emscripten_glDeleteShader = id => {+ if (!id) return;+ var shader = GL.shaders[id];+ if (!shader) {+ // glDeleteShader actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteShader(shader);+ GL.shaders[id] = null;+};++var _glDeleteShader = _emscripten_glDeleteShader;++var _emscripten_glDeleteSync = id => {+ if (!id) return;+ var sync = GL.syncs[id];+ if (!sync) {+ // glDeleteSync signals an error when deleting a nonexisting object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteSync(sync);+ sync.name = 0;+ GL.syncs[id] = null;+};++var _glDeleteSync = _emscripten_glDeleteSync;++var _emscripten_glDeleteTextures = (n, textures) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((textures) + (i * 4)) >> 2)];+ var texture = GL.textures[id];+ // GL spec: "glDeleteTextures silently ignores 0s and names that do not+ // correspond to existing textures".+ if (!texture) continue;+ GLctx.deleteTexture(texture);+ texture.name = 0;+ GL.textures[id] = null;+ }+};++var _glDeleteTextures = _emscripten_glDeleteTextures;++var _emscripten_glDeleteVertexArrays = (n, vaos) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((vaos) + (i * 4)) >> 2)];+ GLctx.deleteVertexArray(GL.vaos[id]);+ GL.vaos[id] = null;+ }+};++var _glDeleteVertexArrays = _emscripten_glDeleteVertexArrays;++var _emscripten_glDetachShader = (program, shader) => {+ GLctx.detachShader(GL.programs[program], GL.shaders[shader]);+};++var _glDetachShader = _emscripten_glDetachShader;++var _emscripten_glDisable = x0 => GLctx.disable(x0);++var _glDisable = _emscripten_glDisable;++var _emscripten_glDisableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = false;+ GLctx.disableVertexAttribArray(index);+};++var _glDisableVertexAttribArray = _emscripten_glDisableVertexAttribArray;++var _emscripten_glDrawArrays = (mode, first, count) => {+ // bind any client-side buffers+ GL.preDrawHandleClientVertexAttribBindings(first + count);+ GLctx.drawArrays(mode, first, count);+ GL.postDrawHandleClientVertexAttribBindings();+};++var _glDrawArrays = _emscripten_glDrawArrays;++var tempFixedLengthArray = [];++var _emscripten_glDrawBuffers = (n, bufs) => {+ var bufArray = tempFixedLengthArray[n];+ for (var i = 0; i < n; i++) {+ bufArray[i] = HEAP32[(((bufs) + (i * 4)) >> 2)];+ }+ GLctx.drawBuffers(bufArray);+};++var _glDrawBuffers = _emscripten_glDrawBuffers;++var _emscripten_glEnable = x0 => GLctx.enable(x0);++var _glEnable = _emscripten_glEnable;++var _emscripten_glEnableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = true;+ GLctx.enableVertexAttribArray(index);+};++var _glEnableVertexAttribArray = _emscripten_glEnableVertexAttribArray;++var _emscripten_glFenceSync = (condition, flags) => {+ var sync = GLctx.fenceSync(condition, flags);+ if (sync) {+ var id = GL.getNewId(GL.syncs);+ sync.name = id;+ GL.syncs[id] = sync;+ return id;+ }+ return 0;+};++var _glFenceSync = _emscripten_glFenceSync;++var _emscripten_glFinish = () => GLctx.finish();++var _glFinish = _emscripten_glFinish;++var _emscripten_glFlush = () => GLctx.flush();++var _glFlush = _emscripten_glFlush;++var _emscripten_glFramebufferTexture2D = (target, attachment, textarget, texture, level) => {+ GLctx.framebufferTexture2D(target, attachment, textarget, GL.textures[texture], level);+};++var _glFramebufferTexture2D = _emscripten_glFramebufferTexture2D;++var _emscripten_glFramebufferTextureLayer = (target, attachment, texture, level, layer) => {+ GLctx.framebufferTextureLayer(target, attachment, GL.textures[texture], level, layer);+};++var _glFramebufferTextureLayer = _emscripten_glFramebufferTextureLayer;++var _emscripten_glGenBuffers = (n, buffers) => {+ GL.genObject(n, buffers, "createBuffer", GL.buffers);+};++var _glGenBuffers = _emscripten_glGenBuffers;++var _emscripten_glGenFramebuffers = (n, ids) => {+ GL.genObject(n, ids, "createFramebuffer", GL.framebuffers);+};++var _glGenFramebuffers = _emscripten_glGenFramebuffers;++var _emscripten_glGenTextures = (n, textures) => {+ GL.genObject(n, textures, "createTexture", GL.textures);+};++var _glGenTextures = _emscripten_glGenTextures;++var _emscripten_glGenVertexArrays = (n, arrays) => {+ GL.genObject(n, arrays, "createVertexArray", GL.vaos);+};++var _glGenVertexArrays = _emscripten_glGenVertexArrays;++var _emscripten_glGetAttribLocation = (program, name) => GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));++var _glGetAttribLocation = _emscripten_glGetAttribLocation;++var _emscripten_glGetError = () => {+ var error = GLctx.getError() || GL.lastError;+ GL.lastError = 0;+ return error;+};++var _glGetError = _emscripten_glGetError;++var webglGetExtensions = () => {+ var exts = getEmscriptenSupportedExtensions(GLctx);+ exts = exts.concat(exts.map(e => "GL_" + e));+ return exts;+};++var emscriptenWebGLGet = (name_, p, type) => {+ // Guard against user passing a null pointer.+ // Note that GLES2 spec does not say anything about how passing a null+ // pointer should be treated. Testing on desktop core GL 3, the application+ // crashes on glGetIntegerv to a null pointer, but better to report an error+ // instead of doing anything random.+ if (!p) {+ GL.recordError(1281);+ return;+ }+ var ret = undefined;+ switch (name_) {+ // Handle a few trivial GLES values+ case 36346:+ // GL_SHADER_COMPILER+ ret = 1;+ break;++ case 36344:+ // GL_SHADER_BINARY_FORMATS+ if (type != 0 && type != 1) {+ GL.recordError(1280);+ }+ // Do not write anything to the out pointer, since no binary formats are+ // supported.+ return;++ case 34814:+ // GL_NUM_PROGRAM_BINARY_FORMATS+ case 36345:+ // GL_NUM_SHADER_BINARY_FORMATS+ ret = 0;+ break;++ case 34466:+ // GL_NUM_COMPRESSED_TEXTURE_FORMATS+ // WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete+ // since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be+ // queried for length), so implement it ourselves to allow C++ GLES2+ // code to get the length.+ var formats = GLctx.getParameter(34467);+ ret = formats ? formats.length : 0;+ break;++ case 33309:+ // GL_NUM_EXTENSIONS+ if (GL.currentContext.version < 2) {+ // Calling GLES3/WebGL2 function with a GLES2/WebGL1 context+ GL.recordError(1282);+ return;+ }+ ret = webglGetExtensions().length;+ break;++ case 33307:+ // GL_MAJOR_VERSION+ case 33308:+ // GL_MINOR_VERSION+ if (GL.currentContext.version < 2) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ ret = name_ == 33307 ? 3 : 0;+ // return version 3.0+ break;+ }+ if (ret === undefined) {+ var result = GLctx.getParameter(name_);+ switch (typeof result) {+ case "number":+ ret = result;+ break;++ case "boolean":+ ret = result ? 1 : 0;+ break;++ case "string":+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;++ case "object":+ if (result === null) {+ // null is a valid result for some (e.g., which buffer is bound -+ // perhaps nothing is bound), but otherwise can mean an invalid+ // name_, which we need to report as an error+ switch (name_) {+ case 34964:+ // ARRAY_BUFFER_BINDING+ case 35725:+ // CURRENT_PROGRAM+ case 34965:+ // ELEMENT_ARRAY_BUFFER_BINDING+ case 36006:+ // FRAMEBUFFER_BINDING or DRAW_FRAMEBUFFER_BINDING+ case 36007:+ // RENDERBUFFER_BINDING+ case 32873:+ // TEXTURE_BINDING_2D+ case 34229:+ // WebGL 2 GL_VERTEX_ARRAY_BINDING, or WebGL 1 extension OES_vertex_array_object GL_VERTEX_ARRAY_BINDING_OES+ case 36662:+ // COPY_READ_BUFFER_BINDING or COPY_READ_BUFFER+ case 36663:+ // COPY_WRITE_BUFFER_BINDING or COPY_WRITE_BUFFER+ case 35053:+ // PIXEL_PACK_BUFFER_BINDING+ case 35055:+ // PIXEL_UNPACK_BUFFER_BINDING+ case 36010:+ // READ_FRAMEBUFFER_BINDING+ case 35097:+ // SAMPLER_BINDING+ case 35869:+ // TEXTURE_BINDING_2D_ARRAY+ case 32874:+ // TEXTURE_BINDING_3D+ case 36389:+ // TRANSFORM_FEEDBACK_BINDING+ case 35983:+ // TRANSFORM_FEEDBACK_BUFFER_BINDING+ case 35368:+ // UNIFORM_BUFFER_BINDING+ case 34068:+ {+ // TEXTURE_BINDING_CUBE_MAP+ ret = 0;+ break;+ }++ default:+ {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ }+ } else if (result instanceof Float32Array || result instanceof Uint32Array || result instanceof Int32Array || result instanceof Array) {+ for (var i = 0; i < result.length; ++i) {+ switch (type) {+ case 0:+ HEAP32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 2:+ HEAPF32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 4:+ HEAP8[(p) + (i)] = result[i] ? 1 : 0;+ break;+ }+ }+ return;+ } else {+ try {+ ret = result.name | 0;+ } catch (e) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);+ return;+ }+ }+ break;++ default:+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof (result)}!`);+ return;+ }+ }+ switch (type) {+ case 1:+ writeI53ToI64(p, ret);+ break;++ case 0:+ HEAP32[((p) >> 2)] = ret;+ break;++ case 2:+ HEAPF32[((p) >> 2)] = ret;+ break;++ case 4:+ HEAP8[p] = ret ? 1 : 0;+ break;+ }+};++var _emscripten_glGetFloatv = (name_, p) => emscriptenWebGLGet(name_, p, 2);++var _glGetFloatv = _emscripten_glGetFloatv;++var _emscripten_glGetIntegerv = (name_, p) => emscriptenWebGLGet(name_, p, 0);++var _glGetIntegerv = _emscripten_glGetIntegerv;++var _emscripten_glGetProgramiv = (program, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (program >= GL.counter) {+ GL.recordError(1281);+ return;+ }+ program = GL.programs[program];+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getProgramInfoLog(program);+ if (log === null) log = "(unknown error)";+ HEAP32[((p) >> 2)] = log.length + 1;+ } else if (pname == 35719) {+ if (!program.maxUniformLength) {+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (var i = 0; i < numActiveUniforms; ++i) {+ program.maxUniformLength = Math.max(program.maxUniformLength, GLctx.getActiveUniform(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformLength;+ } else if (pname == 35722) {+ if (!program.maxAttributeLength) {+ var numActiveAttributes = GLctx.getProgramParameter(program, 35721);+ for (var i = 0; i < numActiveAttributes; ++i) {+ program.maxAttributeLength = Math.max(program.maxAttributeLength, GLctx.getActiveAttrib(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxAttributeLength;+ } else if (pname == 35381) {+ if (!program.maxUniformBlockNameLength) {+ var numActiveUniformBlocks = GLctx.getProgramParameter(program, 35382);+ for (var i = 0; i < numActiveUniformBlocks; ++i) {+ program.maxUniformBlockNameLength = Math.max(program.maxUniformBlockNameLength, GLctx.getActiveUniformBlockName(program, i).length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformBlockNameLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getProgramParameter(program, pname);+ }+};++var _glGetProgramiv = _emscripten_glGetProgramiv;++var _emscripten_glGetShaderInfoLog = (shader, maxLength, length, infoLog) => {+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;+ if (length) HEAP32[((length) >> 2)] = numBytesWrittenExclNull;+};++var _glGetShaderInfoLog = _emscripten_glGetShaderInfoLog;++var _emscripten_glGetShaderiv = (shader, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ // The GLES2 specification says that if the shader has an empty info log,+ // a value of 0 is returned. Otherwise the log has a null char appended.+ // (An empty string is falsey, so we can just check that instead of+ // looking at log.length.)+ var logLength = log ? log.length + 1 : 0;+ HEAP32[((p) >> 2)] = logLength;+ } else if (pname == 35720) {+ // GL_SHADER_SOURCE_LENGTH+ var source = GLctx.getShaderSource(GL.shaders[shader]);+ // source may be a null, or the empty string, both of which are falsey+ // values that we report a 0 length for.+ var sourceLength = source ? source.length + 1 : 0;+ HEAP32[((p) >> 2)] = sourceLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getShaderParameter(GL.shaders[shader], pname);+ }+};++var _glGetShaderiv = _emscripten_glGetShaderiv;++var _emscripten_glGetString = name_ => {+ var ret = GL.stringCache[name_];+ if (!ret) {+ switch (name_) {+ case 7939:+ ret = stringToNewUTF8(webglGetExtensions().join(" "));+ break;++ case 7936:+ case 7937:+ case 37445:+ case 37446:+ var s = GLctx.getParameter(name_);+ if (!s) {+ GL.recordError(1280);+ }+ ret = s ? stringToNewUTF8(s) : 0;+ break;++ case 7938:+ var webGLVersion = GLctx.getParameter(7938);+ // return GLES version string corresponding to the version of the WebGL context+ var glVersion = `OpenGL ES 2.0 (${webGLVersion})`;+ if (GL.currentContext.version >= 2) glVersion = `OpenGL ES 3.0 (${webGLVersion})`;+ ret = stringToNewUTF8(glVersion);+ break;++ case 35724:+ var glslVersion = GLctx.getParameter(35724);+ // extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...'+ var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;+ var ver_num = glslVersion.match(ver_re);+ if (ver_num !== null) {+ if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + "0";+ // ensure minor version has 2 digits+ glslVersion = `OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`;+ }+ ret = stringToNewUTF8(glslVersion);+ break;++ default:+ GL.recordError(1280);+ }+ GL.stringCache[name_] = ret;+ }+ return ret;+};++var _glGetString = _emscripten_glGetString;++var _emscripten_glGetUniformBlockIndex = (program, uniformBlockName) => GLctx.getUniformBlockIndex(GL.programs[program], UTF8ToString(uniformBlockName));++var _glGetUniformBlockIndex = _emscripten_glGetUniformBlockIndex;++/** @suppress {checkTypes} */ var jstoi_q = str => parseInt(str);++/** @noinline */ var webglGetLeftBracePos = name => name.slice(-1) == "]" && name.lastIndexOf("[");++var webglPrepareUniformLocationsBeforeFirstUse = program => {+ var uniformLocsById = program.uniformLocsById, // Maps GLuint -> WebGLUniformLocation+ uniformSizeAndIdsByName = program.uniformSizeAndIdsByName, // Maps name -> [uniform array length, GLuint]+ i, j;+ // On the first time invocation of glGetUniformLocation on this shader program:+ // initialize cache data structures and discover which uniforms are arrays.+ if (!uniformLocsById) {+ // maps GLint integer locations to WebGLUniformLocations+ program.uniformLocsById = uniformLocsById = {};+ // maps integer locations back to uniform name strings, so that we can lazily fetch uniform array locations+ program.uniformArrayNamesById = {};+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (i = 0; i < numActiveUniforms; ++i) {+ var u = GLctx.getActiveUniform(program, i);+ var nm = u.name;+ var sz = u.size;+ var lb = webglGetLeftBracePos(nm);+ var arrayName = lb > 0 ? nm.slice(0, lb) : nm;+ // Assign a new location.+ var id = program.uniformIdCounter;+ program.uniformIdCounter += sz;+ // Eagerly get the location of the uniformArray[0] base element.+ // The remaining indices >0 will be left for lazy evaluation to+ // improve performance. Those may never be needed to fetch, if the+ // application fills arrays always in full starting from the first+ // element of the array.+ uniformSizeAndIdsByName[arrayName] = [ sz, id ];+ // Store placeholder integers in place that highlight that these+ // >0 index locations are array indices pending population.+ for (j = 0; j < sz; ++j) {+ uniformLocsById[id] = j;+ program.uniformArrayNamesById[id++] = arrayName;+ }+ }+ }+};++var _emscripten_glGetUniformLocation = (program, name) => {+ name = UTF8ToString(name);+ if (program = GL.programs[program]) {+ webglPrepareUniformLocationsBeforeFirstUse(program);+ var uniformLocsById = program.uniformLocsById;+ // Maps GLuint -> WebGLUniformLocation+ var arrayIndex = 0;+ var uniformBaseName = name;+ // Invariant: when populating integer IDs for uniform locations, we must+ // maintain the precondition that arrays reside in contiguous addresses,+ // i.e. for a 'vec4 colors[10];', colors[4] must be at location+ // colors[0]+4. However, user might call glGetUniformLocation(program,+ // "colors") for an array, so we cannot discover based on the user input+ // arguments whether the uniform we are dealing with is an array. The only+ // way to discover which uniforms are arrays is to enumerate over all the+ // active uniforms in the program.+ var leftBrace = webglGetLeftBracePos(name);+ // If user passed an array accessor "[index]", parse the array index off the accessor.+ if (leftBrace > 0) {+ arrayIndex = jstoi_q(name.slice(leftBrace + 1)) >>> 0;+ // "index]", coerce parseInt(']') with >>>0 to treat "foo[]" as "foo[0]" and foo[-1] as unsigned out-of-bounds.+ uniformBaseName = name.slice(0, leftBrace);+ }+ // Have we cached the location of this uniform before?+ // A pair [array length, GLint of the uniform location]+ var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName];+ // If a uniform with this name exists, and if its index is within the+ // array limits (if it's even an array), query the WebGLlocation, or+ // return an existing cached location.+ if (sizeAndId && arrayIndex < sizeAndId[0]) {+ arrayIndex += sizeAndId[1];+ // Add the base location of the uniform to the array index offset.+ if ((uniformLocsById[arrayIndex] = uniformLocsById[arrayIndex] || GLctx.getUniformLocation(program, name))) {+ return arrayIndex;+ }+ }+ } else {+ // N.b. we are currently unable to distinguish between GL program IDs that+ // never existed vs GL program IDs that have been deleted, so report+ // GL_INVALID_VALUE in both cases.+ GL.recordError(1281);+ }+ return -1;+};++var _glGetUniformLocation = _emscripten_glGetUniformLocation;++var _emscripten_glLineWidth = x0 => GLctx.lineWidth(x0);++var _glLineWidth = _emscripten_glLineWidth;++var _emscripten_glLinkProgram = program => {+ program = GL.programs[program];+ GLctx.linkProgram(program);+ // Invalidate earlier computed uniform->ID mappings, those have now become stale+ program.uniformLocsById = 0;+ // Mark as null-like so that glGetUniformLocation() knows to populate this again.+ program.uniformSizeAndIdsByName = {};+};++var _glLinkProgram = _emscripten_glLinkProgram;++var _emscripten_glPixelStorei = (pname, param) => {+ if (pname == 3317) {+ GL.unpackAlignment = param;+ } else if (pname == 3314) {+ GL.unpackRowLength = param;+ }+ GLctx.pixelStorei(pname, param);+};++var _glPixelStorei = _emscripten_glPixelStorei;++var computeUnpackAlignedImageSize = (width, height, sizePerPixel) => {+ function roundedToNextMultipleOf(x, y) {+ return (x + y - 1) & -y;+ }+ var plainRowSize = (GL.unpackRowLength || width) * sizePerPixel;+ var alignedRowSize = roundedToNextMultipleOf(plainRowSize, GL.unpackAlignment);+ return height * alignedRowSize;+};++var colorChannelsInGlTextureFormat = format => {+ // Micro-optimizations for size: map format to size by subtracting smallest+ // enum value (0x1902) from all values first. Also omit the most common+ // size value (1) from the list, which is assumed by formats not on the+ // list.+ var colorChannels = {+ // 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1,+ // 0x1906 /* GL_ALPHA */ - 0x1902: 1,+ 5: 3,+ 6: 4,+ // 0x1909 /* GL_LUMINANCE */ - 0x1902: 1,+ 8: 2,+ 29502: 3,+ 29504: 4,+ // 0x1903 /* GL_RED */ - 0x1902: 1,+ 26917: 2,+ 26918: 2,+ // 0x8D94 /* GL_RED_INTEGER */ - 0x1902: 1,+ 29846: 3,+ 29847: 4+ };+ return colorChannels[format - 6402] || 1;+};++var heapObjectForWebGLType = type => {+ // Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare+ // smaller values for the heap, for shorter generated code size.+ // Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16.+ // (since most types are HEAPU16)+ type -= 5120;+ if (type == 0) return HEAP8;+ if (type == 1) return HEAPU8;+ if (type == 2) return HEAP16;+ if (type == 4) return HEAP32;+ if (type == 6) return HEAPF32;+ if (type == 5 || type == 28922 || type == 28520 || type == 30779 || type == 30782) return HEAPU32;+ return HEAPU16;+};++var toTypedArrayIndex = (pointer, heap) => pointer >>> (31 - Math.clz32(heap.BYTES_PER_ELEMENT));++var emscriptenWebGLGetTexPixelData = (type, format, width, height, pixels) => {+ var heap = heapObjectForWebGLType(type);+ var sizePerPixel = colorChannelsInGlTextureFormat(format) * heap.BYTES_PER_ELEMENT;+ var bytes = computeUnpackAlignedImageSize(width, height, sizePerPixel);+ return heap.subarray(toTypedArrayIndex(pixels, heap), toTypedArrayIndex(pixels + bytes, heap));+};++var _emscripten_glReadPixels = (x, y, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelPackBufferBinding) {+ GLctx.readPixels(x, y, width, height, format, type, pixels);+ return;+ }+ var heap = heapObjectForWebGLType(type);+ var target = toTypedArrayIndex(pixels, heap);+ GLctx.readPixels(x, y, width, height, format, type, heap, target);+ return;+ }+ var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels);+ if (!pixelData) {+ GL.recordError(1280);+ return;+ }+ GLctx.readPixels(x, y, width, height, format, type, pixelData);+};++var _glReadPixels = _emscripten_glReadPixels;++var _emscripten_glShaderSource = (shader, count, string, length) => {+ var source = GL.getSource(shader, count, string, length);+ GLctx.shaderSource(GL.shaders[shader], source);+};++var _glShaderSource = _emscripten_glShaderSource;++var _emscripten_glTexImage2D = (target, level, internalFormat, width, height, border, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ var index = toTypedArrayIndex(pixels, heap);+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, heap, index);+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels) : null;+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixelData);+};++var _glTexImage2D = _emscripten_glTexImage2D;++var _emscripten_glTexParameterf = (x0, x1, x2) => GLctx.texParameterf(x0, x1, x2);++var _glTexParameterf = _emscripten_glTexParameterf;++var _emscripten_glTexParameterfv = (target, pname, params) => {+ var param = HEAPF32[((params) >> 2)];+ GLctx.texParameterf(target, pname, param);+};++var _glTexParameterfv = _emscripten_glTexParameterfv;++var _emscripten_glTexParameteri = (x0, x1, x2) => GLctx.texParameteri(x0, x1, x2);++var _glTexParameteri = _emscripten_glTexParameteri;++var _emscripten_glTexStorage2D = (x0, x1, x2, x3, x4) => GLctx.texStorage2D(x0, x1, x2, x3, x4);++var _glTexStorage2D = _emscripten_glTexStorage2D;++var _emscripten_glTexStorage3D = (x0, x1, x2, x3, x4, x5) => GLctx.texStorage3D(x0, x1, x2, x3, x4, x5);++var _glTexStorage3D = _emscripten_glTexStorage3D;++var _emscripten_glTexSubImage2D = (target, level, xoffset, yoffset, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, heap, toTypedArrayIndex(pixels, heap));+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels) : null;+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData);+};++var _glTexSubImage2D = _emscripten_glTexSubImage2D;++var _emscripten_glTexSubImage3D = (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels) => {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);+ } else if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, heap, toTypedArrayIndex(pixels, heap));+ } else {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, null);+ }+};++var _glTexSubImage3D = _emscripten_glTexSubImage3D;++var webglGetProgramUniformLocation = (program, location) => {+ if (program) {+ var webglLoc = program.uniformLocsById[location];+ // program.uniformLocsById[location] stores either an integer, or a+ // WebGLUniformLocation.+ // If an integer, we have not yet bound the location, so do it now. The+ // integer value specifies the array index we should bind to.+ if (typeof webglLoc == "number") {+ program.uniformLocsById[location] = webglLoc = GLctx.getUniformLocation(program, program.uniformArrayNamesById[location] + (webglLoc > 0 ? `[${webglLoc}]` : ""));+ }+ // Else an already cached WebGLUniformLocation, return it.+ return webglLoc;+ } else {+ GL.recordError(1282);+ }+};++var webglGetUniformLocation = location => webglGetProgramUniformLocation(GLctx.currentProgram, location);++var _emscripten_glUniform1f = (location, v0) => {+ GLctx.uniform1f(webglGetUniformLocation(location), v0);+};++var _glUniform1f = _emscripten_glUniform1f;++var miniTempWebGLFloatBuffers = [];++var _emscripten_glUniform1fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform1fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count);+ return;+ }+ if (count <= 288) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; ++i) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 4) >> 2));+ }+ GLctx.uniform1fv(webglGetUniformLocation(location), view);+};++var _glUniform1fv = _emscripten_glUniform1fv;++var _emscripten_glUniform1i = (location, v0) => {+ GLctx.uniform1i(webglGetUniformLocation(location), v0);+};++var _glUniform1i = _emscripten_glUniform1i;++var _emscripten_glUniform2f = (location, v0, v1) => {+ GLctx.uniform2f(webglGetUniformLocation(location), v0, v1);+};++var _glUniform2f = _emscripten_glUniform2f;++var _emscripten_glUniform2fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform2fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 2);+ return;+ }+ if (count <= 144) {+ // avoid allocation when uploading few enough uniforms+ count *= 2;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 2) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 8) >> 2));+ }+ GLctx.uniform2fv(webglGetUniformLocation(location), view);+};++var _glUniform2fv = _emscripten_glUniform2fv;++var _emscripten_glUniform3f = (location, v0, v1, v2) => {+ GLctx.uniform3f(webglGetUniformLocation(location), v0, v1, v2);+};++var _glUniform3f = _emscripten_glUniform3f;++var _emscripten_glUniform4f = (location, v0, v1, v2, v3) => {+ GLctx.uniform4f(webglGetUniformLocation(location), v0, v1, v2, v3);+};++var _glUniform4f = _emscripten_glUniform4f;++var _emscripten_glUniform4fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[4 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 4;+ for (var i = 0; i < count; i += 4) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4fv(webglGetUniformLocation(location), view);+};++var _glUniform4fv = _emscripten_glUniform4fv;++var miniTempWebGLIntBuffers = [];++var _emscripten_glUniform4iv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4iv(webglGetUniformLocation(location), HEAP32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLIntBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAP32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAP32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAP32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAP32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAP32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4iv(webglGetUniformLocation(location), view);+};++var _glUniform4iv = _emscripten_glUniform4iv;++var _emscripten_glUniformBlockBinding = (program, uniformBlockIndex, uniformBlockBinding) => {+ program = GL.programs[program];+ GLctx.uniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);+};++var _glUniformBlockBinding = _emscripten_glUniformBlockBinding;++var _emscripten_glUniformMatrix2fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix2fv = _emscripten_glUniformMatrix2fv;++var _emscripten_glUniformMatrix3fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 9);+ return;+ }+ if (count <= 32) {+ // avoid allocation when uploading few enough uniforms+ count *= 9;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 9) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ view[i + 4] = HEAPF32[(((value) + (4 * i + 16)) >> 2)];+ view[i + 5] = HEAPF32[(((value) + (4 * i + 20)) >> 2)];+ view[i + 6] = HEAPF32[(((value) + (4 * i + 24)) >> 2)];+ view[i + 7] = HEAPF32[(((value) + (4 * i + 28)) >> 2)];+ view[i + 8] = HEAPF32[(((value) + (4 * i + 32)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 36) >> 2));+ }+ GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix3fv = _emscripten_glUniformMatrix3fv;++var _emscripten_glUniformMatrix4fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 16);+ return;+ }+ if (count <= 18) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[16 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 16;+ for (var i = 0; i < count; i += 16) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ view[i + 4] = heap[dst + 4];+ view[i + 5] = heap[dst + 5];+ view[i + 6] = heap[dst + 6];+ view[i + 7] = heap[dst + 7];+ view[i + 8] = heap[dst + 8];+ view[i + 9] = heap[dst + 9];+ view[i + 10] = heap[dst + 10];+ view[i + 11] = heap[dst + 11];+ view[i + 12] = heap[dst + 12];+ view[i + 13] = heap[dst + 13];+ view[i + 14] = heap[dst + 14];+ view[i + 15] = heap[dst + 15];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 64) >> 2));+ }+ GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix4fv = _emscripten_glUniformMatrix4fv;++var _emscripten_glUseProgram = program => {+ program = GL.programs[program];+ GLctx.useProgram(program);+ // Record the currently active program so that we can access the uniform+ // mapping table of that program.+ GLctx.currentProgram = program;+};++var _glUseProgram = _emscripten_glUseProgram;++var _emscripten_glVertexAttribPointer = (index, size, type, normalized, stride, ptr) => {+ var cb = GL.currentContext.clientBuffers[index];+ if (!GLctx.currentArrayBufferBinding) {+ cb.size = size;+ cb.type = type;+ cb.normalized = normalized;+ cb.stride = stride;+ cb.ptr = ptr;+ cb.clientside = true;+ cb.vertexAttribPointerAdaptor = /** @this {WebGLRenderingContext} */ function(index, size, type, normalized, stride, ptr) {+ this.vertexAttribPointer(index, size, type, normalized, stride, ptr);+ };+ return;+ }+ cb.clientside = false;+ GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);+};++var _glVertexAttribPointer = _emscripten_glVertexAttribPointer;++var _emscripten_glViewport = (x0, x1, x2, x3) => GLctx.viewport(x0, x1, x2, x3);++var _glViewport = _emscripten_glViewport;++function _mediapipe_find_canvas_event_target(canvasSelector) {+ let target = findCanvasEventTarget(canvasSelector);+ // WebGPU-on-worker uses this function to try to grab the canvas, but+ // doesn't have a DOM element to find. So as a quick patch, if the default+ // behavior is unsuccessful here then we try a webgpu canvas property+ // which is set by the user directly on the Module, much like how our old+ // pipeline used the Module.canvas property. See b/265271517 for details.+ if (Module && !target) {+ target = Module.canvasWebGpu;+ }+ return Emval.toHandle(target);+}++function _mediapipe_webgl_tex_image_drawable(drawableHandle) {+ const drawable = Emval.toValue(drawableHandle);+ GLctx.texImage2D(GLctx.TEXTURE_2D, 0, GLctx.RGBA, GLctx.RGBA, GLctx.UNSIGNED_BYTE, drawable);+}++var _random_get = (buffer, size) => randomFill(HEAPU8.subarray(buffer, buffer + size));++var _wgpuCommandEncoderBeginComputePass = (encoderPtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (12)) >> 2)])+ };+ }+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateComputePassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginComputePass(desc));+ return ptr;+};++var _wgpuCommandEncoderBeginRenderPass = (encoderPtr, descriptor) => {+ function makeColorAttachment(caPtr) {+ var viewPtr = HEAPU32[(((caPtr) + (4)) >> 2)];+ if (viewPtr === 0) {+ // Null `view` means no attachment in this slot.+ return undefined;+ }+ var depthSlice = HEAPU32[(((caPtr) + (8)) >> 2)];+ if (depthSlice == 4294967295) depthSlice = undefined;+ return {+ "view": WebGPU.getJsObject(viewPtr),+ "depthSlice": depthSlice,+ "resolveTarget": WebGPU.getJsObject(HEAPU32[(((caPtr) + (12)) >> 2)]),+ "clearValue": WebGPU.makeColor(caPtr + 24),+ "loadOp": WebGPU.LoadOp[HEAP32[(((caPtr) + (16)) >> 2)]],+ "storeOp": WebGPU.StoreOp[HEAP32[(((caPtr) + (20)) >> 2)]]+ };+ }+ function makeColorAttachments(count, caPtr) {+ var attachments = [];+ for (var i = 0; i < count; ++i) {+ attachments.push(makeColorAttachment(caPtr + 56 * i));+ }+ return attachments;+ }+ function makeDepthStencilAttachment(dsaPtr) {+ if (dsaPtr === 0) return undefined;+ return {+ "view": WebGPU.getJsObject(HEAPU32[(((dsaPtr) + (4)) >> 2)]),+ "depthClearValue": HEAPF32[(((dsaPtr) + (16)) >> 2)],+ "depthLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (8)) >> 2)]],+ "depthStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (12)) >> 2)]],+ "depthReadOnly": !!(HEAPU32[(((dsaPtr) + (20)) >> 2)]),+ "stencilClearValue": HEAPU32[(((dsaPtr) + (32)) >> 2)],+ "stencilLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (24)) >> 2)]],+ "stencilStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (28)) >> 2)]],+ "stencilReadOnly": !!(HEAPU32[(((dsaPtr) + (36)) >> 2)])+ };+ }+ function makeRenderPassDescriptor(descriptor) {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var maxDrawCount = undefined;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var renderPassMaxDrawCount = nextInChainPtr;+ // Note: The user could have passed a really huge value here, which is technically valid in+ // C but will not be allowed by WebGPU in JS because of [EnforceRange]. We intentionally+ // ignore that case because it's not useful - apps can just pick a smaller maxDrawCount.+ maxDrawCount = readI53FromI64((renderPassMaxDrawCount) + (8));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "colorAttachments": makeColorAttachments(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)]),+ "depthStencilAttachment": makeDepthStencilAttachment(HEAPU32[(((descriptor) + (20)) >> 2)]),+ "occlusionQuerySet": WebGPU.getJsObject(HEAPU32[(((descriptor) + (24)) >> 2)]),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (28)) >> 2)]),+ "maxDrawCount": maxDrawCount+ };+ return desc;+ }+ var desc = makeRenderPassDescriptor(descriptor);+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateRenderPassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginRenderPass(desc));+ return ptr;+};++var _wgpuCommandEncoderCopyBufferToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyBufferToTexture(WebGPU.makeTexelCopyBufferInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToBuffer = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToBuffer(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyBufferInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToTexture(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderFinish = (encoderPtr, descriptor) => {+ // TODO: Use the descriptor.+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateCommandBuffer(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.finish());+ return ptr;+};++var _wgpuComputePassEncoderDispatchWorkgroups = (passPtr, x, y, z) => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.dispatchWorkgroups(x, y, z);+};++var _wgpuComputePassEncoderEnd = passPtr => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.end();+};++var _wgpuComputePassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuComputePassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuComputePipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuDeviceCreateBindGroup = (devicePtr, descriptor) => {+ function makeEntry(entryPtr) {+ var bufferPtr = HEAPU32[(((entryPtr) + (8)) >> 2)];+ var samplerPtr = HEAPU32[(((entryPtr) + (32)) >> 2)];+ var textureViewPtr = HEAPU32[(((entryPtr) + (36)) >> 2)];+ var externalTexturePtr = 0;+ WebGPU.iterateExtensions(entryPtr, {+ 14: ptr => {+ externalTexturePtr = HEAPU32[(((ptr) + (8)) >> 2)];+ }+ });+ var resource;+ if (bufferPtr) {+ // Note the sentinel UINT64_MAX will be read as -1.+ var size = readI53FromI64((entryPtr) + (24));+ if (size == -1) size = undefined;+ resource = {+ "buffer": WebGPU.getJsObject(bufferPtr),+ "offset": readI53FromI64((entryPtr) + (16)),+ "size": size+ };+ } else {+ resource = WebGPU.getJsObject(samplerPtr || textureViewPtr || externalTexturePtr);+ }+ return {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "resource": resource+ };+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 40 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.getJsObject(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "entries": makeEntries(HEAPU32[(((descriptor) + (16)) >> 2)], HEAPU32[(((descriptor) + (20)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroup(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroup(desc));+ return ptr;+};++var _wgpuDeviceCreateBindGroupLayout = (devicePtr, descriptor) => {+ function makeBufferEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.BufferBindingType[typeInt],+ "hasDynamicOffset": !!(HEAPU32[(((substructPtr) + (8)) >> 2)]),+ "minBindingSize": readI53FromI64((substructPtr) + (16))+ };+ }+ function makeSamplerEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.SamplerBindingType[typeInt]+ };+ }+ function makeTextureEntry(substructPtr) {+ var sampleTypeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!sampleTypeInt) return undefined;+ return {+ "sampleType": WebGPU.TextureSampleType[sampleTypeInt],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "multisampled": !!(HEAPU32[(((substructPtr) + (12)) >> 2)])+ };+ }+ function makeStorageTextureEntry(substructPtr) {+ var accessInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!accessInt) return undefined;+ return {+ "access": WebGPU.StorageTextureAccess[accessInt],+ "format": WebGPU.TextureFormat[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (12)) >> 2)]]+ };+ }+ function makeEntry(entryPtr) {+ var entry = {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "visibility": HEAPU32[(((entryPtr) + (8)) >> 2)],+ "buffer": makeBufferEntry(entryPtr + 24),+ "sampler": makeSamplerEntry(entryPtr + 48),+ "texture": makeTextureEntry(entryPtr + 56),+ "storageTexture": makeStorageTextureEntry(entryPtr + 72)+ };+ WebGPU.iterateExtensions(entryPtr, {+ 13: ptr => {+ entry["externalTexture"] = {};+ }+ });+ return entry;+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 88 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "entries": makeEntries(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroupLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateCommandEncoder = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4)+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateCommandEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createCommandEncoder(desc));+ return ptr;+};++var _wgpuDeviceCreateComputePipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateComputePipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createComputePipeline(desc));+ return ptr;+};++var _wgpuDeviceCreatePipelineLayout = (devicePtr, descriptor) => {+ var bglCount = HEAPU32[(((descriptor) + (12)) >> 2)];+ var bglPtr = HEAPU32[(((descriptor) + (16)) >> 2)];+ var bgls = [];+ for (var i = 0; i < bglCount; ++i) {+ bgls.push(WebGPU.getJsObject(HEAPU32[(((bglPtr) + (4 * i)) >> 2)]));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "bindGroupLayouts": bgls,+ "immediateSize": HEAPU32[(((descriptor) + (20)) >> 2)]+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreatePipelineLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createPipelineLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateRenderPipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateRenderPipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createRenderPipeline(desc));+ return ptr;+};++var _wgpuDeviceCreateSampler = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "addressModeU": WebGPU.AddressMode[HEAP32[(((descriptor) + (12)) >> 2)]],+ "addressModeV": WebGPU.AddressMode[HEAP32[(((descriptor) + (16)) >> 2)]],+ "addressModeW": WebGPU.AddressMode[HEAP32[(((descriptor) + (20)) >> 2)]],+ "magFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (24)) >> 2)]],+ "minFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (28)) >> 2)]],+ "mipmapFilter": WebGPU.MipmapFilterMode[HEAP32[(((descriptor) + (32)) >> 2)]],+ "lodMinClamp": HEAPF32[(((descriptor) + (36)) >> 2)],+ "lodMaxClamp": HEAPF32[(((descriptor) + (40)) >> 2)],+ "compare": WebGPU.CompareFunction[HEAP32[(((descriptor) + (44)) >> 2)]],+ "maxAnisotropy": HEAPU16[(((descriptor) + (48)) >> 1)]+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateSampler(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createSampler(desc));+ return ptr;+};++var _wgpuDeviceCreateTexture = (devicePtr, descriptor) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var textureBindingViewDimension;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var textureBindingViewDimensionDescriptor = nextInChainPtr;+ textureBindingViewDimension = WebGPU.TextureViewDimension[HEAP32[(((textureBindingViewDimensionDescriptor) + (8)) >> 2)]];+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "size": WebGPU.makeExtent3D(descriptor + 28),+ "mipLevelCount": HEAPU32[(((descriptor) + (44)) >> 2)],+ "sampleCount": HEAPU32[(((descriptor) + (48)) >> 2)],+ "dimension": WebGPU.TextureDimension[HEAP32[(((descriptor) + (24)) >> 2)]],+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (40)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "textureBindingViewDimension": textureBindingViewDimension+ };+ var viewFormatCount = HEAPU32[(((descriptor) + (52)) >> 2)];+ if (viewFormatCount) {+ var viewFormatsPtr = HEAPU32[(((descriptor) + (56)) >> 2)];+ // viewFormatsPtr pointer to an array of TextureFormat which is an enum of size uint32_t+ desc["viewFormats"] = Array.from(HEAP32.subarray((((viewFormatsPtr) >> 2)), ((viewFormatsPtr + viewFormatCount * 4) >> 2)), format => WebGPU.TextureFormat[format]);+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateTexture(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createTexture(desc));+ return ptr;+};++var _wgpuQueueSubmit = (queuePtr, commandCount, commands) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var cmds = Array.from(HEAP32.subarray((((commands) >> 2)), ((commands + commandCount * 4) >> 2)), id => WebGPU.getJsObject(id));+ queue.submit(cmds);+};++function _wgpuQueueWriteBuffer(queuePtr, bufferPtr, bufferOffset_low, bufferOffset_high, data, size) {+ var bufferOffset = convertI32PairToI53Checked(bufferOffset_low, bufferOffset_high);+ var queue = WebGPU.getJsObject(queuePtr);+ var buffer = WebGPU.getJsObject(bufferPtr);+ // There is a size limitation for ArrayBufferView. Work around by passing in a subarray+ // instead of the whole heap. crbug.com/1201109+ var subarray = HEAPU8.subarray(data, data + size);+ queue.writeBuffer(buffer, bufferOffset, subarray, 0, size);+}++var _wgpuQueueWriteTexture = (queuePtr, destinationPtr, data, dataSize, dataLayoutPtr, writeSizePtr) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var destination = WebGPU.makeTexelCopyTextureInfo(destinationPtr);+ var dataLayout = WebGPU.makeTexelCopyBufferLayout(dataLayoutPtr);+ var writeSize = WebGPU.makeExtent3D(writeSizePtr);+ // This subarray isn't strictly necessary, but helps work around an issue+ // where Chromium makes a copy of the entire heap. crbug.com/1134457+ var subarray = HEAPU8.subarray(data, data + dataSize);+ queue.writeTexture(destination, subarray, dataLayout, writeSize);+};++var _wgpuRenderPassEncoderDraw = (passPtr, vertexCount, instanceCount, firstVertex, firstInstance) => {+ firstVertex >>>= 0;+ firstInstance >>>= 0;+ var pass = WebGPU.getJsObject(passPtr);+ pass.draw(vertexCount, instanceCount, firstVertex, firstInstance);+};++var _wgpuRenderPassEncoderEnd = encoderPtr => {+ var encoder = WebGPU.getJsObject(encoderPtr);+ encoder.end();+};++var _wgpuRenderPassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuRenderPassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuRenderPipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuTextureCreateView = (texturePtr, descriptor) => {+ var desc;+ if (descriptor) {+ var swizzle;+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var swizzleDescriptor = nextInChainPtr;+ var swizzlePtr = swizzleDescriptor + 8;+ var r = WebGPU.ComponentSwizzle[HEAP32[((swizzlePtr) >> 2)]] || "r";+ var g = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (4)) >> 2)]] || "g";+ var b = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (8)) >> 2)]] || "b";+ var a = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (12)) >> 2)]] || "a";+ swizzle = `${r}${g}${b}${a}`;+ }+ var mipLevelCount = HEAPU32[(((descriptor) + (24)) >> 2)];+ var arrayLayerCount = HEAPU32[(((descriptor) + (32)) >> 2)];+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (12)) >> 2)]],+ "dimension": WebGPU.TextureViewDimension[HEAP32[(((descriptor) + (16)) >> 2)]],+ "baseMipLevel": HEAPU32[(((descriptor) + (20)) >> 2)],+ "mipLevelCount": mipLevelCount === 4294967295 ? undefined : mipLevelCount,+ "baseArrayLayer": HEAPU32[(((descriptor) + (28)) >> 2)],+ "arrayLayerCount": arrayLayerCount === 4294967295 ? undefined : arrayLayerCount,+ "aspect": WebGPU.TextureAspect[HEAP32[(((descriptor) + (36)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (40)) >> 2)],+ "swizzle": swizzle+ };+ }+ var texture = WebGPU.getJsObject(texturePtr);+ var ptr = _emwgpuCreateTextureView(0);+ WebGPU.Internals.jsObjectInsert(ptr, texture.createView(desc));+ return ptr;+};++var _wgpuTextureDestroy = texturePtr => {+ WebGPU.getJsObject(texturePtr).destroy();+};++var _wgpuTextureGetFormat = texturePtr => {+ var texture = WebGPU.getJsObject(texturePtr);+ // Should return the enum integer instead of string.+ return WebGPU.TextureFormat.indexOf(texture.format);+};++var getCFunc = ident => {+ var func = Module["_" + ident];+ // closure exported function+ return func;+};++var writeArrayToMemory = (array, buffer) => {+ HEAP8.set(array, buffer);+};++/**+ * @param {string|null=} returnType+ * @param {Array=} argTypes+ * @param {Array=} args+ * @param {Object=} opts+ */ var ccall = (ident, returnType, argTypes, args, opts) => {+ // For fast lookup of conversion functions+ var toC = {+ "string": str => {+ var ret = 0;+ if (str !== null && str !== undefined && str !== 0) {+ // null string+ ret = stringToUTF8OnStack(str);+ }+ return ret;+ },+ "array": arr => {+ var ret = stackAlloc(arr.length);+ writeArrayToMemory(arr, ret);+ return ret;+ }+ };+ function convertReturnValue(ret) {+ if (returnType === "string") {+ return UTF8ToString(ret);+ }+ if (returnType === "boolean") return Boolean(ret);+ return ret;+ }+ var func = getCFunc(ident);+ var cArgs = [];+ var stack = 0;+ if (args) {+ for (var i = 0; i < args.length; i++) {+ var converter = toC[argTypes[i]];+ if (converter) {+ if (!stack) stack = stackSave();+ cArgs[i] = converter(args[i]);+ } else {+ cArgs[i] = args[i];+ }+ }+ }+ var ret = func(...cArgs);+ function onDone(ret) {+ if (stack) stackRestore(stack);+ return convertReturnValue(ret);+ }+ ret = onDone(ret);+ return ret;+};++var FS_createPath = (...args) => FS.createPath(...args);++var FS_unlink = (...args) => FS.unlink(...args);++var FS_createLazyFile = (...args) => FS.createLazyFile(...args);++var FS_createDevice = (...args) => FS.createDevice(...args);++FS.createPreloadedFile = FS_createPreloadedFile;++FS.preloadFile = FS_preloadFile;++FS.staticInit();++// Signal GL rendering layer that processing of a new frame is about to+// start. This helps it optimize VBO double-buffering and reduce GPU stalls.+registerPreMainLoop(() => GL.newRenderingFrameStarted());++for (let i = 0; i < 32; ++i) tempFixedLengthArray.push(new Array(i));++var miniTempWebGLFloatBuffersStorage = new Float32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLFloatBuffers[i] = miniTempWebGLFloatBuffersStorage.subarray(0, i);+}++var miniTempWebGLIntBuffersStorage = new Int32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLIntBuffers[i] = miniTempWebGLIntBuffersStorage.subarray(0, i);+}++// End JS library code+// include: postlibrary.js+// This file is included after the automatically-generated JS library code+// but before the wasm module is created.+{+ // Begin ATMODULES hooks+ if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"];+ if (Module["print"]) out = Module["print"];+ if (Module["printErr"]) err = Module["printErr"];+ // End ATMODULES hooks+ if (Module["arguments"]) programArgs = Module["arguments"];+ if (Module["thisProgram"]) thisProgram = Module["thisProgram"];+ var preInit = Module["preInit"];+ if (preInit) {+ if (typeof preInit == "function") Module["preInit"] = preInit = [ preInit ];+ // Written as a loop so that preInit functions that themselves add more+ // preInit functions. Is this actually needed?+ while (preInit.length > 0) {+ preInit.shift()();+ }+ }+}++// Begin runtime exports+Module["addRunDependency"] = addRunDependency;++Module["removeRunDependency"] = removeRunDependency;++Module["ccall"] = ccall;++Module["stringToNewUTF8"] = stringToNewUTF8;++Module["FS_preloadFile"] = FS_preloadFile;++Module["FS_unlink"] = FS_unlink;++Module["FS_createPath"] = FS_createPath;++Module["FS_createDevice"] = FS_createDevice;++Module["FS_createDataFile"] = FS_createDataFile;++Module["FS_createLazyFile"] = FS_createLazyFile;++// End runtime exports+// Begin JS library exports+// End JS library exports+// end include: postlibrary.js+var ASM_CONSTS = {+ 1607348: $0 => {+ const canvas = Emval.toValue($0);+ const context = canvas.getContext("webgpu");+ return WebGPU.importJsTexture(context.getCurrentTexture());+ },+ 1607491: ($0, $1, $2, $3, $4) => {+ const drawable = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const texture = WebGPU.getJsObject($2);+ const width = $3;+ const height = $4;+ device.queue.copyExternalImageToTexture({+ source: drawable+ }, {+ texture+ }, [ width, height ]);+ },+ 1607750: ($0, $1, $2, $3) => {+ const sourceExtTex = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const sampler = WebGPU.getJsObject($2);+ const bgLayout = WebGPU.getJsObject($3);+ const bindGroup = device.createBindGroup({+ layout: bgLayout,+ entries: [ {+ binding: 0,+ resource: sampler+ }, {+ binding: 1,+ resource: sourceExtTex+ } ]+ });+ return WebGPU.importJsBindGroup(bindGroup);+ },+ 1608120: ($0, $1) => {+ const input = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ ctx.drawImage(input, 0, 0, output.width, output.height);+ },+ 1608285: ($0, $1) => {+ const inputArray = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ const image_data = new ImageData(inputArray, output.width, output.height);+ ctx.putImageData(image_data, 0, 0);+ },+ 1608509: ($0, $1) => {+ const input = Emval.toValue($0);+ const outputArray = Emval.toValue($1);+ const ctx = input.getContext("2d");+ const data = ctx.getImageData(0, 0, input.width, input.height);+ outputArray.set(data.data);+ },+ 1608713: () => (typeof HTMLCanvasElement !== "undefined"),+ 1608768: () => !!Module["preinitializedWebGPUDevice"],+ 1608819: () => {+ specialHTMLTargets["#canvas"] = Module.canvas;+ }+};++function BeginGlQueryTiming(calc_name, num_repetitions) {+ const gl = Module.canvas.getContext("webgl2");+ const query = gl.createQuery();+ Module.WEBGL_SHADER_CALC_METRICS = Module.WEBGL_SHADER_CALC_METRICS || {};+ Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)] = {+ query,+ repetitions: num_repetitions+ };+ Module.WEBGL_QUERY_TIMER_EXT = Module.WEBGL_QUERY_TIMER_EXT || gl.getExtension("EXT_disjoint_timer_query_webgl2");+ gl.beginQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, query);+}++function EndGlQueryTiming(calc_name) {+ const gl = Module.canvas.getContext("webgl2");+ gl.endQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)].query);+}++function JsWrapImageConverter() {+ if (!Module._imageConverter) {+ Module._imageConverter = (binaryPtr, binarySize, width, height, numChannels, makeDeepCopy, outputType) => {+ const imageData = new outputType(makeDeepCopy ? Module.HEAPU8.slice(binaryPtr, binaryPtr + binarySize).buffer : Module.HEAPU8.buffer, binaryPtr, width * height * numChannels);+ return {+ data: imageData,+ width,+ height+ };+ };+ }+}++function JsOnUint8ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnFloat32ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnWebGLTextureListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, timestamp_ms);+}++function JsOnUint8ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnFloat32ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnWebGLTextureVectorListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, false, timestamp_ms);+}++function JsWrapLoggingHelpers() {+ if (!Module["_decodeBase64"]) {+ Module["_decodeBase64"] = function(encoded_key_ptr) {+ const encodedStr = UTF8ToString(encoded_key_ptr);+ return atob(encodedStr);+ };+ }+}++function JsOnEmptyPacketListener(output_stream_name, timestamp) {+ Module._wrapEmptyPacketListenerOutput(output_stream_name, timestamp);+}++function JsOnVectorFinishedListener(output_stream_name, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, undefined, true, timestamp);+}++function JsOnSimpleListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), timestamp);+}++function JsOnVectorListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), false, timestamp);+}++function JsOnVectorListenerProto(output_stream_name, proto_ptr, proto_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(proto_ptr, proto_ptr + proto_size) : new Uint8Array(Module.HEAPU8.buffer, proto_ptr, proto_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, false, timestamp);+}++function JsWrapSimpleListeners() {+ if (!Module._wrapSimpleListenerOutput) {+ Module._wrapSimpleListenerOutput = (outputStreamName, ...args) => {+ if (Module.simpleListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.simpleListeners[streamName]) {+ Module.simpleListeners[streamName](...args);+ }+ }+ };+ }+ if (!Module._wrapEmptyPacketListenerOutput) {+ Module._wrapEmptyPacketListenerOutput = (outputStreamName, timestamp) => {+ if (Module.emptyPacketListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.emptyPacketListeners[streamName]) {+ Module.emptyPacketListeners[streamName](timestamp);+ }+ }+ };+ }+}++function JsOnSimpleListenerBinaryArray(output_stream_name, binary_ptr, binary_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(binary_ptr, binary_ptr + binary_size) : new Uint8Array(Module.HEAPU8.buffer, binary_ptr, binary_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, timestamp);+}++function mediapipe_import_external_texture(device_handle, source_handle) {+ const device = WebGPU.getJsObject(device_handle);+ const source = Emval.toValue(source_handle);+ const externalTexture = device.importExternalTexture({+ source+ });+ return Emval.toHandle(externalTexture);+}++function mediapipe_create_utility_canvas2d() {+ let canvas;+ if (typeof HTMLCanvasElement !== "undefined") {+ canvas = document.createElement("canvas");+ canvas.style.display = "none";+ } else {+ canvas = new OffscreenCanvas(0, 0);+ }+ return Emval.toHandle(canvas);+}++function GetAdapterArchitecture() {+ const device = Module["preinitializedWebGPUDevice"];+ const architecture = device.adapterInfo ? device.adapterInfo.architecture : "Unknown";+ return stringToNewUTF8(architecture);+}++function GetAdapterDescription() {+ const device = Module["preinitializedWebGPUDevice"];+ const description = device.adapterInfo ? device.adapterInfo.description : "Unknown";+ return stringToNewUTF8(description);+}++function GetAdapterDeviceName() {+ const device = Module["preinitializedWebGPUDevice"];+ const deviceName = device.adapterInfo ? device.adapterInfo.device : "Unknown";+ return stringToNewUTF8(deviceName);+}++function GetAdapterVendor() {+ const device = Module["preinitializedWebGPUDevice"];+ const vendor = device.adapterInfo ? device.adapterInfo.vendor : "Unknown";+ return stringToNewUTF8(vendor);+}++function __asyncjs__mediapipe_map_buffer_jspi(buffer_handle, data) {+ return Asyncify.handleAsync(async () => {+ const buffer = WebGPU.getJsObject(buffer_handle);+ if ("mapSync" in buffer) {+ buffer.mapSync(GPUMapMode.READ);+ } else {+ await buffer.mapAsync(GPUMapMode.READ);+ }+ const mapped = buffer.getMappedRange();+ HEAPU8.set(new Uint8Array(mapped), data);+ buffer.unmap();+ });+}++function hardware_concurrency() {+ var concurrency = 1;+ try {+ concurrency = self.navigator.hardwareConcurrency;+ } catch (e) {}+ return concurrency;+}++function UseBottomLeftGpuOrigin() {+ return (Module && Module.gpuOriginForWebTexturesIsBottomLeft);+}++function custom_emscripten_dbgn(str, len) {+ if (typeof (dbg) !== "undefined") {+ dbg(UTF8ToString(str, len));+ } else {+ if (typeof (custom_dbg) === "undefined") {+ function custom_dbg(text) {+ console.warn.apply(console, arguments);+ }+ }+ custom_dbg(UTF8ToString(str, len));+ }+}++function JsWrapErrorListenerInternal(code, message) {+ if (Module.errorListener) {+ const stringMessage = UTF8ToString(message);+ Module.errorListener(code, stringMessage);+ }+}++// Imports from the Wasm binary.+var _free, _malloc, _interactive_segmenter_create, _interactive_segmenter_set_image, _interactive_segmenter_segment, _interactive_segmenter_close, _wgpuDeviceAddRef, _addBoundTextureAsImageToStream, _attachImageListener, _attachImageVectorListener, _mediapipeLoggerGetEncodedApiKey, _registerModelResourcesGraphService, _bindTextureToStream, _addBoundTextureToStream, _addDoubleToInputStream, _addFloatToInputStream, _addBoolToInputStream, _addIntToInputStream, _addUintToInputStream, _addStringToInputStream, _addRawDataSpanToInputStream, _allocateBoolVector, _allocateFloatVector, _allocateDoubleVector, _allocateIntVector, _allocateUintVector, _allocateStringVector, _addBoolVectorEntry, _addFloatVectorEntry, _addDoubleVectorEntry, _addIntVectorEntry, _addUintVectorEntry, _addStringVectorEntry, _addBoolVectorToInputStream, _addFloatVectorToInputStream, _addDoubleVectorToInputStream, _addIntVectorToInputStream, _addUintVectorToInputStream, _addStringVectorToInputStream, _addFlatHashMapToInputStream, _addProtoToInputStream, _addEmptyPacketToInputStream, _addBoolToInputSidePacket, _addDoubleToInputSidePacket, _addFloatToInputSidePacket, _addIntToInputSidePacket, _addUintToInputSidePacket, _addStringToInputSidePacket, _addRawDataSpanToInputSidePacket, _addProtoToInputSidePacket, _addBoolVectorToInputSidePacket, _addDoubleVectorToInputSidePacket, _addFloatVectorToInputSidePacket, _addIntVectorToInputSidePacket, _addUintVectorToInputSidePacket, _addStringVectorToInputSidePacket, _attachBoolListener, _attachBoolVectorListener, _attachDoubleListener, _attachDoubleVectorListener, _attachFloatListener, _attachFloatVectorListener, _attachIntListener, _attachIntVectorListener, _attachUintListener, _attachUintVectorListener, _attachStringListener, _attachStringVectorListener, _attachProtoListener, _attachProtoVectorListener, _getGraphConfig, ___getTypeName, _emwgpuCreateBindGroup, _emwgpuCreateBindGroupLayout, _emwgpuCreateCommandBuffer, _emwgpuCreateCommandEncoder, _emwgpuCreateComputePassEncoder, _emwgpuCreateComputePipeline, _emwgpuCreateExternalTexture, _emwgpuCreatePipelineLayout, _emwgpuCreateQuerySet, _emwgpuCreateRenderBundle, _emwgpuCreateRenderBundleEncoder, _emwgpuCreateRenderPassEncoder, _emwgpuCreateRenderPipeline, _emwgpuCreateSampler, _emwgpuCreateSurface, _emwgpuCreateTexture, _emwgpuCreateTextureView, _emwgpuCreateAdapter, _emwgpuImportBuffer, _emwgpuCreateDevice, _emwgpuCreateQueue, _emwgpuCreateShaderModule, _emwgpuOnCreateComputePipelineCompleted, _emwgpuOnCreateRenderPipelineCompleted, _clearSubgraphs, _pushBinarySubgraph, _pushTextSubgraph, _changeBinaryGraph, _changeTextGraph, _processGl, _process, _bindTextureToCanvas, _requestShaderRefreshOnGraphChange, _waitUntilIdle, _closeGraph, _setAutoRenderToScreen, _emscripten_builtin_memalign, _memalign, __emscripten_tempret_set, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, dynCall_ji, dynCall_jii, dynCall_iiiijij, dynCall_iij, dynCall_iiiijj, dynCall_viijj, dynCall_viiijjj, dynCall_vij, dynCall_viiji, dynCall_viji, dynCall_iiiji, dynCall_jjj, dynCall_jiii, dynCall_viijii, dynCall_vijjj, dynCall_vj, dynCall_viij, dynCall_jiji, dynCall_iiiiij, dynCall_iiiiijj, dynCall_iiiiiijj, memory, _kVersionStampBuildChangelistStr, _kVersionStampCitcSnapshotStr, _kVersionStampCitcWorkspaceIdStr, _kVersionStampSourceUriStr, _kVersionStampBuildClientStr, _kVersionStampBuildClientMintStatusStr, _kVersionStampBuildCompilerStr, _kVersionStampBuildDateTimePstStr, _kVersionStampBuildDepotPathStr, _kVersionStampBuildIdStr, _kVersionStampBuildInfoStr, _kVersionStampBuildLabelStr, _kVersionStampBuildTargetStr, _kVersionStampBuildTimestampStr, _kVersionStampBuildToolStr, _kVersionStampG3BuildTargetStr, _kVersionStampVerifiableStr, _kVersionStampBuildFdoTypeStr, _kVersionStampBuildBaselineChangelistStr, _kVersionStampBuildLtoTypeStr, _kVersionStampBuildPropellerTypeStr, _kVersionStampBuildPghoTypeStr, _kVersionStampBuildFdoProfileChangelistStr, _kVersionStampBuildMemprofProfileChangelistStr, _kVersionStampBuildUsernameStr, _kVersionStampBuildHostnameStr, _kVersionStampBuildDirectoryStr, _kVersionStampBuildChangelistInt, _kVersionStampCitcSnapshotInt, _kVersionStampBuildClientMintStatusInt, _kVersionStampBuildTimestampInt, _kVersionStampVerifiableInt, _kVersionStampBuildCoverageEnabledInt, _kVersionStampBuildBaselineChangelistInt, _kVersionStampPrecookedTimestampStr, _kVersionStampPrecookedClientInfoStr, __indirect_function_table, _kVersionStampBuildHasHardeningProtobuf, wasmMemory, wasmTable;++function assignWasmExports(wasmExports) {+ _free = Module["_free"] = wasmExports["de"];+ _malloc = Module["_malloc"] = wasmExports["ee"];+ _interactive_segmenter_create = Module["_interactive_segmenter_create"] = wasmExports["fe"];+ _interactive_segmenter_set_image = Module["_interactive_segmenter_set_image"] = wasmExports["ge"];+ _interactive_segmenter_segment = Module["_interactive_segmenter_segment"] = wasmExports["he"];+ _interactive_segmenter_close = Module["_interactive_segmenter_close"] = wasmExports["ie"];+ _wgpuDeviceAddRef = wasmExports["je"];+ _addBoundTextureAsImageToStream = Module["_addBoundTextureAsImageToStream"] = wasmExports["ke"];+ _attachImageListener = Module["_attachImageListener"] = wasmExports["le"];+ _attachImageVectorListener = Module["_attachImageVectorListener"] = wasmExports["me"];+ _mediapipeLoggerGetEncodedApiKey = Module["_mediapipeLoggerGetEncodedApiKey"] = wasmExports["ne"];+ _registerModelResourcesGraphService = Module["_registerModelResourcesGraphService"] = wasmExports["oe"];+ _bindTextureToStream = Module["_bindTextureToStream"] = wasmExports["pe"];+ _addBoundTextureToStream = Module["_addBoundTextureToStream"] = wasmExports["qe"];+ _addDoubleToInputStream = Module["_addDoubleToInputStream"] = wasmExports["re"];+ _addFloatToInputStream = Module["_addFloatToInputStream"] = wasmExports["se"];+ _addBoolToInputStream = Module["_addBoolToInputStream"] = wasmExports["te"];+ _addIntToInputStream = Module["_addIntToInputStream"] = wasmExports["ue"];+ _addUintToInputStream = Module["_addUintToInputStream"] = wasmExports["ve"];+ _addStringToInputStream = Module["_addStringToInputStream"] = wasmExports["we"];+ _addRawDataSpanToInputStream = Module["_addRawDataSpanToInputStream"] = wasmExports["xe"];+ _allocateBoolVector = Module["_allocateBoolVector"] = wasmExports["ye"];+ _allocateFloatVector = Module["_allocateFloatVector"] = wasmExports["ze"];+ _allocateDoubleVector = Module["_allocateDoubleVector"] = wasmExports["Ae"];+ _allocateIntVector = Module["_allocateIntVector"] = wasmExports["Be"];+ _allocateUintVector = Module["_allocateUintVector"] = wasmExports["Ce"];+ _allocateStringVector = Module["_allocateStringVector"] = wasmExports["De"];+ _addBoolVectorEntry = Module["_addBoolVectorEntry"] = wasmExports["Ee"];+ _addFloatVectorEntry = Module["_addFloatVectorEntry"] = wasmExports["Fe"];+ _addDoubleVectorEntry = Module["_addDoubleVectorEntry"] = wasmExports["Ge"];+ _addIntVectorEntry = Module["_addIntVectorEntry"] = wasmExports["He"];+ _addUintVectorEntry = Module["_addUintVectorEntry"] = wasmExports["Ie"];+ _addStringVectorEntry = Module["_addStringVectorEntry"] = wasmExports["Je"];+ _addBoolVectorToInputStream = Module["_addBoolVectorToInputStream"] = wasmExports["Ke"];+ _addFloatVectorToInputStream = Module["_addFloatVectorToInputStream"] = wasmExports["Le"];+ _addDoubleVectorToInputStream = Module["_addDoubleVectorToInputStream"] = wasmExports["Me"];+ _addIntVectorToInputStream = Module["_addIntVectorToInputStream"] = wasmExports["Ne"];+ _addUintVectorToInputStream = Module["_addUintVectorToInputStream"] = wasmExports["Oe"];+ _addStringVectorToInputStream = Module["_addStringVectorToInputStream"] = wasmExports["Pe"];+ _addFlatHashMapToInputStream = Module["_addFlatHashMapToInputStream"] = wasmExports["Qe"];+ _addProtoToInputStream = Module["_addProtoToInputStream"] = wasmExports["Re"];+ _addEmptyPacketToInputStream = Module["_addEmptyPacketToInputStream"] = wasmExports["Se"];+ _addBoolToInputSidePacket = Module["_addBoolToInputSidePacket"] = wasmExports["Te"];+ _addDoubleToInputSidePacket = Module["_addDoubleToInputSidePacket"] = wasmExports["Ue"];+ _addFloatToInputSidePacket = Module["_addFloatToInputSidePacket"] = wasmExports["Ve"];+ _addIntToInputSidePacket = Module["_addIntToInputSidePacket"] = wasmExports["We"];+ _addUintToInputSidePacket = Module["_addUintToInputSidePacket"] = wasmExports["Xe"];+ _addStringToInputSidePacket = Module["_addStringToInputSidePacket"] = wasmExports["Ye"];+ _addRawDataSpanToInputSidePacket = Module["_addRawDataSpanToInputSidePacket"] = wasmExports["Ze"];+ _addProtoToInputSidePacket = Module["_addProtoToInputSidePacket"] = wasmExports["_e"];+ _addBoolVectorToInputSidePacket = Module["_addBoolVectorToInputSidePacket"] = wasmExports["$e"];+ _addDoubleVectorToInputSidePacket = Module["_addDoubleVectorToInputSidePacket"] = wasmExports["af"];+ _addFloatVectorToInputSidePacket = Module["_addFloatVectorToInputSidePacket"] = wasmExports["bf"];+ _addIntVectorToInputSidePacket = Module["_addIntVectorToInputSidePacket"] = wasmExports["cf"];+ _addUintVectorToInputSidePacket = Module["_addUintVectorToInputSidePacket"] = wasmExports["df"];+ _addStringVectorToInputSidePacket = Module["_addStringVectorToInputSidePacket"] = wasmExports["ef"];+ _attachBoolListener = Module["_attachBoolListener"] = wasmExports["ff"];+ _attachBoolVectorListener = Module["_attachBoolVectorListener"] = wasmExports["gf"];+ _attachDoubleListener = Module["_attachDoubleListener"] = wasmExports["hf"];+ _attachDoubleVectorListener = Module["_attachDoubleVectorListener"] = wasmExports["jf"];+ _attachFloatListener = Module["_attachFloatListener"] = wasmExports["kf"];+ _attachFloatVectorListener = Module["_attachFloatVectorListener"] = wasmExports["lf"];+ _attachIntListener = Module["_attachIntListener"] = wasmExports["mf"];+ _attachIntVectorListener = Module["_attachIntVectorListener"] = wasmExports["nf"];+ _attachUintListener = Module["_attachUintListener"] = wasmExports["of"];+ _attachUintVectorListener = Module["_attachUintVectorListener"] = wasmExports["pf"];+ _attachStringListener = Module["_attachStringListener"] = wasmExports["qf"];+ _attachStringVectorListener = Module["_attachStringVectorListener"] = wasmExports["rf"];+ _attachProtoListener = Module["_attachProtoListener"] = wasmExports["sf"];+ _attachProtoVectorListener = Module["_attachProtoVectorListener"] = wasmExports["tf"];+ _getGraphConfig = Module["_getGraphConfig"] = wasmExports["uf"];+ ___getTypeName = wasmExports["vf"];+ _emwgpuCreateBindGroup = wasmExports["wf"];+ _emwgpuCreateBindGroupLayout = wasmExports["xf"];+ _emwgpuCreateCommandBuffer = wasmExports["yf"];+ _emwgpuCreateCommandEncoder = wasmExports["zf"];+ _emwgpuCreateComputePassEncoder = wasmExports["Af"];+ _emwgpuCreateComputePipeline = wasmExports["Bf"];+ _emwgpuCreateExternalTexture = wasmExports["Cf"];+ _emwgpuCreatePipelineLayout = wasmExports["Df"];+ _emwgpuCreateQuerySet = wasmExports["Ef"];+ _emwgpuCreateRenderBundle = wasmExports["Ff"];+ _emwgpuCreateRenderBundleEncoder = wasmExports["Gf"];+ _emwgpuCreateRenderPassEncoder = wasmExports["Hf"];+ _emwgpuCreateRenderPipeline = wasmExports["If"];+ _emwgpuCreateSampler = wasmExports["Jf"];+ _emwgpuCreateSurface = wasmExports["Kf"];+ _emwgpuCreateTexture = wasmExports["Lf"];+ _emwgpuCreateTextureView = wasmExports["Mf"];+ _emwgpuCreateAdapter = wasmExports["Nf"];+ _emwgpuImportBuffer = wasmExports["Of"];+ _emwgpuCreateDevice = wasmExports["Pf"];+ _emwgpuCreateQueue = wasmExports["Qf"];+ _emwgpuCreateShaderModule = wasmExports["Rf"];+ _emwgpuOnCreateComputePipelineCompleted = wasmExports["Sf"];+ _emwgpuOnCreateRenderPipelineCompleted = wasmExports["Tf"];+ _clearSubgraphs = Module["_clearSubgraphs"] = wasmExports["Uf"];+ _pushBinarySubgraph = Module["_pushBinarySubgraph"] = wasmExports["Vf"];+ _pushTextSubgraph = Module["_pushTextSubgraph"] = wasmExports["Wf"];+ _changeBinaryGraph = Module["_changeBinaryGraph"] = wasmExports["Xf"];+ _changeTextGraph = Module["_changeTextGraph"] = wasmExports["Yf"];+ _processGl = Module["_processGl"] = wasmExports["Zf"];+ _process = Module["_process"] = wasmExports["_f"];+ _bindTextureToCanvas = Module["_bindTextureToCanvas"] = wasmExports["$f"];+ _requestShaderRefreshOnGraphChange = Module["_requestShaderRefreshOnGraphChange"] = wasmExports["ag"];+ _waitUntilIdle = Module["_waitUntilIdle"] = wasmExports["bg"];+ _closeGraph = Module["_closeGraph"] = wasmExports["cg"];+ _setAutoRenderToScreen = Module["_setAutoRenderToScreen"] = wasmExports["dg"];+ _emscripten_builtin_memalign = wasmExports["fg"];+ _memalign = wasmExports["gg"];+ __emscripten_tempret_set = wasmExports["hg"];+ __emscripten_stack_restore = wasmExports["ig"];+ __emscripten_stack_alloc = wasmExports["jg"];+ _emscripten_stack_get_current = wasmExports["kg"];+ dynCall_ji = wasmExports["dynCall_ji"];+ dynCall_jii = wasmExports["dynCall_jii"];+ dynCall_iiiijij = wasmExports["dynCall_iiiijij"];+ dynCall_iij = wasmExports["dynCall_iij"];+ dynCall_iiiijj = wasmExports["dynCall_iiiijj"];+ dynCall_viijj = wasmExports["dynCall_viijj"];+ dynCall_viiijjj = wasmExports["dynCall_viiijjj"];+ dynCall_vij = wasmExports["dynCall_vij"];+ dynCall_viiji = wasmExports["dynCall_viiji"];+ dynCall_viji = wasmExports["dynCall_viji"];+ dynCall_iiiji = wasmExports["dynCall_iiiji"];+ dynCall_jjj = wasmExports["dynCall_jjj"];+ dynCall_jiii = wasmExports["dynCall_jiii"];+ dynCall_viijii = wasmExports["dynCall_viijii"];+ dynCall_vijjj = wasmExports["dynCall_vijjj"];+ dynCall_vj = wasmExports["dynCall_vj"];+ dynCall_viij = wasmExports["dynCall_viij"];+ dynCall_jiji = wasmExports["dynCall_jiji"];+ dynCall_iiiiij = wasmExports["dynCall_iiiiij"];+ dynCall_iiiiijj = wasmExports["dynCall_iiiiijj"];+ dynCall_iiiiiijj = wasmExports["dynCall_iiiiiijj"];+ memory = wasmMemory = wasmExports["sd"];+ _kVersionStampBuildChangelistStr = Module["_kVersionStampBuildChangelistStr"] = wasmExports["ud"].value;+ _kVersionStampCitcSnapshotStr = Module["_kVersionStampCitcSnapshotStr"] = wasmExports["vd"].value;+ _kVersionStampCitcWorkspaceIdStr = Module["_kVersionStampCitcWorkspaceIdStr"] = wasmExports["wd"].value;+ _kVersionStampSourceUriStr = Module["_kVersionStampSourceUriStr"] = wasmExports["xd"].value;+ _kVersionStampBuildClientStr = Module["_kVersionStampBuildClientStr"] = wasmExports["yd"].value;+ _kVersionStampBuildClientMintStatusStr = Module["_kVersionStampBuildClientMintStatusStr"] = wasmExports["zd"].value;+ _kVersionStampBuildCompilerStr = Module["_kVersionStampBuildCompilerStr"] = wasmExports["Ad"].value;+ _kVersionStampBuildDateTimePstStr = Module["_kVersionStampBuildDateTimePstStr"] = wasmExports["Bd"].value;+ _kVersionStampBuildDepotPathStr = Module["_kVersionStampBuildDepotPathStr"] = wasmExports["Cd"].value;+ _kVersionStampBuildIdStr = Module["_kVersionStampBuildIdStr"] = wasmExports["Dd"].value;+ _kVersionStampBuildInfoStr = Module["_kVersionStampBuildInfoStr"] = wasmExports["Ed"].value;+ _kVersionStampBuildLabelStr = Module["_kVersionStampBuildLabelStr"] = wasmExports["Fd"].value;+ _kVersionStampBuildTargetStr = Module["_kVersionStampBuildTargetStr"] = wasmExports["Gd"].value;+ _kVersionStampBuildTimestampStr = Module["_kVersionStampBuildTimestampStr"] = wasmExports["Hd"].value;+ _kVersionStampBuildToolStr = Module["_kVersionStampBuildToolStr"] = wasmExports["Id"].value;+ _kVersionStampG3BuildTargetStr = Module["_kVersionStampG3BuildTargetStr"] = wasmExports["Jd"].value;+ _kVersionStampVerifiableStr = Module["_kVersionStampVerifiableStr"] = wasmExports["Kd"].value;+ _kVersionStampBuildFdoTypeStr = Module["_kVersionStampBuildFdoTypeStr"] = wasmExports["Ld"].value;+ _kVersionStampBuildBaselineChangelistStr = Module["_kVersionStampBuildBaselineChangelistStr"] = wasmExports["Md"].value;+ _kVersionStampBuildLtoTypeStr = Module["_kVersionStampBuildLtoTypeStr"] = wasmExports["Nd"].value;+ _kVersionStampBuildPropellerTypeStr = Module["_kVersionStampBuildPropellerTypeStr"] = wasmExports["Od"].value;+ _kVersionStampBuildPghoTypeStr = Module["_kVersionStampBuildPghoTypeStr"] = wasmExports["Pd"].value;+ _kVersionStampBuildFdoProfileChangelistStr = Module["_kVersionStampBuildFdoProfileChangelistStr"] = wasmExports["Qd"].value;+ _kVersionStampBuildMemprofProfileChangelistStr = Module["_kVersionStampBuildMemprofProfileChangelistStr"] = wasmExports["Rd"].value;+ _kVersionStampBuildUsernameStr = Module["_kVersionStampBuildUsernameStr"] = wasmExports["Sd"].value;+ _kVersionStampBuildHostnameStr = Module["_kVersionStampBuildHostnameStr"] = wasmExports["Td"].value;+ _kVersionStampBuildDirectoryStr = Module["_kVersionStampBuildDirectoryStr"] = wasmExports["Ud"].value;+ _kVersionStampBuildChangelistInt = Module["_kVersionStampBuildChangelistInt"] = wasmExports["Vd"].value;+ _kVersionStampCitcSnapshotInt = Module["_kVersionStampCitcSnapshotInt"] = wasmExports["Wd"].value;+ _kVersionStampBuildClientMintStatusInt = Module["_kVersionStampBuildClientMintStatusInt"] = wasmExports["Xd"].value;+ _kVersionStampBuildTimestampInt = Module["_kVersionStampBuildTimestampInt"] = wasmExports["Yd"].value;+ _kVersionStampVerifiableInt = Module["_kVersionStampVerifiableInt"] = wasmExports["Zd"].value;+ _kVersionStampBuildCoverageEnabledInt = Module["_kVersionStampBuildCoverageEnabledInt"] = wasmExports["_d"].value;+ _kVersionStampBuildBaselineChangelistInt = Module["_kVersionStampBuildBaselineChangelistInt"] = wasmExports["$d"].value;+ _kVersionStampPrecookedTimestampStr = Module["_kVersionStampPrecookedTimestampStr"] = wasmExports["ae"].value;+ _kVersionStampPrecookedClientInfoStr = Module["_kVersionStampPrecookedClientInfoStr"] = wasmExports["be"].value;+ __indirect_function_table = wasmTable = wasmExports["ce"];+ _kVersionStampBuildHasHardeningProtobuf = Module["_kVersionStampBuildHasHardeningProtobuf"] = wasmExports["eg"].value;+}++var wasmImports = {+ /** @export */ rd: BeginGlQueryTiming,+ /** @export */ qd: EndGlQueryTiming,+ /** @export */ pd: GetAdapterArchitecture,+ /** @export */ od: GetAdapterDescription,+ /** @export */ nd: GetAdapterDeviceName,+ /** @export */ md: GetAdapterVendor,+ /** @export */ ld: JsOnEmptyPacketListener,+ /** @export */ kd: JsOnFloat32ArrayImageListener,+ /** @export */ jd: JsOnFloat32ArrayImageVectorListener,+ /** @export */ ob: JsOnSimpleListenerBinaryArray,+ /** @export */ id: JsOnSimpleListenerBool,+ /** @export */ hd: JsOnSimpleListenerDouble,+ /** @export */ gd: JsOnSimpleListenerFloat,+ /** @export */ fd: JsOnSimpleListenerInt,+ /** @export */ ed: JsOnSimpleListenerString,+ /** @export */ dd: JsOnSimpleListenerUint,+ /** @export */ cd: JsOnUint8ArrayImageListener,+ /** @export */ bd: JsOnUint8ArrayImageVectorListener,+ /** @export */ R: JsOnVectorFinishedListener,+ /** @export */ ad: JsOnVectorListenerBool,+ /** @export */ $c: JsOnVectorListenerDouble,+ /** @export */ _c: JsOnVectorListenerFloat,+ /** @export */ Zc: JsOnVectorListenerInt,+ /** @export */ Yc: JsOnVectorListenerProto,+ /** @export */ Xc: JsOnVectorListenerString,+ /** @export */ Wc: JsOnVectorListenerUint,+ /** @export */ Vc: JsOnWebGLTextureListener,+ /** @export */ Uc: JsOnWebGLTextureVectorListener,+ /** @export */ Tc: JsWrapErrorListenerInternal,+ /** @export */ nb: JsWrapImageConverter,+ /** @export */ Sc: JsWrapLoggingHelpers,+ /** @export */ v: JsWrapSimpleListeners,+ /** @export */ mb: UseBottomLeftGpuOrigin,+ /** @export */ xb: __asyncjs__mediapipe_map_buffer_jspi,+ /** @export */ n: ___cxa_throw,+ /** @export */ Rc: ___syscall_dup,+ /** @export */ Qc: ___syscall_faccessat,+ /** @export */ E: ___syscall_fcntl64,+ /** @export */ Pc: ___syscall_fstat64,+ /** @export */ Mb: ___syscall_ftruncate64,+ /** @export */ Oc: ___syscall_getcwd,+ /** @export */ Nc: ___syscall_getdents64,+ /** @export */ Mc: ___syscall_getuid32,+ /** @export */ Lc: ___syscall_ioctl,+ /** @export */ Kc: ___syscall_lstat64,+ /** @export */ Jc: ___syscall_mkdirat,+ /** @export */ Ic: ___syscall_newfstatat,+ /** @export */ Sa: ___syscall_openat,+ /** @export */ Hc: ___syscall_readlinkat,+ /** @export */ Gc: ___syscall_rmdir,+ /** @export */ Fc: ___syscall_stat64,+ /** @export */ lb: ___syscall_unlinkat,+ /** @export */ Ec: ___syscall_utimensat,+ /** @export */ zc: __abort_js,+ /** @export */ Ib: __embind_register_bigint,+ /** @export */ yc: __embind_register_bool,+ /** @export */ xc: __embind_register_emval,+ /** @export */ jb: __embind_register_float,+ /** @export */ I: __embind_register_integer,+ /** @export */ r: __embind_register_memory_view,+ /** @export */ wc: __embind_register_std_string,+ /** @export */ Qa: __embind_register_std_wstring,+ /** @export */ vc: __embind_register_void,+ /** @export */ ba: __emval_create_invoker,+ /** @export */ q: __emval_decref,+ /** @export */ Pa: __emval_get_global,+ /** @export */ ib: __emval_get_property,+ /** @export */ la: __emval_incref,+ /** @export */ Oa: __emval_instanceof,+ /** @export */ aa: __emval_invoke,+ /** @export */ wa: __emval_new_cstring,+ /** @export */ $: __emval_run_destructors,+ /** @export */ hb: __emval_set_property,+ /** @export */ uc: __emval_typeof,+ /** @export */ Hb: __gmtime_js,+ /** @export */ Gb: __localtime_js,+ /** @export */ Fb: __mktime_js,+ /** @export */ Eb: __mmap_js,+ /** @export */ Db: __munmap_js,+ /** @export */ tc: __tzset_js,+ /** @export */ Lb: _clock_time_get,+ /** @export */ sc: custom_emscripten_dbgn,+ /** @export */ _: _emscripten_asm_const_int,+ /** @export */ gb: _emscripten_asm_const_ptr,+ /** @export */ Na: _emscripten_errn,+ /** @export */ rc: _emscripten_get_heap_max,+ /** @export */ y: _emscripten_get_now,+ /** @export */ T: _emscripten_has_asyncify,+ /** @export */ qc: _emscripten_outn,+ /** @export */ pc: _emscripten_pc_get_function,+ /** @export */ oc: _emscripten_resize_heap,+ /** @export */ fb: _emscripten_stack_snapshot,+ /** @export */ nc: _emscripten_stack_unwind_buffer,+ /** @export */ mc: _emscripten_webgl_create_context,+ /** @export */ lc: _emscripten_webgl_destroy_context,+ /** @export */ kc: _emscripten_webgl_get_context_attributes,+ /** @export */ ka: _emscripten_webgl_get_current_context,+ /** @export */ jc: _emscripten_webgl_make_context_current,+ /** @export */ Q: _emscripten_webgpu_get_device,+ /** @export */ ic: _emwgpuBufferDestroy,+ /** @export */ hc: _emwgpuBufferGetMappedRange,+ /** @export */ gc: _emwgpuBufferUnmap,+ /** @export */ u: _emwgpuDelete,+ /** @export */ fc: _emwgpuDeviceCreateBuffer,+ /** @export */ Cb: _emwgpuDeviceCreateComputePipelineAsync,+ /** @export */ Bb: _emwgpuDeviceCreateRenderPipelineAsync,+ /** @export */ ec: _emwgpuDeviceCreateShaderModule,+ /** @export */ dc: _emwgpuDeviceDestroy,+ /** @export */ cc: _emwgpuWaitAny,+ /** @export */ Dc: _environ_get,+ /** @export */ Cc: _environ_sizes_get,+ /** @export */ bc: _exit,+ /** @export */ ma: _fd_close,+ /** @export */ Kb: _fd_pread,+ /** @export */ kb: _fd_read,+ /** @export */ Jb: _fd_seek,+ /** @export */ Ra: _fd_write,+ /** @export */ b: _glActiveTexture,+ /** @export */ va: _glAttachShader,+ /** @export */ ac: _glBindAttribLocation,+ /** @export */ c: _glBindBuffer,+ /** @export */ eb: _glBindBufferBase,+ /** @export */ t: _glBindFramebuffer,+ /** @export */ a: _glBindTexture,+ /** @export */ m: _glBindVertexArray,+ /** @export */ db: _glBlendEquation,+ /** @export */ $b: _glBlendFunc,+ /** @export */ j: _glBufferData,+ /** @export */ P: _glClear,+ /** @export */ O: _glClearColor,+ /** @export */ fa: _glClientWaitSync,+ /** @export */ ja: _glColorMask,+ /** @export */ cb: _glCompileShader,+ /** @export */ bb: _glCreateProgram,+ /** @export */ Ma: _glCreateShader,+ /** @export */ p: _glDeleteBuffers,+ /** @export */ S: _glDeleteFramebuffers,+ /** @export */ h: _glDeleteProgram,+ /** @export */ ia: _glDeleteShader,+ /** @export */ ua: _glDeleteSync,+ /** @export */ D: _glDeleteTextures,+ /** @export */ A: _glDeleteVertexArrays,+ /** @export */ ab: _glDetachShader,+ /** @export */ H: _glDisable,+ /** @export */ o: _glDisableVertexAttribArray,+ /** @export */ i: _glDrawArrays,+ /** @export */ ha: _glDrawBuffers,+ /** @export */ _b: _glEnable,+ /** @export */ l: _glEnableVertexAttribArray,+ /** @export */ $a: _glFenceSync,+ /** @export */ ta: _glFinish,+ /** @export */ x: _glFlush,+ /** @export */ C: _glFramebufferTexture2D,+ /** @export */ _a: _glFramebufferTextureLayer,+ /** @export */ s: _glGenBuffers,+ /** @export */ Z: _glGenFramebuffers,+ /** @export */ G: _glGenTextures,+ /** @export */ B: _glGenVertexArrays,+ /** @export */ Za: _glGetAttribLocation,+ /** @export */ ga: _glGetError,+ /** @export */ Zb: _glGetFloatv,+ /** @export */ w: _glGetIntegerv,+ /** @export */ Yb: _glGetProgramiv,+ /** @export */ Xb: _glGetShaderInfoLog,+ /** @export */ Wb: _glGetShaderiv,+ /** @export */ N: _glGetString,+ /** @export */ Vb: _glGetUniformBlockIndex,+ /** @export */ d: _glGetUniformLocation,+ /** @export */ Ub: _glLineWidth,+ /** @export */ Ya: _glLinkProgram,+ /** @export */ sa: _glPixelStorei,+ /** @export */ ra: _glReadPixels,+ /** @export */ La: _glShaderSource,+ /** @export */ F: _glTexImage2D,+ /** @export */ qa: _glTexParameterf,+ /** @export */ Xa: _glTexParameterfv,+ /** @export */ f: _glTexParameteri,+ /** @export */ pa: _glTexStorage2D,+ /** @export */ Tb: _glTexStorage3D,+ /** @export */ Y: _glTexSubImage2D,+ /** @export */ Sb: _glTexSubImage3D,+ /** @export */ M: _glUniform1f,+ /** @export */ oa: _glUniform1fv,+ /** @export */ e: _glUniform1i,+ /** @export */ X: _glUniform2f,+ /** @export */ Rb: _glUniform2fv,+ /** @export */ Ka: _glUniform3f,+ /** @export */ Wa: _glUniform4f,+ /** @export */ W: _glUniform4fv,+ /** @export */ Qb: _glUniform4iv,+ /** @export */ Pb: _glUniformBlockBinding,+ /** @export */ Ob: _glUniformMatrix2fv,+ /** @export */ Nb: _glUniformMatrix3fv,+ /** @export */ Ja: _glUniformMatrix4fv,+ /** @export */ g: _glUseProgram,+ /** @export */ k: _glVertexAttribPointer,+ /** @export */ V: _glViewport,+ /** @export */ Ia: hardware_concurrency,+ /** @export */ Ab: mediapipe_create_utility_canvas2d,+ /** @export */ zb: _mediapipe_find_canvas_event_target,+ /** @export */ yb: mediapipe_import_external_texture,+ /** @export */ wb: _mediapipe_webgl_tex_image_drawable,+ /** @export */ Bc: _proc_exit,+ /** @export */ Ac: _random_get,+ /** @export */ Ha: _wgpuCommandEncoderBeginComputePass,+ /** @export */ Ga: _wgpuCommandEncoderBeginRenderPass,+ /** @export */ vb: _wgpuCommandEncoderCopyBufferToTexture,+ /** @export */ ub: _wgpuCommandEncoderCopyTextureToBuffer,+ /** @export */ tb: _wgpuCommandEncoderCopyTextureToTexture,+ /** @export */ L: _wgpuCommandEncoderFinish,+ /** @export */ Fa: _wgpuComputePassEncoderDispatchWorkgroups,+ /** @export */ Ea: _wgpuComputePassEncoderEnd,+ /** @export */ Da: _wgpuComputePassEncoderSetBindGroup,+ /** @export */ Ca: _wgpuComputePassEncoderSetPipeline,+ /** @export */ Ba: _wgpuComputePipelineGetBindGroupLayout,+ /** @export */ ea: _wgpuDeviceCreateBindGroup,+ /** @export */ sb: _wgpuDeviceCreateBindGroupLayout,+ /** @export */ K: _wgpuDeviceCreateCommandEncoder,+ /** @export */ rb: _wgpuDeviceCreateComputePipeline,+ /** @export */ qb: _wgpuDeviceCreatePipelineLayout,+ /** @export */ Va: _wgpuDeviceCreateRenderPipeline,+ /** @export */ U: _wgpuDeviceCreateSampler,+ /** @export */ da: _wgpuDeviceCreateTexture,+ /** @export */ J: _wgpuQueueSubmit,+ /** @export */ na: _wgpuQueueWriteBuffer,+ /** @export */ pb: _wgpuQueueWriteTexture,+ /** @export */ Aa: _wgpuRenderPassEncoderDraw,+ /** @export */ za: _wgpuRenderPassEncoderEnd,+ /** @export */ ya: _wgpuRenderPassEncoderSetBindGroup,+ /** @export */ xa: _wgpuRenderPassEncoderSetPipeline,+ /** @export */ Ua: _wgpuRenderPipelineGetBindGroupLayout,+ /** @export */ z: _wgpuTextureCreateView,+ /** @export */ Ta: _wgpuTextureDestroy,+ /** @export */ ca: _wgpuTextureGetFormat+};++// include: postamble.js+// === Auto-generated postamble setup entry stuff ===+async function run() {+ preRun();+ if (runDependencies) {+ await resolveRunDependencies();+ }+ var setStatus = Module["setStatus"];+ if (setStatus) {+ setStatus("Running...");+ // Yield to the event loop to allow the browser to paint "Running..."+ await new Promise(resolve => setTimeout(resolve, 1));+ // Then we want to clear the status text, but only after the rest of this function runs.+ setTimeout(setStatus, 1, "");+ }+ if (ABORT) return;+ initRuntime();+ Module["onRuntimeInitialized"]?.();+ postRun();+}++var wasmExports;++// In modularize mode the generated code is within a factory function so we+// can use await here (since it's not top-level-await).+wasmExports = await createWasm();++await run();+++ return Module;+ };+})();++// Export using a UMD style export, or ES6 exports if selected+if (typeof exports === 'object' && typeof module === 'object') {+ module.exports = ModuleFactory;+ // This default export looks redundant, but it allows TS to import this+ // commonjs style module.+ module.exports.default = ModuleFactory;+} else if (typeof define === 'function' && define['amd'])+ define([], () => ModuleFactory);+diff --git a/src/assets/mediapipeVision/vision_wasm_internal.wasm b/src/assets/mediapipeVision/vision_wasm_internal.wasmindex 1fcd4f7..d14a0c1 100644Binary files a/src/assets/mediapipeVision/vision_wasm_internal.wasm and b/src/assets/mediapipeVision/vision_wasm_internal.wasm differdiff --git a/src/manifest.json b/src/manifest.jsonindex 78f979c..5579ba4 100755--- a/src/manifest.json+++ b/src/manifest.json@@ -3,7 +3,7 @@"name": "__MSG_extName__","description": "__MSG_extDesc__","default_locale": "en",- "version": "4.7.1",+ "version": "4.7.2","background": {"service_worker": "background.bundle.js"},diff --git a/src/pages/Background/alarms/handleAlarm.js b/src/pages/Background/alarms/handleAlarm.jsindex 4940e4e..7abd307 100644--- a/src/pages/Background/alarms/handleAlarm.js+++ b/src/pages/Background/alarms/handleAlarm.js@@ -245,11 +245,14 @@ export const handleAlarm = async (alarm) => {}if (alarm.name === "recording-alarm") {- const { recording } = await chrome.storage.local.get(["recording"]);+ const { recording, isSubscribed, offscreen } =+ await chrome.storage.local.get(["recording", "isSubscribed", "offscreen"]);if (recording) {diagEvent("alarm-fired");- stopRecording();+ // Cloud or offscreen: a BG stopRecording() closes the recorder doc mid-finalize.+ // The recorder stops itself via video-ready, same as a toolbar stop.+ if (!isSubscribed && !offscreen) stopRecording();sendMessageRecord({ type: "stop-recording-tab" });await handleTabMessaging(null);}diff --git a/src/pages/Background/listeners/onInstalledListener.js b/src/pages/Background/listeners/onInstalledListener.jsindex 9f85ad1..218c8d2 100644--- a/src/pages/Background/listeners/onInstalledListener.js+++ b/src/pages/Background/listeners/onInstalledListener.js@@ -8,6 +8,9 @@ export const onInstalledListener = () => {chrome.runtime.onInstalled.addListener(async (details) => {const version = chrome.runtime.getManifest().version;+ // The floating window does not survive a reload, so neither does its flag.+ chrome.storage.local.remove(["cameraPipTab", "prompterScriptTab"]).catch(() => {});+if (details.reason === "install") {chrome.storage.local.clear();diff --git a/src/pages/Background/listeners/onStartupListener.js b/src/pages/Background/listeners/onStartupListener.jsindex e347802..6459ef0 100644--- a/src/pages/Background/listeners/onStartupListener.js+++ b/src/pages/Background/listeners/onStartupListener.js@@ -7,6 +7,7 @@ const CLOUD_FEATURES_ENABLED =// For some reason without this the service worker doesn't always workexport const onStartupListener = async () => {chrome.runtime.onStartup.addListener(() => {+ chrome.storage.local.remove(["cameraPipTab", "prompterScriptTab"]).catch(() => {});if (globalThis.SCREENITY_VERBOSE_LOGS) {console.log("Service worker started up successfully.");}diff --git a/src/pages/Background/listeners/onTabRemovedListener.js b/src/pages/Background/listeners/onTabRemovedListener.jsindex dd09031..e655e42 100644--- a/src/pages/Background/listeners/onTabRemovedListener.js+++ b/src/pages/Background/listeners/onTabRemovedListener.js@@ -5,8 +5,29 @@ import { isRecordingStartInFlight } from "../recording/startRecording";import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";import { forgetRetained } from "../recording/recordingRetention";+// The floating camera window dies with its tab, whether the tab closes,+// navigates or is discarded, and a crashed page never gets to clear the flag.+const clearCameraPipTab = async (tabId) => {+ try {+ const stored = await chrome.storage.local.get([+ "cameraPipTab",+ "prompterScriptTab",+ ]);+ const stale = ["cameraPipTab", "prompterScriptTab"].filter(+ (key) => stored[key] === tabId+ );+ if (stale.length) await chrome.storage.local.remove(stale);+ } catch {}+};+export const onTabRemovedListener = () => {+ chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {+ if (changeInfo.status === "loading" || changeInfo.discarded) {+ clearCameraPipTab(tabId);+ }+ });chrome.tabs.onRemoved.addListener(async (tabId) => {+ clearCameraPipTab(tabId);// Drops the protection only. The bytes stay until the next cleanup, so// closing a tab never destroys a recording on its own.forgetRetained(tabId).catch(() => {});diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.jsindex 41e1861..af9fbdf 100644--- a/src/pages/Background/recording/recordingHelpers.js+++ b/src/pages/Background/recording/recordingHelpers.js@@ -304,27 +304,36 @@ export const handleRecordingError = async (request) => {type: "recording-error",error: request?.error || null,why: request?.why || null,- }).then(() => {- const candidateTabs = [activeTab, recordingUiTabId, tabRecordedID].filter(- (id, idx, arr) => Number.isInteger(id) && arr.indexOf(id) === idx,- );- candidateTabs.forEach((id) => {- sendMessageTab(id, { type: "stop-pending" }).catch(() => {});- });- // refocus only when no editor is open- if (!sandboxAlive) {- focusTab(activeTab);- }- if (request.error === "stream-error") {- // `why` carries the server's reason word, which is what picks the- // lapsed-subscription copy from the never-subscribed one.- sendMessageTab(activeTab, {- type: "stream-error",- errorCode,- why: request?.why || null,+ })+ // The recorder that reported this is usually being torn down, so the relay+ // can reject; the user must still hear about it.+ .catch((err) => {+ diagEvent("warning", {+ note: "recording-error relay undelivered",+ err: String(err).slice(0, 80),});- }- });+ })+ .then(() => {+ const candidateTabs = [activeTab, recordingUiTabId, tabRecordedID].filter(+ (id, idx, arr) => Number.isInteger(id) && arr.indexOf(id) === idx,+ );+ candidateTabs.forEach((id) => {+ sendMessageTab(id, { type: "stop-pending" }).catch(() => {});+ });+ // refocus only when no editor is open+ if (!sandboxAlive) {+ focusTab(activeTab);+ }+ if (request.error === "stream-error") {+ // `why` carries the server's reason word, which is what picks the+ // lapsed-subscription copy from the never-subscribed one.+ sendMessageTab(activeTab, {+ type: "stream-error",+ errorCode,+ why: request?.why || null,+ });+ }+ });const { recordingTab } = await chrome.storage.local.get(["recordingTab"]);if (recordingTab) {diff --git a/src/pages/Background/tabManagement/resetActiveTab.js b/src/pages/Background/tabManagement/resetActiveTab.jsindex 6725f95..a18e2b6 100644--- a/src/pages/Background/tabManagement/resetActiveTab.js+++ b/src/pages/Background/tabManagement/resetActiveTab.js@@ -1,6 +1,8 @@import { focusTab } from "./focusTab";import { sendMessageTab } from "./sendMessageTab";import { startRecording } from "../recording/startRecording";+import { waitForPrompterGate } from "./waitForPrompterGate";+import { waitForPopupHidden } from "./waitForPopupHidden";import { getCurrentTab } from "./getCurrentTab";import { traceStep } from "../../utils/startFlowTrace";import { perfMark, perfSpan } from "../../utils/perfMarks";@@ -15,11 +17,14 @@ export const restartActiveTab = async (message = {}) => {const currentTab = await getCurrentTab();const targetTabId = preferredTabId || currentTab?.id || null;if (targetTabId) {+ const sentAt = Date.now();sendMessageTab(targetTabId, { type: "ready-to-record" });const { countdown } = await chrome.storage.local.get(["countdown"]);if (!countdown) {+ await waitForPrompterGate(targetTabId, sentAt);+ await waitForPopupHidden(sentAt);startRecording("restartActiveTab-no-countdown");}} else {@@ -116,11 +121,14 @@ export const resetActiveTab = async (forceRestart = false, message = {}) => {if (targetTabId) {perfMark("BG.resetActiveTab ready-to-record.sent", { targetTabId });+ const sentAt = Date.now();sendMessageTab(targetTabId, { type: "ready-to-record" }).catch(() => {});const { countdown } = await chrome.storage.local.get(["countdown"]);if (!countdown) {+ await waitForPrompterGate(targetTabId, sentAt);+ await waitForPopupHidden(sentAt);startRecording("resetActiveTab-no-countdown", { storedCountdown: countdown });}} else {diff --git a/src/pages/Background/tabManagement/setSurface.js b/src/pages/Background/tabManagement/setSurface.jsindex 73ccd7c..694c7f4 100644--- a/src/pages/Background/tabManagement/setSurface.js+++ b/src/pages/Background/tabManagement/setSurface.js@@ -12,15 +12,16 @@ export const setSurface = async (request) => {} catch (err) {console.warn("[Screenity][BG] setSurface auth refresh failed:", err);}- const { activeTab, isSubscribed, instantMode, recordingType } =+ const { activeTab, isSubscribed, instantMode, recordingType, cameraPipTab } =await chrome.storage.local.get(["activeTab","isSubscribed","instantMode","recordingType",+ "cameraPipTab",]);- sendMessageTab(activeTab, {+ const message = {type: "set-surface",surface: request.surface,// A region/tab capture still reports displaySurface "monitor". Without this@@ -28,5 +29,11 @@ export const setSurface = async (request) => {recordingType: recordingType || null,subscribed: result ? Boolean(result.subscribed) : Boolean(isSubscribed),instantMode: result ? Boolean(result.instantMode) : Boolean(instantMode),- });+ };+ sendMessageTab(activeTab, message);+ // The floating camera belongs to the tab that opened it, which may no longer+ // be the active one; it decides whether the new capture still fits.+ if (cameraPipTab != null && cameraPipTab !== activeTab) {+ sendMessageTab(cameraPipTab, message)?.catch?.(() => {});+ }};diff --git a/src/pages/Background/tabManagement/waitForPopupHidden.js b/src/pages/Background/tabManagement/waitForPopupHidden.jsnew file mode 100644index 0000000..9123834--- /dev/null+++ b/src/pages/Background/tabManagement/waitForPopupHidden.js@@ -0,0 +1,23 @@+// With the countdown off, capture is already live when ready-to-record is sent, so the+// popup would land in the first frames. The page marks the frame after hiding it; wait+// for that, up to the timeout (a hidden tab never paints).+export const waitForPopupHidden = async (sentAt, timeoutMs = 400) => {+ try {+ const { popupHiddenAt } = await chrome.storage.local.get(["popupHiddenAt"]);+ if (popupHiddenAt >= sentAt) return;+ await new Promise((resolve) => {+ const finish = () => {+ clearTimeout(timer);+ chrome.storage.onChanged.removeListener(onChanged);+ resolve();+ };+ const onChanged = (changes, area) => {+ if (area === "local" && changes.popupHiddenAt?.newValue >= sentAt) {+ finish();+ }+ };+ const timer = setTimeout(finish, timeoutMs);+ chrome.storage.onChanged.addListener(onChanged);+ });+ } catch {}+};diff --git a/src/pages/Background/tabManagement/waitForPrompterGate.js b/src/pages/Background/tabManagement/waitForPrompterGate.jsnew file mode 100644index 0000000..a69cc87--- /dev/null+++ b/src/pages/Background/tabManagement/waitForPrompterGate.js@@ -0,0 +1,25 @@+// With the countdown off the recorder starts as soon as ready-to-record is sent, so a+// full-screen capture could record the floating script before the page closes it. The+// page marks the gate done; this waits for that mark, up to a second.+export const waitForPrompterGate = async (tabId, sentAt, timeoutMs = 1000) => {+ try {+ const { prompterScriptTab, prompterGateDone } =+ await chrome.storage.local.get(["prompterScriptTab", "prompterGateDone"]);+ if (prompterScriptTab == null || prompterScriptTab !== tabId) return;+ if (prompterGateDone >= sentAt) return;+ await new Promise((resolve) => {+ const finish = () => {+ clearTimeout(timer);+ chrome.storage.onChanged.removeListener(onChanged);+ resolve();+ };+ const onChanged = (changes, area) => {+ if (area === "local" && changes.prompterGateDone?.newValue >= sentAt) {+ finish();+ }+ };+ const timer = setTimeout(finish, timeoutMs);+ chrome.storage.onChanged.addListener(onChanged);+ });+ } catch {}+};diff --git a/src/pages/Camera/components/Background.js b/src/pages/Camera/components/Background.jsindex 2777833..799baf8 100644--- a/src/pages/Camera/components/Background.js+++ b/src/pages/Camera/components/Background.js@@ -70,9 +70,11 @@ const Background = () => {bottomCanvasContextRef,);+ const video = videoRef.current;+ const hasVideoSize = video && video.videoWidth > 0 && video.videoHeight > 0;resizeCanvases(- effectRef.current.width,- effectRef.current.height,+ hasVideoSize ? video.videoWidth : effectRef.current.width,+ hasVideoSize ? video.videoHeight : effectRef.current.height,true,effectRef.current,canvasRef,@@ -90,6 +92,7 @@ const Background = () => {let consecutiveErrors = 0;let lastSuccessAt = Date.now();let recreatingSegmenter = false;+ let lastFrameCount = -1;// Watchdog: if the segmenter goes silent (returns null masks for// 5s+ while video is delivering frames), the GPU context likely@@ -146,11 +149,23 @@ const Background = () => {const segmenter = segmenterRef.current;if (video && video.readyState >= 2 && segmenter && video.videoWidth > 0) {+ // rAF outruns the camera; skip frames already drawn.+ const frameCount = video.getVideoPlaybackQuality?.().totalVideoFrames;+ if (frameCount !== undefined) {+ if (frameCount === lastFrameCount) {+ animFrameId = requestAnimationFrame(tick);+ return;+ }+ lastFrameCount = frameCount;+ }const result = segmentFromVideo(video, segmenter);- if (result && result.categoryMask) {+ if (result && result.confidenceMask) {consecutiveErrors = 0;lastSuccessAt = Date.now();+ if (bottomCanvasRef.current) {+ bottomCanvasRef.current.style.opacity = blurRef.current ? "0" : "1";+ }if (blurRef.current) {renderBlurFromVideo(video, result, canvasRef);} else if (effectRef.current) {@@ -236,6 +251,7 @@ const Background = () => {transform: "translate(-50%, -50%)",width: "100%",height: "100%",+ objectFit: "cover",zIndex: 999999,opacity: backgroundEffects ? 1 : 0,backgroundColor: "transparent",diff --git a/src/pages/Camera/utils/backgroundUtils.js b/src/pages/Camera/utils/backgroundUtils.jsindex 50e6e2f..042453f 100644--- a/src/pages/Camera/utils/backgroundUtils.js+++ b/src/pages/Camera/utils/backgroundUtils.js@@ -45,15 +45,16 @@ function getReusableCanvases() {}let _maskImageDataCache = null;-let _maskImageDataCacheSize = 0;function getOrCreateMaskImageData(ctx, width, height) {- const size = width * height;- if (_maskImageDataCache && _maskImageDataCacheSize === size) {+ if (+ _maskImageDataCache &&+ _maskImageDataCache.width === width &&+ _maskImageDataCache.height === height+ ) {return _maskImageDataCache;}_maskImageDataCache = ctx.createImageData(width, height);- _maskImageDataCacheSize = size;return _maskImageDataCache;}@@ -76,8 +77,8 @@ const tryCreateSegmenter = async (vision, delegate) => {modelAssetPath: "./assets/mediapipeVision/selfie_segmenter.tflite",delegate,},- outputCategoryMask: true,- outputConfidenceMasks: false,+ outputCategoryMask: false,+ outputConfidenceMasks: true,runningMode: "VIDEO",});};@@ -146,20 +147,55 @@ export const loadSegmentationModel = async () => {}};-// segmentForVideo's callback fires synchronously, so the result can be returned directly.+// The model runs at 256px; a full-res input only enlarges the slow mask readback.+const SEGMENT_INPUT_WIDTH = 256;+let _segInputCanvas = null;+let _segInputCtx = null;++// The mask is only valid inside the callback, so copy it out there.+let _maskCopy = null;+export const segmentFromVideo = (videoElement, segmenter) => {if (!videoElement || !segmenter) return null;if (videoElement.readyState < 2 || videoElement.videoWidth === 0) return null;try {+ const vw = videoElement.videoWidth;+ const vh = videoElement.videoHeight;+ const inW = Math.min(vw, SEGMENT_INPUT_WIDTH);+ const inH = Math.max(1, Math.round((inW * vh) / vw));++ if (!_segInputCanvas) {+ _segInputCanvas = document.createElement("canvas");+ _segInputCtx = _segInputCanvas.getContext("2d");+ }+ if (_segInputCanvas.width !== inW || _segInputCanvas.height !== inH) {+ _segInputCanvas.width = inW;+ _segInputCanvas.height = inH;+ }+ _segInputCtx.drawImage(videoElement, 0, 0, inW, inH);+const timestampMs = performance.now();let result = null;- segmenter.segmentForVideo(videoElement, timestampMs, (r) => {- result = r;+ segmenter.segmentForVideo(_segInputCanvas, timestampMs, (r) => {+ const mask = r && r.confidenceMasks && r.confidenceMasks[0];+ if (!mask) return;+ const src = mask.getAsFloat32Array();+ if (!_maskCopy || _maskCopy.length !== src.length) {+ _maskCopy = new Float32Array(src.length);+ }+ _maskCopy.set(src);+ const copy = _maskCopy;+ result = {+ confidenceMask: {+ width: mask.width,+ height: mask.height,+ data: copy,+ },+ };});- if (!result || !result.categoryMask) return null;return result;} catch (error) {console.error("Error during segmentation:", error);@@ -167,9 +203,18 @@ export const segmentFromVideo = (videoElement, segmenter) => {}};-function buildSmoothedMask(segmentationResult, edgeBlurAmount, personOpaque) {- const mask = segmentationResult.categoryMask;- const maskData = mask.getAsUint8Array();+// Confidence below LOW is background, above HIGH is person; the ramp softens+// the model's blobby falloff.+const MASK_EDGE_LOW = 0.3;+const MASK_EDGE_HIGH = 0.7;+// Weight of the current frame; the rest is the previous one, which stops edge shimmer.+const MASK_TEMPORAL_WEIGHT = 0.6;++let _prevAlpha = null;++function buildSmoothedMask(segmentationResult, edgeBlurAmount, personOpaque, videoWidth) {+ const mask = segmentationResult.confidenceMask;+ const conf = mask.data;const maskW = mask.width;const maskH = mask.height;@@ -183,28 +228,33 @@ function buildSmoothedMask(segmentationResult, edgeBlurAmount, personOpaque) {}const maskImageData = getOrCreateMaskImageData(maskCtx, maskW, maskH);- const maskPixels = maskImageData.data;-- for (let i = 0; i < maskData.length; i++) {- const offset = i * 4;- const isPerson = maskData[i] === 1;- if (personOpaque) {- maskPixels[offset] = 255;- maskPixels[offset + 1] = 255;- maskPixels[offset + 2] = 255;- maskPixels[offset + 3] = isPerson ? 255 : 0;- } else {- // For destination-out masking.- maskPixels[offset] = 0;- maskPixels[offset + 1] = 0;- maskPixels[offset + 2] = 0;- maskPixels[offset + 3] = isPerson ? 0 : 255;- }+ const maskPixels = new Uint32Array(maskImageData.data.buffer);++ if (!_prevAlpha || _prevAlpha.length !== conf.length) {+ _prevAlpha = new Float32Array(conf.length);+ _prevAlpha.set(conf);+ }++ const range = MASK_EDGE_HIGH - MASK_EDGE_LOW;+ for (let i = 0; i < conf.length; i++) {+ let t = (conf[i] - MASK_EDGE_LOW) / range;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ const target = t * t * (3 - 2 * t);+ const alpha =+ _prevAlpha[i] + (target - _prevAlpha[i]) * MASK_TEMPORAL_WEIGHT;+ _prevAlpha[i] = alpha;+ const a = Math.round(alpha * 255);+ // Little-endian RGBA: white for person-opaque, black for destination-out.+ maskPixels[i] = personOpaque+ ? ((a << 24) | 0x00ffffff) >>> 0+ : (((255 - a) << 24) >>> 0);}maskCtx.putImageData(maskImageData, 0, 0);smoothMaskCtx.clearRect(0, 0, maskW, maskH);- smoothMaskCtx.filter = `blur(${edgeBlurAmount}px)`;+ // Edge blur is tuned in video pixels; the mask is smaller than the video.+ const edgePx = (edgeBlurAmount * maskW) / videoWidth;+ smoothMaskCtx.filter = `blur(${edgePx}px)`;smoothMaskCtx.drawImage(maskCanvas, 0, 0);smoothMaskCtx.filter = "none";@@ -216,7 +266,7 @@ export const renderBlurFromVideo = (videoElement, segmentationResult, canvasRef)try {const backgroundBlurAmount = 16;- const edgeBlurAmount = 8;+ const edgeBlurAmount = 3;const vw = videoElement.videoWidth;const vh = videoElement.videoHeight;@@ -238,7 +288,7 @@ export const renderBlurFromVideo = (videoElement, segmentationResult, canvasRef)blurCtx.filter = "none";const { smoothMaskCanvas, maskW, maskH } =- buildSmoothedMask(segmentationResult, edgeBlurAmount, true);+ buildSmoothedMask(segmentationResult, edgeBlurAmount, true, vw);const ratio = vw / vh;const outW = Math.round(window.innerHeight * ratio);@@ -282,7 +332,7 @@ export const renderPersonCutoutFromVideo = (if (!videoElement || !segmentationResult || !canvasRef.current) return false;try {- const edgeBlurAmount = 4;+ const edgeBlurAmount = 2;const vw = videoElement.videoWidth;const vh = videoElement.videoHeight;@@ -297,11 +347,18 @@ export const renderPersonCutoutFromVideo = (frameCtx.drawImage(videoElement, 0, 0);const { smoothMaskCanvas, maskW, maskH } =- buildSmoothedMask(segmentationResult, edgeBlurAmount, true);+ buildSmoothedMask(segmentationResult, edgeBlurAmount, true, vw);const canvas = canvasRef.current;const ctx = canvasContextRef.current;+ const outW = Math.round((window.innerHeight * vw) / vh);+ const outH = window.innerHeight;+ if (canvas.width !== outW || canvas.height !== outH) {+ canvas.width = outW;+ canvas.height = outH;+ }+if (personCanvas.width !== canvas.width || personCanvas.height !== canvas.height) {personCanvas.width = canvas.width;personCanvas.height = canvas.height;diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex b524647..87ee8ea 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -184,6 +184,7 @@ const deferFinalizeHostAllowed = () =>(!IS_IFRAME_CONTEXT &&typeof window !== "undefined" &&window.SCREENITY_DEFER_FINALIZE_ON_TAB === true);+const LOCAL_CHUNK_WRITE_TIMEOUT_MS = 10000;const SCREEN_CHUNK_MEMORY_WINDOW = 8;const CAMERA_CHUNK_MEMORY_WINDOW = 8;const AUDIO_CHUNK_MEMORY_WINDOW = 8;@@ -402,6 +403,7 @@ const CloudRecorder = () => {const isRestarting = useRef(false);const isFinishing = useRef(false);+ const stopPromiseRef = useRef(null);// Re-entry guard for setMic()'s lazy acquire branch (see Recorder.jsx).const isLazyAcquiringMic = useRef(false);// Latest mic-toggle intent so a mid-acquire toggle-off is honored.@@ -1340,7 +1342,7 @@ const CloudRecorder = () => {d.visibility?.changes ?? "?"} q=${d.peakEncodeQueueSize?.video ?? "?"} drop=${d.droppedForBackpressure?.video ?? "?"- } n=${name} m=${message}`,+ } dec=${String(d.decision || "?").slice(0, 45)} n=${name} m=${message}`,});} catch {}};@@ -5069,7 +5071,17 @@ const CloudRecorder = () => {// Pre-flight OPFS quota; otherwise we start and checkMaxMemory// stops us within ~1s of the first chunk.try {- const { quota = 0, usage = 0 } = await navigator.storage.estimate();+ // Bounded so a hung estimate can't wedge the start.+ let estimateTimer = null;+ const { quota = 0, usage = 0 } = await Promise.race([+ navigator.storage.estimate(),+ new Promise((_, reject) => {+ estimateTimer = setTimeout(+ () => reject(new Error("storage-estimate-timeout")),+ 5000,+ );+ }),+ ]).finally(() => clearTimeout(estimateTimer));const headroom = Math.max(0, quota - usage);const minQuota = 25 * 1024 * 1024;if (quota > 0 && quota < minQuota) {@@ -5523,20 +5535,33 @@ const CloudRecorder = () => {index.current++;const writeStartedAt = performance.now();- await chunksStore- .setItem(`chunk_${chunkIndex}`, {- index: chunkIndex,- chunk: blob,- timestamp,- })- .catch((err) => {- fatalErrorRef.current = true;- sendRecordingError(- "Could not buffer recording data locally (IndexedDB blocked)."- );- sendStopRecording();- throw err;+ let localWriteOk = true;+ let localWriteTimer = null;+ try {+ await Promise.race([+ chunksStore.setItem(`chunk_${chunkIndex}`, {+ index: chunkIndex,+ chunk: blob,+ timestamp,+ }),+ new Promise((_, reject) => {+ localWriteTimer = setTimeout(+ () => reject(new Error("local-chunk-write-timeout")),+ LOCAL_CHUNK_WRITE_TIMEOUT_MS+ );+ }),+ ]);+ } catch (err) {+ localWriteOk = false;+ console.warn("Failed to persist screen chunk locally:", err);+ void emitUploadTelemetry("upload_local_backup_degraded", {+ backupType: "screen",+ reason: "screen-idb-write-failed",+ error: err?.message || String(err),});+ } finally {+ clearTimeout(localWriteTimer);+ }const writeMs = performance.now() - writeStartedAt;const writeStats = localWriteStatsRef.current;writeStats.count += 1;@@ -5544,13 +5569,15 @@ const CloudRecorder = () => {if (writeMs > writeStats.maxMs) writeStats.maxMs = writeMs;if (writeMs >= 1000) writeStats.slowCount += 1;- patchTrackState("screen", {- durableChunkCount: chunkIndex + 1,- lastPersistedChunkIndex: chunkIndex,- lastPersistedAt: timestamp,- });+ if (localWriteOk) {+ patchTrackState("screen", {+ durableChunkCount: chunkIndex + 1,+ lastPersistedChunkIndex: chunkIndex,+ lastPersistedAt: timestamp,+ });- requestSessionPersist({ lastChunkIndex: chunkIndex });+ requestSessionPersist({ lastChunkIndex: chunkIndex });+ }if (uploadersInitialized.current && screenUploader.current) {try {@@ -7140,8 +7167,14 @@ const CloudRecorder = () => {return avg < silenceThreshold;};- const stopRecording = async (shouldFinalize = true, reason = "unknown") => {- if (isFinishing.current || sentLast.current) return;+ const stopRecording = (shouldFinalize = true, reason = "unknown") => {+ if (isFinishing.current || sentLast.current) return Promise.resolve();+ const run = runStopRecording(shouldFinalize, reason);+ stopPromiseRef.current = run;+ return run;+ };++ const runStopRecording = async (shouldFinalize, reason) => {// Lock immediately: prevents duplicate stop/finalize races under unload pressure.isFinishing.current = true;clearPendingStart();@@ -10077,6 +10110,14 @@ const CloudRecorder = () => {request.reason || "offscreen-shutdown");}+ // An in-flight stop (e.g. the timer alarm) makes the call above a no-op;+ // ack after its finalize, within the timeout.+ if (request.shouldFinalize !== false && stopPromiseRef.current) {+ await Promise.race([+ stopPromiseRef.current.catch(() => {}),+ new Promise((resolve) => setTimeout(resolve, timeoutMs)),+ ]);+ }// Don't stop capture tracks here: it raced a slow start (isInit not// yet flipped, tracks live) and killed the capture mid-start.const drainPromise = Promise.all([diff --git a/src/pages/Content/camera/layout/CameraWrap.jsx b/src/pages/Content/camera/layout/CameraWrap.jsxindex 8df337b..64d06dd 100644--- a/src/pages/Content/camera/layout/CameraWrap.jsx+++ b/src/pages/Content/camera/layout/CameraWrap.jsx@@ -128,6 +128,7 @@ const CameraWrap = (props) => {!contentState.recording &&!contentState.pendingRecording &&!contentState.preparingRecording &&+ !contentState.restartingRecording &&!contentState.startGateOpen &&!contentState.countdownActive &&!contentState.isCountdownVisible;@@ -135,6 +136,7 @@ const CameraWrap = (props) => {// auth round-trip. pipActive false until "pip-started" keeps the bubble.const hidden =contentState.cameraInWindow ||+ contentState.cameraPipElsewhere ||(!idle &&!contentState.cameraOnPage &&(contentState.pipActive ||diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsxindex b34c5ed..871bdf9 100644--- a/src/pages/Content/context/ContentState.jsx+++ b/src/pages/Content/context/ContentState.jsx@@ -9,6 +9,8 @@ import React, {import { updateFromStorage } from "./utils/updateFromStorage";import { shouldResendCropTarget } from "./cropTargetGate";+import { cameraPipOnOtherTab } from "../teleprompter/prompterRules";+import { getPrompterWindow } from "../teleprompter/prompterWindow";import { lifecycle } from "../../utils/lifecycleLog";import { perfMark, perfReset } from "../../utils/perfMarks";@@ -94,6 +96,8 @@ const ContentState = (props) => {};const suppressStartBeepRef = useRef(false);const tabIdRef = useRef(null);+ const cameraPipTabRef = useRef(null);+ const restartingFlagRef = useRef(false);const activeTabRef = useRef(null);const tabRecordedIdRef = useRef(null);const recordingUiTabRef = useRef(null);@@ -166,6 +170,18 @@ const ContentState = (props) => {[isTargetTab]);+ const recomputeCameraPipElsewhere = useCallback(() => {+ const elsewhere = cameraPipOnOtherTab({+ ownerTabId: cameraPipTabRef.current,+ tabId: tabIdRef.current,+ });+ setContentState((prev) =>+ prev.cameraPipElsewhere === elsewhere+ ? prev+ : { ...prev, cameraPipElsewhere: elsewhere }+ );+ }, []);+const verifyUser = useCallback(async () => {if (!CLOUD_FEATURES_ENABLED) return;// Don't force a cookie-based re-login from the popup: a fresh install with@@ -206,6 +222,7 @@ const ContentState = (props) => {if (response?.tabId !== undefined && response?.tabId !== null) {tabIdRef.current = response.tabId;recomputeRecordingUiAllowed("tab-id");+ recomputeCameraPipElsewhere();}});@@ -217,8 +234,11 @@ const ContentState = (props) => {"recordingStartTime","recordingBeepTabId","recordingNow",+ "cameraPipTab",],(result) => {+ cameraPipTabRef.current = result.cameraPipTab ?? null;+ recomputeCameraPipElsewhere();activeTabRef.current = result.activeTab ?? null;tabRecordedIdRef.current = result.tabRecordedID ?? null;recordingUiTabRef.current = result.recordingUiTabId ?? null;@@ -227,7 +247,7 @@ const ContentState = (props) => {recomputeRecordingUiAllowed("storage-mount");});- }, [recomputeRecordingUiAllowed]);+ }, [recomputeRecordingUiAllowed, recomputeCameraPipElsewhere]);// Recompute the recording-UI scope on visibility/focus. Unlike// reconcileOnVisible (which bails during active recording), this runs during@@ -237,14 +257,24 @@ const ContentState = (props) => {// runs before `contentState` is declared, so it must not reference it.useEffect(() => {recomputeRecordingUiAllowed("mount");- const onVisible = () => recomputeRecordingUiAllowed("visibility");+ const onVisible = () => {+ recomputeRecordingUiAllowed("visibility");+ // Storage change events can be missed while a tab is in the background.+ chrome.storage.local+ .get("cameraPipTab")+ .then((stored) => {+ cameraPipTabRef.current = stored?.cameraPipTab ?? null;+ recomputeCameraPipElsewhere();+ })+ .catch(() => {});+ };document.addEventListener("visibilitychange", onVisible);window.addEventListener("focus", onVisible);return () => {document.removeEventListener("visibilitychange", onVisible);window.removeEventListener("focus", onVisible);};- }, [recomputeRecordingUiAllowed]);+ }, [recomputeRecordingUiAllowed, recomputeCameraPipElsewhere]);// Permissions-Policy camera=()/microphone=() surfaces as NotAllowedError, not a// real permission issue. This top-page probe misses feature=(self) (facebook.com);@@ -979,6 +1009,8 @@ const ContentState = (props) => {? true: false,});+ // The start gate reads this before the new pick lands.+ chrome.storage.local.remove("surface").catch(() => {});setContentState((prevContentState) => ({...prevContentState,@@ -1031,6 +1063,7 @@ const ContentState = (props) => {contentStateRef.current.recordingType === "camera" ? true : false,});traceStep("desktopCaptureSent");+ chrome.storage.local.remove("surface").catch(() => {});setContentState((prevContentState) => ({...prevContentState,@@ -1421,6 +1454,7 @@ const ContentState = (props) => {isAddingImage: false,pipEnded: false,pipActive: false,+ cameraPipElsewhere: false,tabCaptureFrame: false,showOnboardingArrow: false,offline: false,@@ -1433,7 +1467,6 @@ const ContentState = (props) => {parentRef: null,shadowRef: null,settingsOpen: false,- hideUIAlerts: false,toolbarHover: false,hideUI: false,bigTab: "record",@@ -1905,7 +1938,8 @@ const ContentState = (props) => {// hot tick never awaits IPC again.updateTimerFromStorage();const interval = setInterval(() => {- if (document.hidden) return;+ // The floating window shows this clock, and stays visible when the tab is not.+ if (document.hidden && !getPrompterWindow()) return;tickTimerFromRefs();}, 1000);const handleVisibility = () => {@@ -1931,6 +1965,12 @@ const ContentState = (props) => {// recording has fully stopped elsewhere. Without this, Wrapper.jsx's// 800ms post-stop loader timer fires on the next hide→show// transition and the "Preparing..." overlay appears.+ const pendingSinceRef = useRef(0);+ useEffect(() => {+ if (!contentState.pendingRecording) pendingSinceRef.current = 0;+ else if (!pendingSinceRef.current) pendingSinceRef.current = Date.now();+ }, [contentState.pendingRecording]);+useEffect(() => {const reconcileOnVisible = async () => {if (document.hidden) return;@@ -1938,8 +1978,18 @@ const ContentState = (props) => {const snap = await chrome.storage.local.get(["recording","restarting",+ "pendingRecording",]);if (snap.recording || snap.restarting) return;+ // Closing the picker refocuses the tab mid-start; resetting the button+ // then invites a second click. Stuck-start timers still cover a real hang.+ if (+ snap.pendingRecording &&+ pendingSinceRef.current &&+ Date.now() - pendingSinceRef.current < 60000+ ) {+ return;+ }setContentState((prev) =>prev.finalizingRecording ||prev.preparingRecording ||@@ -2044,6 +2094,13 @@ const ContentState = (props) => {if (changes.recordingUiTabId) {recordingUiTabRef.current = changes.recordingUiTabId.newValue ?? null;}+ if (changes.restarting) {+ restartingFlagRef.current = Boolean(changes.restarting.newValue);+ }+ if (changes.cameraPipTab) {+ cameraPipTabRef.current = changes.cameraPipTab.newValue ?? null;+ recomputeCameraPipElsewhere();+ }if (changes.recordingStartTime) {recordingStartTimeRef.current =changes.recordingStartTime.newValue ?? null;@@ -2081,7 +2138,10 @@ const ContentState = (props) => {...prev,preparingRecording: false,pendingRecording: false,- restartingRecording: false,+ // A restart passes through "not recording"; its own flag ends it.+ restartingRecording: restartingFlagRef.current+ ? prev.restartingRecording+ : false,}: prev);@@ -2335,7 +2395,12 @@ const ContentState = (props) => {chrome.storage.onChanged.addListener(onChanged);return () => chrome.storage.onChanged.removeListener(onChanged);- }, [isTargetTab, updateTimerFromStorage, verifyUser]);+ }, [+ isTargetTab,+ updateTimerFromStorage,+ verifyUser,+ recomputeCameraPipElsewhere,+ ]);useEffect(() => {if (!contentState.customRegion) {@@ -2487,7 +2552,6 @@ const ContentState = (props) => {if (!contentState.hideUI) {setContentState((prevContentState) => ({...prevContentState,- hideUIAlerts: false,hideToolbar: false,toolbarHover: false,}));diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.jsindex 1dec4f2..dea6b18 100644--- a/src/pages/Content/context/messaging/handlers.js+++ b/src/pages/Content/context/messaging/handlers.js@@ -11,6 +11,7 @@ import {abortStartGate,runPrompterStartGate,} from "../../teleprompter/prompterGate";+import { getPrompterWindow } from "../../teleprompter/prompterWindow";import { traceStep, setStartFlowOutcome } from "../../../utils/startFlowTrace";import { perfMark } from "../../../utils/perfMarks";import { triggerSupportDownload } from "../../../utils/triggerSupportDownload";@@ -631,13 +632,28 @@ export const setupHandlers = () => {preparingRecording: false,pendingRecording: true,}));+ // Two frames: the popup is out of the capture only once it has painted away.+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ chrome.storage.local.set({ popupHiddenAt: Date.now() }).catch(() => {});+ }),+ );// Waits on the user's choice when the capture would record the teleprompter// window. No-op if it isn't open.+ const hadScriptWindow = Boolean(getPrompterWindow());try {// Ended under the prompt (stop-pending, recording-error): no countdown.if ((await runPrompterStartGate(getState())) === ABORTED) return;- } catch {}+ } catch {+ } finally {+ // With no countdown the background holds the start for this mark.+ if (hadScriptWindow) {+ chrome.storage.local+ .set({ prompterGateDone: Date.now() })+ .catch(() => {});+ }+ }// BG is source of truth; reading React default would race the user// setting and produce double beeps.@@ -715,11 +731,10 @@ export const setupHandlers = () => {...prev,hideUI: nextHideUI,hideToolbar: nextHideUI ? true : prev.hideToolbar,- hideUIAlerts: nextHideUI ? true : prev.hideUIAlerts,}));chrome.storage.local.set({hideUI: nextHideUI,- ...(nextHideUI ? { hideToolbar: true, hideUIAlerts: true } : {}),+ ...(nextHideUI ? { hideToolbar: true } : {}),});});@@ -756,7 +771,9 @@ export const setupHandlers = () => {nextActive? chrome.i18n.getMessage("micOnToast"): chrome.i18n.getMessage("micOffToast"),- () => {}+ () => {},+ undefined,+ { quietWhileRecording: true });}});diff --git a/src/pages/Content/context/utils/migrateHideUIAlerts.js b/src/pages/Content/context/utils/migrateHideUIAlerts.jsnew file mode 100644index 0000000..0bbfbd5--- /dev/null+++ b/src/pages/Content/context/utils/migrateHideUIAlerts.js@@ -0,0 +1,8 @@+// "Hide UI notifications" was removed. Its mode showed the toolbar with+// everything else off, so a user who had it gets the normal UI back; a user who+// also had the toolbar hidden keeps that.+export const migrateHideUIAlerts = (stored) => {+ if (!stored?.hideUIAlerts) return null;+ const resetHideUI = !stored.hideToolbar && !stored.toolbarHover;+ return { resetHideUI };+};diff --git a/src/pages/Content/context/utils/updateFromStorage.js b/src/pages/Content/context/utils/updateFromStorage.jsindex f264856..d906866 100644--- a/src/pages/Content/context/utils/updateFromStorage.js+++ b/src/pages/Content/context/utils/updateFromStorage.js@@ -1,5 +1,6 @@import { setContentState } from "../ContentState";import { checkRecording } from "./checkRecording";+import { migrateHideUIAlerts } from "./migrateHideUIAlerts";const CURSOR_EFFECTS = ["target", "highlight", "spotlight"];@@ -77,8 +78,17 @@ export const updateFromStorage = (check = true, id = null) => {"wasLoggedIn","instantMode","hasSubscribedBefore",+ "isSubscribed",],(result) => {+ const migration = migrateHideUIAlerts(result);+ if (migration) {+ chrome.storage.local.remove("hideUIAlerts");+ if (migration.resetHideUI) {+ chrome.storage.local.set({ hideUI: false });+ result.hideUI = false;+ }+ }const storedEffects = normalizeCursorEffects(result.cursorEffects);const hasStoredEffects = Array.isArray(result.cursorEffects);const legacyMode =@@ -251,10 +261,6 @@ export const updateFromStorage = (check = true, id = null) => {result.surface !== undefined && result.surface !== null? result.surface: prevContentState.surface,- hideUIAlerts:- result.hideUIAlerts !== undefined && result.hideUIAlerts !== null- ? result.hideUIAlerts- : prevContentState.hideUIAlerts,hideUI:result.hideUI !== undefined && result.hideUI !== null? result.hideUI@@ -325,6 +331,13 @@ export const updateFromStorage = (check = true, id = null) => {instantMode: result.instantMode || false,onboarding: result.onboarding || false,hasSubscribedBefore: result.hasSubscribedBefore || false,+ // Seeds a fresh tab only: until the auth check answers, a Pro bubble+ // would show on a page loaded mid-recording. That check overrides it.+ isSubscribed:+ prevContentState.isSubscribed === undefined &&+ typeof result.isSubscribed === "boolean"+ ? result.isSubscribed+ : prevContentState.isSubscribed,showProSplash: result.showProSplash || false,}));diff --git a/src/pages/Content/popup/components/Switch.jsx b/src/pages/Content/popup/components/Switch.jsxindex 1a24e45..515be3f 100644--- a/src/pages/Content/popup/components/Switch.jsx+++ b/src/pages/Content/popup/components/Switch.jsx@@ -62,10 +62,7 @@ const Switch = (props) => {useEffect(() => {if (props.name === "hideUI") {- if (contentState.hideUIAlerts) {- setHideToolbarLabel(chrome.i18n.getMessage("hideUIAlerts"));- setHideToolbarState(2);- } else if (contentState.hideToolbar) {+ if (contentState.hideToolbar) {setHideToolbarLabel(chrome.i18n.getMessage("hideToolbarLabel"));setHideToolbarState(1);} else if (contentState.toolbarHover) {@@ -108,12 +105,10 @@ const Switch = (props) => {setContentState((prevContentState) => ({...prevContentState,hideToolbar: true,- hideUIAlerts: false,toolbarHover: false,}));chrome.storage.local.set({hideToolbar: true,- hideUIAlerts: false,toolbarHover: false,});setHideToolbarLabel(@@ -131,33 +126,10 @@ const Switch = (props) => {setContentState((prevContentState) => ({...prevContentState,hideToolbar: false,- hideUIAlerts: true,- toolbarHover: false,- }));- chrome.storage.local.set({- hideToolbar: false,- hideUIAlerts: true,- toolbarHover: false,- });- setHideToolbarLabel(chrome.i18n.getMessage("hideUIAlerts"));- dropdownRef.current.classList.remove("labelDropdownActive");- setHideToolbarState(2);- }}- >- {chrome.i18n.getMessage("hideUIAlerts")}- </div>- <div- className="labelDropdownContentItem"- onClick={() => {- setContentState((prevContentState) => ({- ...prevContentState,- hideToolbar: false,- hideUIAlerts: false,toolbarHover: true,}));chrome.storage.local.set({hideToolbar: false,- hideUIAlerts: false,toolbarHover: true,});setHideToolbarLabel(@@ -205,36 +177,20 @@ const Switch = (props) => {setContentState((prevContentState) => ({...prevContentState,hideToolbar: true,- hideUIAlerts: false,toolbarHover: false,}));chrome.storage.local.set({hideToolbar: true,- hideUIAlerts: false,- toolbarHover: false,- });- } else if (hideToolbarState === 2) {- setContentState((prevContentState) => ({- ...prevContentState,- hideToolbar: false,- hideUIAlerts: true,- toolbarHover: false,- }));- chrome.storage.local.set({- hideToolbar: false,- hideUIAlerts: true,toolbarHover: false,});} else if (hideToolbarState === 3) {setContentState((prevContentState) => ({...prevContentState,hideToolbar: false,- hideUIAlerts: false,toolbarHover: true,}));chrome.storage.local.set({hideToolbar: false,- hideUIAlerts: false,toolbarHover: true,});}diff --git a/src/pages/Content/teleprompter/TeleprompterController.jsx b/src/pages/Content/teleprompter/TeleprompterController.jsxindex 7fe035b..70e92f1 100644--- a/src/pages/Content/teleprompter/TeleprompterController.jsx+++ b/src/pages/Content/teleprompter/TeleprompterController.jsx@@ -21,7 +21,11 @@ import {normalizeSettings,shouldClosePrompter,} from "./prompterRules";-import { notifyPrompterClosed, startCameraCloseNotice } from "./prompterGate";+import {+ giveWindowToCamera,+ notifyPrompterClosed,+ startCameraCloseNotice,+} from "./prompterGate";import { loadPrompterSettings, savePrompterSettings } from "./prompterSettings";import {closePipLayer,@@ -38,6 +42,51 @@ const SAVE_DELAY_MS = 400;const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";+// Publishes this tab's id under `key` while `active`; removes it on exit only if+// still ours, since another tab's window may have replaced this one (Chrome+// keeps a single floating window).+const usePublishedTab = (key, active) => {+ const publishedRef = useRef(null);+ const clear = useCallback(() => {+ const mine = publishedRef.current;+ if (mine == null) return;+ publishedRef.current = null;+ try {+ chrome.storage.local+ .get(key)+ .then((stored) => {+ if (stored?.[key] === mine) return chrome.storage.local.remove(key);+ })+ .catch(() => {});+ } catch {}+ }, [key]);+ useEffect(() => {+ let cancelled = false;+ if (active) {+ chrome.runtime+ .sendMessage({ type: "get-tab-id" })+ .then((res) => {+ if (cancelled || res?.tabId == null) return;+ publishedRef.current = res.tabId;+ chrome.storage.local.set({ [key]: res.tabId });+ })+ .catch(() => {});+ } else {+ clear();+ }+ return () => {+ cancelled = true;+ };+ }, [active, key, clear]);+ useEffect(() => {+ window.addEventListener("pagehide", clear);+ return () => {+ window.removeEventListener("pagehide", clear);+ clear();+ };+ }, [clear]);+};+// Always mounted. Owns the floating window once the popup opens it and ties it// to the recording: scrolls with the take, stops on pause, closes if the capture includes it.const TeleprompterController = () => {@@ -192,6 +241,12 @@ const TeleprompterController = () => {// Hiding the camera in the window moves it to the page, bubble included, even// where it is normally hidden during a recording.const cameraShown = cameraOn && settings?.showCamera !== false;++ // Other tabs can't see this window, so their page bubble would double the camera in it.+ // Wait for settings: they decide whether the camera is really in the window.+ usePublishedTab("cameraPipTab", cameraShown && settings !== null);+ // The background holds a no-countdown start until the gate has closed this.+ usePublishedTab("prompterScriptTab", prompterOn || controlsOn);useEffect(() => {const onPage = cameraOn && !cameraShown;setContentState((prev) =>@@ -221,7 +276,6 @@ const TeleprompterController = () => {recordingType: message.recordingType || null,surface: message.surface,layers: getPipLayers(),- keepVisible: getPrompterKeepVisible(),cameraEnabled:Boolean(state.cameraActive) && state.defaultVideoInput !== "none",windowOpen: Boolean(getPrompterWindow()),@@ -259,8 +313,18 @@ const TeleprompterController = () => {})) {if (getPipLayers().prompter) void notifyPrompterClosed(state);- closePipLayer("prompter", "capture records the window");- closePipLayer("controls", "capture records the window");+ // The camera has to be in the window before the script leaves it, or the window closes.+ giveWindowToCamera({+ ...state,+ isSubscribed: Boolean(message.subscribed),+ instantMode: Boolean(message.instantMode),+ recordingType: message.recordingType || state.recordingType,+ })+ .catch(() => {})+ .finally(() => {+ closePipLayer("prompter", "capture records the window");+ closePipLayer("controls", "capture records the window");+ });}};chrome.runtime.onMessage.addListener(onRuntime);@@ -472,7 +536,9 @@ const TeleprompterController = () => {});contentState.openToast?.(chrome.i18n.getMessage(pressed ? "micOnToast" : "micOffToast"),- () => {}+ () => {},+ undefined,+ { quietWhileRecording: true });};diff --git a/src/pages/Content/teleprompter/prompterGate.js b/src/pages/Content/teleprompter/prompterGate.jsindex 52d4924..98b296c 100644--- a/src/pages/Content/teleprompter/prompterGate.js+++ b/src/pages/Content/teleprompter/prompterGate.js@@ -1,5 +1,6 @@import { setContentState } from "../context/ContentState";import { cameraCanLiveInWindow, prompterCaptureStatus } from "./prompterRules";+import { loadPrompterSettings } from "./prompterSettings";import {closePipLayer,getPipLayers,@@ -12,16 +13,19 @@ import {const NO_PROMPT_KEY = "teleprompterFullScreenNoPrompt";// Burnt-in camera: once a full-screen capture closes the script, the camera takes the window.-const giveWindowToCamera = (state) => {+// A camera the user moved to the page stays there, or the window would hold a blank panel+// next to a bubble that is also on the page.+export const giveWindowToCamera = async (state) => {const own = cameraCanLiveInWindow({cloud: process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true",subscribed: state.isSubscribed,instantMode: state.instantMode,});if (own || state.recordingType !== "screen") return;- if (state.cameraActive && state.defaultVideoInput !== "none") {- openPipLayer("camera", "gate: full screen");- }+ if (!state.cameraActive || state.defaultVideoInput === "none") return;+ const { showCamera } = await loadPrompterSettings();+ if (showCamera === false) return;+ openPipLayer("camera", "gate: full screen");};const msg = (key, fallback) => chrome.i18n.getMessage(key) || fallback;@@ -178,7 +182,7 @@ export const runPrompterStartGate = async (state) => {if (getPrompterKeepVisible()) return;// Controls-only window needs no prompt, the toolbar is visible.if (!getPipLayers().prompter) {- giveWindowToCamera(state);+ await giveWindowToCamera(state);closePipLayer("controls", "gate: full screen");return startCameraCloseNotice(state);}@@ -186,7 +190,7 @@ export const runPrompterStartGate = async (state) => {// No countdown: close the script and toast instead of asking.const { remembered, countdownOn } = await readGatePrefs();if (!countdownOn && !remembered) {- giveWindowToCamera(state);+ await giveWindowToCamera(state);closeScriptWindow("gate: no countdown");state.openToast?.(msg("teleprompterFullScreenTitle", "Teleprompter will be closed"),@@ -195,7 +199,7 @@ export const runPrompterStartGate = async (state) => {return;}if (remembered || typeof state.openModal !== "function") {- giveWindowToCamera(state);+ await giveWindowToCamera(state);closeScriptWindow("gate: remembered");return;}@@ -207,7 +211,7 @@ export const runPrompterStartGate = async (state) => {settled = true;resolve(ABORTED);};- const choose = (choice) => () => {+ const choose = (choice) => async () => {if (settled) return;settled = true;abortOpenPrompt = null;@@ -227,7 +231,7 @@ export const runPrompterStartGate = async (state) => {if (choice === "never") {chrome.storage.local.set({ [NO_PROMPT_KEY]: true }).catch(() => {});}- giveWindowToCamera(state);+ await giveWindowToCamera(state);closeScriptWindow("gate: closed");}resolve();diff --git a/src/pages/Content/teleprompter/prompterRules.js b/src/pages/Content/teleprompter/prompterRules.jsindex e5ce1b3..5c818e2 100644--- a/src/pages/Content/teleprompter/prompterRules.js+++ b/src/pages/Content/teleprompter/prompterRules.js@@ -104,6 +104,11 @@ export const wantsCameraLayerAtStart = ({return (recordingType === "region" || recordingType === "tab") && own;};+// The floating window belongs to the tab that opened it, so every other tab+// sees only this storage flag. Its page bubble would double the camera there.+export const cameraPipOnOtherTab = ({ ownerTabId, tabId }) =>+ ownerTabId != null && ownerTabId !== tabId;+// Whether the capture records the floating window along with the screen. A// region or tab capture still reports displaySurface "monitor", so the// recording type leads.@@ -132,7 +137,6 @@ export const planCameraAtSurface = ({recordingType,surface,layers,- keepVisible,cameraEnabled,windowOpen,}) => {@@ -146,8 +150,9 @@ export const planCameraAtSurface = ({if (layers.camera) return keeps ? "keep" : "close";if (!keeps || !cameraEnabled || !windowOpen) return "keep";const own = cameraCanLiveInWindow({ cloud, subscribed, instantMode });- // A script kept over a full-screen capture does not share the window with a burnt-in camera.- if (!own && layers.prompter && keepVisible) return "keep";+ // A burnt-in camera never shares the window with the script. While the script+ // is up, the start gate or take-start close decides which one keeps the window.+ if (!own && layers.prompter) return "keep";return "open";};diff --git a/src/pages/Content/toolbar/components/MicToggle.jsx b/src/pages/Content/toolbar/components/MicToggle.jsxindex 622e8eb..eb6258a 100644--- a/src/pages/Content/toolbar/components/MicToggle.jsx+++ b/src/pages/Content/toolbar/components/MicToggle.jsx@@ -53,7 +53,9 @@ const MicToggle = (props) => {pressed? chrome.i18n.getMessage("micOnToast"): chrome.i18n.getMessage("micOffToast"),- () => {}+ () => {},+ undefined,+ { quietWhileRecording: true });}}>diff --git a/src/pages/Content/toolbar/components/Toast.jsx b/src/pages/Content/toolbar/components/Toast.jsxindex a234e6f..56da3af 100644--- a/src/pages/Content/toolbar/components/Toast.jsx+++ b/src/pages/Content/toolbar/components/Toast.jsx@@ -28,8 +28,9 @@ const Toast = () => {contentStateRef.current = contentState;}, [contentState]);- const openToast = useCallback((title, action, durationMs = 2000) => {- if (contentStateRef.current.hideUI) return;+ const openToast = useCallback((title, action, durationMs = 2000, opts) => {+ // The toast is in the page, so a tab or screen capture records it.+ if (opts?.quietWhileRecording && contentStateRef.current.recording) return;setTitle(title);setOpen(true);// Keep trigger callable even when a toast is opened without an action.diff --git a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx b/src/pages/Content/toolbar/layout/ToolbarWrap.jsxindex df72349..380e651 100644--- a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx+++ b/src/pages/Content/toolbar/layout/ToolbarWrap.jsx@@ -318,17 +318,37 @@ const ToolbarWrap = () => {useEffect(() => {if (!contentState.openToast) return;if (contentState.drawingMode) {- contentState.openToast(chrome.i18n.getMessage("drawingModeToast"), () => {- setMode("");- });+ contentState.openToast(+ chrome.i18n.getMessage("drawingModeToast"),+ () => {+ setMode("");+ },+ undefined,+ { quietWhileRecording: true },+ );}if (contentState.blurMode) {- contentState.openToast(chrome.i18n.getMessage("blurModeToast"), () => {- setMode("");- });+ contentState.openToast(+ chrome.i18n.getMessage("blurModeToast"),+ () => {+ setMode("");+ },+ undefined,+ { quietWhileRecording: true },+ );}}, [contentState.drawingMode, contentState.blurMode, contentState.openToast]);+ // The toast carried the Esc shortcut, and it is hidden while recording.+ useEffect(() => {+ if (!contentState.drawingMode && !contentState.blurMode) return;+ const onKeyDown = (e) => {+ if (e.key === "Escape") setMode("");+ };+ document.addEventListener("keydown", onKeyDown);+ return () => document.removeEventListener("keydown", onKeyDown);+ }, [contentState.drawingMode, contentState.blurMode]);+useEffect(() => {if (contentState.drawingMode) setMode("draw");else if (contentState.blurMode) setMode("blur");@@ -456,14 +476,12 @@ const ToolbarWrap = () => {hideToolbar: true,drawingMode: false,blurMode: false,- hideUIAlerts: false,toolbarHover: false,hideUI: true,}));chrome.storage.local.set({hideToolbar: true,- hideUIAlerts: false,toolbarHover: false,hideUI: true,});diff --git a/src/pages/EditorApp/components/editor/Trimmer.jsx b/src/pages/EditorApp/components/editor/Trimmer.jsxindex 5151f06..156ce7c 100644--- a/src/pages/EditorApp/components/editor/Trimmer.jsx+++ b/src/pages/EditorApp/components/editor/Trimmer.jsx@@ -18,6 +18,8 @@ const Trimmer = (props) => {const addToHistoryRef = useRef(null);const startBoundRef = useRef(0);const endBoundRef = useRef(1);+ const lastSeekRef = useRef(0);+ const seekTimerRef = useRef(null);useEffect(() => {setContentStateRef.current = setContentState;@@ -26,6 +28,33 @@ const Trimmer = (props) => {endBoundRef.current = contentState.end;});+ const seekToHandle = (handle) => {+ setContentStateRef.current((prev) =>+ handle && prev.duration > 0+ ? {+ ...prev,+ time: prev[handle] * prev.duration,+ updatePlayerTime: true,+ }+ : prev,+ );+ };++ // Leading + trailing throttle so a fast drag still lands on the last frame.+ const scheduleSeek = (handle) => {+ const elapsed = performance.now() - lastSeekRef.current;+ clearTimeout(seekTimerRef.current);+ if (elapsed >= 60) {+ lastSeekRef.current = performance.now();+ seekToHandle(handle);+ } else {+ seekTimerRef.current = setTimeout(() => {+ lastSeekRef.current = performance.now();+ seekToHandle(handle);+ }, 60 - elapsed);+ }+ };+const handleMouseMoveRef = useRef(null);const handleMouseUpRef = useRef(null);@@ -57,12 +86,16 @@ const Trimmer = (props) => {end: Math.max(validPosition, prev.start + 0.02),}));}+ scheduleSeek(activeHandle.current);};}if (!handleMouseUpRef.current) {handleMouseUpRef.current = () => {+ const handle = activeHandle.current;isDragging.current = false;activeHandle.current = null;+ clearTimeout(seekTimerRef.current);+ seekToHandle(handle);try {addToHistoryRef.current?.();} catch {}@@ -78,6 +111,7 @@ const Trimmer = (props) => {// Cleanup if component unmounts mid-drag.useEffect(() => {return () => {+ clearTimeout(seekTimerRef.current);document.removeEventListener("mousemove", handleMouseMoveRef.current);document.removeEventListener("mouseup", handleMouseUpRef.current);};diff --git a/src/pages/EditorApp/components/editor/VideoPlayer.jsx b/src/pages/EditorApp/components/editor/VideoPlayer.jsxindex 1fd7598..a3faa4e 100644--- a/src/pages/EditorApp/components/editor/VideoPlayer.jsx+++ b/src/pages/EditorApp/components/editor/VideoPlayer.jsx@@ -6,9 +6,9 @@ import { ContentStateContext } from "../../context/ContentState"; // Import theconst VideoPlayer = (props) => {const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState contextconst playerRef = useRef(null);+ const wrapRef = useRef(null);const [url, setUrl] = useState(null);const [source, setSource] = useState(null);- const [isSet, setIsSet] = useState(false);// Probed from the blob's intrinsic dimensions; a fixed "16:9" would// pillarbox recordings of square-ish tabs.const [videoRatio, setVideoRatio] = useState("16:9");@@ -97,62 +97,28 @@ const VideoPlayer = (props) => {}}, [contentState.blob, playerRef]);+ // Media events don't bubble but can be captured, so one listener on the+ // wrapper survives plyr-react rebuilding the Plyr (and its <video>) on every+ // source change.useEffect(() => {- if (playerRef.current && playerRef.current.plyr) {- // Check when the video is playing, update the time in real time- playerRef.current.plyr.on("timeupdate", () => {- setContentState((prevContentState) => ({- ...prevContentState,- time: playerRef.current.plyr.currentTime,- updatePlayerTime: false,- }));- });- }-- return () => {- if (playerRef.current && playerRef.current.plyr) {- playerRef.current.plyr.off("timeupdate");- }- };- }, [playerRef]);-- const handleClick = () => {- if (isSet) return;- if (playerRef.current && playerRef.current.plyr) {- setIsSet(true);- playerRef.current.plyr.on("timeupdate", () => {- setContentState((prevContentState) => ({- ...prevContentState,- time: playerRef.current.plyr.currentTime,- updatePlayerTime: false,- }));- });- }- };-- useEffect(() => {- if (isSet) return;- const handleKeyPress = (event) => {- if (playerRef.current && playerRef.current.plyr) {- setIsSet(true);- playerRef.current.plyr.on("timeupdate", () => {- setContentState((prevContentState) => ({- ...prevContentState,- time: playerRef.current.plyr.currentTime,- updatePlayerTime: false,- }));- });- }- };- window.addEventListener("keydown", handleKeyPress);- return () => {- window.removeEventListener("keydown", handleKeyPress);+ const wrap = wrapRef.current;+ if (!wrap) return;+ const onTimeUpdate = (e) => {+ if (e.target?.tagName !== "VIDEO") return;+ const time = e.target.currentTime;+ setContentState((prevContentState) => ({+ ...prevContentState,+ time,+ updatePlayerTime: false,+ }));};- }, [isSet]);+ wrap.addEventListener("timeupdate", onTimeUpdate, true);+ return () => wrap.removeEventListener("timeupdate", onTimeUpdate, true);+ }, []);return (<div className="videoPlayer">- <div className="playerWrap" onClick={handleClick}>+ <div className="playerWrap" ref={wrapRef}>{url && (<Plyrref={playerRef}diff --git a/src/pages/EditorApp/components/editor/Waveform.jsx b/src/pages/EditorApp/components/editor/Waveform.jsxindex a4dc8ff..b968266 100644--- a/src/pages/EditorApp/components/editor/Waveform.jsx+++ b/src/pages/EditorApp/components/editor/Waveform.jsx@@ -132,20 +132,17 @@ const WaveformGenerator = (props) => {if (contentState.updatePlayerTime) return;if (waveformContainerRef.current === null) return;- const video = document.createElement("video");- video.preload = "metadata";- video.onloadedmetadata = async () => {- const containerRect =- waveformContainerRef.current.getBoundingClientRect();- const cursorX =- containerRect.width * (contentState.time / video.duration);- customCursorRef.current.style.left = `${cursorX}px`;-- URL.revokeObjectURL(video.src);- video.remove();- };- video.src = URL.createObjectURL(contentState.blob);- }, [contentState.time, contentState.blob, waveformContainerRef.current]);+ if (!(contentState.duration > 0)) return;+ const containerRect = waveformContainerRef.current.getBoundingClientRect();+ const cursorX =+ containerRect.width * (contentState.time / contentState.duration);+ customCursorRef.current.style.left = `${cursorX}px`;+ }, [+ contentState.time,+ contentState.blob,+ contentState.duration,+ waveformContainerRef.current,+ ]);return (<div style={{ height: "100%" }}>diff --git a/src/pages/EditorApp/components/global/DisabledTip.jsx b/src/pages/EditorApp/components/global/DisabledTip.jsxnew file mode 100644index 0000000..3570f5d--- /dev/null+++ b/src/pages/EditorApp/components/global/DisabledTip.jsx@@ -0,0 +1,26 @@+import React from "react";+import * as Tooltip from "@radix-ui/react-tooltip";+import styles from "../../styles/edit/_EditorNav.module.scss";++// Disabled buttons swallow hover, so the tooltip hangs off a wrapper span.+const DisabledTip = ({ content, active, children }) => (+ <Tooltip.Provider>+ <Tooltip.Root delayDuration={200} open={active ? undefined : false}>+ <Tooltip.Trigger asChild>+ <span className={styles.saveWrap}>{children}</span>+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Content+ className={styles.tooltip}+ side="bottom"+ align="end"+ sideOffset={8}+ >+ {content}+ </Tooltip.Content>+ </Tooltip.Portal>+ </Tooltip.Root>+ </Tooltip.Provider>+);++export default DisabledTip;diff --git a/src/pages/EditorApp/context/ContentState.jsx b/src/pages/EditorApp/context/ContentState.jsxindex 90acb5f..eb0a613 100644--- a/src/pages/EditorApp/context/ContentState.jsx+++ b/src/pages/EditorApp/context/ContentState.jsx@@ -105,6 +105,7 @@ const ContentState = (props) => {const tabIdRef = useRef(null);const opIdRef = useRef(0);const editWatchdogRef = useRef(null);+ const editWaitersRef = useRef([]);useEffect(() => {if (!DEBUG_RECORDER && !isRecordingDebugEnabled()) return;@@ -889,6 +890,15 @@ const ContentState = (props) => {const probedSec = Number.isFinite(video.duration) && video.duration > 0? video.duration: 0;+ // Large gap = the file holds less than was recorded (or a wrong mvhd).+ // Telemetry only; the override below is unchanged.+ if (recSec - probedSec > Math.max(10, recSec * 0.15)) {+ diagForward("editor-duration-mismatch", {+ recordedSec: Math.round(recSec),+ fileSec: Math.round(probedSec),+ blobBytes: contentState.blob?.size ?? 0,+ });+ }if (recSec > probedSec + 0.3) {durationSec = recSec;} else if (probedSec > 0) {@@ -2219,6 +2229,7 @@ const ContentState = (props) => {// discard timed-out/superseded opsconst msgOpId = event.data._opId;if (msgOpId != null && msgOpId !== opIdRef.current) return;+ settleEditWaiters(true);const base64 = event.data.base64;@@ -2302,6 +2313,12 @@ const ContentState = (props) => {URL.revokeObjectURL(video.src);video.remove();};+ video.onerror = () => {+ // keep a stale pre-edit selection from blocking Save on the new blob+ setContentState((prev) => ({ ...prev, start: 0, end: 1 }));+ URL.revokeObjectURL(video.src);+ video.remove();+ };video.src = URL.createObjectURL(blob);@@ -2378,6 +2395,7 @@ const ContentState = (props) => {errorStack: event.data.errorStack,});clearEditOp();+ settleEditWaiters(false);// fall back to webm/rawBlob even if conversion failssetContentState((prev) => {@@ -2403,6 +2421,7 @@ const ContentState = (props) => {chrome.runtime.sendMessage({ type: "recording-complete" });} else if (event.data.type === "audio-too-large") {clearEditOp();+ settleEditWaiters(false);setContentState((prev) => ({...prev,isFfmpegRunning: false,@@ -2417,6 +2436,7 @@ const ContentState = (props) => {} else if (event.data.type === "edit-too-long") {// Too long for in-browser processing, reset so user can retry or trim.clearEditOp();+ settleEditWaiters(false);setContentState((prev) => ({...prev,isFfmpegRunning: false,@@ -2631,6 +2651,7 @@ const ContentState = (props) => {editWatchdogRef.current = setTimeout(() => {editWatchdogRef.current = null;opIdRef.current += 1;+ settleEditWaiters(false);setContentState((prev) => ({...prev,isFfmpegRunning: false,@@ -2646,6 +2667,12 @@ const ContentState = (props) => {return id;};+ const settleEditWaiters = (ok) => {+ const waiters = editWaitersRef.current;+ editWaitersRef.current = [];+ waiters.forEach((resolve) => resolve(ok));+ };+const clearEditOp = () => {if (editWatchdogRef.current) {clearTimeout(editWatchdogRef.current);@@ -2656,6 +2683,7 @@ const ContentState = (props) => {const cancelEditOp = () => {opIdRef.current += 1;clearEditOp();+ settleEditWaiters(false);setContentState((prev) => ({...prev,isFfmpegRunning: false,@@ -2669,12 +2697,14 @@ const ContentState = (props) => {};const addAudio = async (videoBlob, audioBlob, volume) => {- if (contentState.isFfmpegRunning) return;+ if (contentState.isFfmpegRunning) return false;if (contentState.duration > contentState.editLimit &&!contentState.override- )- return;+ ) {+ setContentState((prev) => ({ ...prev, editErrorType: "too-long" }));+ return false;+ }const sourceBlob = videoBlob || contentState.blob || contentState.webm;const opId = beginEditOp();@@ -2696,6 +2726,8 @@ const ContentState = (props) => {topLevel: false,_opId: opId,});++ return true;};const handleTrim = async (cut) => {@@ -2804,12 +2836,14 @@ const ContentState = (props) => {};const handleCrop = async (x, y, width, height) => {- if (contentState.isFfmpegRunning || contentState.cropping) return;+ if (contentState.isFfmpegRunning || contentState.cropping) return false;if (contentState.duration > contentState.editLimit &&!contentState.override- )- return;+ ) {+ setContentState((prev) => ({ ...prev, editErrorType: "too-long" }));+ return false;+ }const opId = beginEditOp();@@ -3833,15 +3867,10 @@ const ContentState = (props) => {sendMessage({ type: "load-ffmpeg" });};+ // Resolves true once the edit's blob arrives; false on failure, timeout or cancel.const waitForUpdatedBlob = () => {return new Promise((resolve) => {- const handler = (event) => {- if (event.data?.type === "updated-blob") {- window.removeEventListener("message", handler);- resolve();- }- };- window.addEventListener("message", handler);+ editWaitersRef.current.push(resolve);});};diff --git a/src/pages/EditorApp/layout/editor/AudioNav.js b/src/pages/EditorApp/layout/editor/AudioNav.jsindex 4aa85c3..48b9bf3 100644--- a/src/pages/EditorApp/layout/editor/AudioNav.js+++ b/src/pages/EditorApp/layout/editor/AudioNav.js@@ -1,6 +1,7 @@import React, { useContext } from "react";import styles from "../../styles/edit/_EditorNav.module.scss";import { ContentStateContext } from "../../context/ContentState";+import DisabledTip from "../../components/global/DisabledTip";const URL = "/assets/";@@ -41,24 +42,29 @@ const AudioNav = () => {);};+ const saveBlocked = !contentState.pendingAudio && !contentState.isFfmpegRunning;+const saveChanges = async () => {const { pendingAudio, volume } = contentState;- const source = contentState.blob;+ if (!pendingAudio || contentState.isFfmpegRunning) return;- setContentState((prev) => ({- ...prev,- isFfmpegRunning: true,- processingProgress: 0,- fromAudio: true,- }));+ setContentState((prev) => ({ ...prev, fromAudio: true }));- if (pendingAudio) {- contentState.addAudio(source, pendingAudio, volume);- } else {- contentState.handleReencode(true);+ const started = await contentState.addAudio(+ contentState.blob,+ pendingAudio,+ volume,+ );+ if (!started) {+ setContentState((prev) => ({ ...prev, fromAudio: false }));+ return;}- await contentState.waitForUpdatedBlob?.();+ const saved = await contentState.waitForUpdatedBlob?.();+ if (!saved) {+ setContentState((prev) => ({ ...prev, fromAudio: false }));+ return;+ }contentState.clearBackup();contentState.openToast?.(@@ -100,27 +106,32 @@ const AudioNav = () => {{chrome.i18n.getMessage("sandboxEditorRevertButton")}</button>- <button- className="button primaryButton"- onClick={saveChanges}- disabled={contentState.isFfmpegRunning}+ <DisabledTip+ active={saveBlocked}+ content={chrome.i18n.getMessage("sandboxEditorAudioPendingHint")}>- {contentState.isFfmpegRunning ? (- contentState.processingProgress > 0 ? (- <>- {chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||- "Saving"}{" "}- {Math.round(contentState.processingProgress)}%- </>+ <button+ className="button primaryButton"+ onClick={saveChanges}+ disabled={contentState.isFfmpegRunning || !contentState.pendingAudio}+ >+ {contentState.isFfmpegRunning ? (+ contentState.processingProgress > 0 ? (+ <>+ {chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||+ "Saving"}{" "}+ {Math.round(contentState.processingProgress)}%+ </>+ ) : (+ chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||+ "Saving..."+ )) : (- chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||- "Saving..."- )- ) : (- chrome.i18n.getMessage("sandboxEditorSaveButton") ||- "Save changes"- )}- </button>+ chrome.i18n.getMessage("sandboxEditorSaveButton") ||+ "Save changes"+ )}+ </button>+ </DisabledTip></div></div></div>diff --git a/src/pages/EditorApp/layout/editor/AudioUI.js b/src/pages/EditorApp/layout/editor/AudioUI.jsindex 93c4fe2..608acd7 100644--- a/src/pages/EditorApp/layout/editor/AudioUI.js+++ b/src/pages/EditorApp/layout/editor/AudioUI.js@@ -128,6 +128,7 @@ const AudioUI = (props) => {setContentState((prevContentState) => ({...prevContentState,blob: prevBlob.current,+ pendingAudio: null,}));inputRef.current.value = null;}}diff --git a/src/pages/EditorApp/layout/editor/CropNav.js b/src/pages/EditorApp/layout/editor/CropNav.jsindex 0abb021..ab2922f 100644--- a/src/pages/EditorApp/layout/editor/CropNav.js+++ b/src/pages/EditorApp/layout/editor/CropNav.js@@ -55,18 +55,26 @@ const CropNav = () => {};const saveChanges = async () => {- await contentState.handleCrop(+ setContentState((prev) => ({ ...prev, fromCropper: true }));++ const started = await contentState.handleCrop(contentState.left,contentState.top,contentState.width,contentState.height);+ if (!started) {+ setContentState((prev) => ({ ...prev, fromCropper: false }));+ return;+ }- setContentState((prev) => ({- ...prev,- fromCropper: true,- hasTempChanges: false,- }));+ const saved = await contentState.waitForUpdatedBlob?.();+ if (!saved) {+ setContentState((prev) => ({ ...prev, fromCropper: false }));+ return;+ }++ setContentState((prev) => ({ ...prev, hasTempChanges: false }));contentState.clearBackup();contentState.openToast?.(diff --git a/src/pages/EditorApp/layout/editor/EditorNav.js b/src/pages/EditorApp/layout/editor/EditorNav.jsindex 03d3ac6..938090c 100644--- a/src/pages/EditorApp/layout/editor/EditorNav.js+++ b/src/pages/EditorApp/layout/editor/EditorNav.js@@ -1,4 +1,5 @@import React, { useContext } from "react";+import DisabledTip from "../../components/global/DisabledTip";import styles from "../../styles/edit/_EditorNav.module.scss";import { ContentStateContext } from "../../context/ContentState";@@ -42,8 +43,18 @@ const EditorNav = () => {);};+ const hasPendingSelection =+ contentState.start !== 0 || contentState.end !== 1;++ const hasEdits =+ !contentState.backupBlob || contentState.blob !== contentState.backupBlob;++ const saveBlocked = hasPendingSelection && !contentState.isFfmpegRunning;+const saveChanges = async () => {- if (contentState.isFfmpegRunning) return;+ if (contentState.isFfmpegRunning || hasPendingSelection || !hasEdits) {+ return;+ }setContentState((prev) => ({...prev,@@ -92,15 +103,22 @@ const EditorNav = () => {{chrome.i18n.getMessage("sandboxEditorRevertButton")}</button>- <button- className="button primaryButton"- onClick={saveChanges}- disabled={contentState.isFfmpegRunning}+ <DisabledTip+ active={saveBlocked}+ content={chrome.i18n.getMessage("sandboxEditorSelectionPendingHint")}>- {contentState.reencoding- ? chrome.i18n.getMessage("sandboxEditorSaveProgressButton")- : chrome.i18n.getMessage("sandboxEditorSaveButton")}- </button>+ <button+ className="button primaryButton"+ onClick={saveChanges}+ disabled={+ contentState.isFfmpegRunning || hasPendingSelection || !hasEdits+ }+ >+ {contentState.reencoding+ ? chrome.i18n.getMessage("sandboxEditorSaveProgressButton")+ : chrome.i18n.getMessage("sandboxEditorSaveButton")}+ </button>+ </DisabledTip></div></div></div>diff --git a/src/pages/EditorApp/styles/edit/_EditorNav.module.scss b/src/pages/EditorApp/styles/edit/_EditorNav.module.scssindex dd28ebd..3434c62 100644--- a/src/pages/EditorApp/styles/edit/_EditorNav.module.scss+++ b/src/pages/EditorApp/styles/edit/_EditorNav.module.scss@@ -67,3 +67,19 @@display: none;}}++.saveWrap {+ display: inline-flex;+}+.tooltip {+ max-width: 240px;+ padding: 8px 13px;+ border-radius: 12px;+ background-color: $color-text-primary;+ color: $color-text-contrast;+ font-family: $font-medium;+ font-size: 12px;+ line-height: 1.4;+ user-select: none;+ z-index: $z-index-max;+}diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex 9d1cfea..21c7cc0 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -169,6 +169,7 @@ const Recorder = () => {const pendingStartAfterRestart = useRef(false);const recordingGeneration = useRef(0);const isFinishing = useRef(false);+ const stopPromiseRef = useRef(null);const sentLast = useRef(false);const lastTimecode = useRef(0);const hasChunks = useRef(false);@@ -351,6 +352,7 @@ const Recorder = () => {const lastEstimateAt = useRef(0);const ESTIMATE_INTERVAL_MS = 5000;+ const ESTIMATE_TIMEOUT_MS = 5000;const MIN_HEADROOM = 25 * 1024 * 1024;// Aborting still writes a tail chunk and finalizes, so the reserve has to// cover the bytes in flight, not just a flat floor. No-op for WebCodecs@@ -407,7 +409,17 @@ const Recorder = () => {lastEstimateAt.current = now;try {- const { usage = 0, quota = 0 } = await navigator.storage.estimate();+ // A hung estimate() would freeze the serialized write chain, so bound it.+ let estimateTimer = null;+ const { usage = 0, quota = 0 } = await Promise.race([+ navigator.storage.estimate(),+ new Promise((_, reject) => {+ estimateTimer = setTimeout(+ () => reject(new Error("storage-estimate-timeout")),+ ESTIMATE_TIMEOUT_MS,+ );+ }),+ ]).finally(() => clearTimeout(estimateTimer));estimateFailed.current = false;const remaining = quota - usage;const reserve = Math.max(@@ -435,6 +447,17 @@ const Recorder = () => {}return ok;} catch (err) {+ if (String(err?.message || err).includes("storage-estimate-timeout")) {+ // Slow, not low: keep recording and retry on the next chunk.+ chrome.runtime+ .sendMessage({+ type: "diag-forward",+ event: "recorder-storage-estimate-timeout",+ data: { savedCount: savedCount.current },+ })+ .catch(() => {});+ return !lowStorageAbort.current;+ }// No quota info: caller bails ("stop recording" beats QuotaExceeded mid-write).debugWarn("navigator.storage.estimate() failed, treating as low-storage", err);estimateFailed.current = true;@@ -1741,13 +1764,16 @@ const Recorder = () => {// fire-and-forget, waitForDrain only covers MediaRecorder, so onFinalized// could race ahead of slicing. Chain handleChunks and await in onFinalized.let webcodecsWriteChain = Promise.resolve();+ let webcodecsWritesQueued = 0;+ let webcodecsWritesAbandoned = false;+ let webcodecsProgressDiagAt = Date.now();const handleChunk = async (data, timestampMs) => {if (runGeneration !== recordingGeneration.current) {return;}if (useWebCodecs.current) {- if (lowStorageAbort.current) return;+ if (lowStorageAbort.current || webcodecsWritesAbandoned) return;// fMP4 fragments stream in (~1MB each, coalesced upstream); concatenated// they form a valid fMP4 playable directly in <video> and re-muxable later.@@ -1853,9 +1879,12 @@ const Recorder = () => {fileName: err.fileName,};try {- await chrome.storage.local.set({- lastRecordingBackendRef: chunkBackendRef.current,- });+ await Promise.race([+ chrome.storage.local.set({+ lastRecordingBackendRef: chunkBackendRef.current,+ }),+ new Promise((r) => setTimeout(r, 3000)),+ ]);} catch {}}const toastMessage = isOpfsWriterDead@@ -2072,9 +2101,45 @@ const Recorder = () => {}const endDrain = perfSpan("Recorder.onFinalized.waitForDrain");await waitForDrain();- try {- await webcodecsWriteChain;- } catch {}+ // Wait for queued fragments while they keep landing; give up only after a long+ // stall, so a recovering writer finishes the whole take.+ {+ let chainSettled = false;+ webcodecsWriteChain+ .catch(() => {})+ .then(() => {+ chainSettled = true;+ });+ const waitStart = Date.now();+ let lastProgressAt = waitStart;+ let lastSaved = savedCount.current;+ while (!chainSettled) {+ await new Promise((r) => setTimeout(r, 100));+ const nowMs = Date.now();+ if (savedCount.current !== lastSaved) {+ lastSaved = savedCount.current;+ lastProgressAt = nowMs;+ }+ if (+ nowMs - lastProgressAt > 30000 ||+ nowMs - waitStart > 240000+ ) {+ webcodecsWritesAbandoned = true;+ chrome.runtime+ .sendMessage({+ type: "diag-forward",+ event: "recorder-write-chain-stalled",+ data: {+ queued: webcodecsWritesQueued,+ savedCount: savedCount.current,+ waitedMs: nowMs - waitStart,+ },+ })+ .catch(() => {});+ break;+ }+ }+ }endDrain();// Close before validating: OPFS holds an exclusive handle until close.if (chunkWriter.current) {@@ -2093,6 +2158,25 @@ const Recorder = () => {chunkCount: closeResult?.chunkCount,});}+ // All muxer bytes go through the write chain, so a shortfall means fragments were lost before disk.+ if (+ typeof payload?.muxerBytes === "number" &&+ typeof closeResult?.byteSize === "number" &&+ payload.muxerBytes !== closeResult.byteSize+ ) {+ chrome.runtime+ .sendMessage({+ type: "diag-forward",+ event: "recorder-write-shortfall",+ data: {+ muxerBytes: payload.muxerBytes,+ byteSize: closeResult.byteSize,+ queued: webcodecsWritesQueued,+ abandoned: webcodecsWritesAbandoned,+ },+ })+ .catch(() => {});+ }// Recorder's view of the finalized artifact + editor's backend.// Pairs with opfs-close-ok/fail to locate header-only files.chrome.runtime@@ -2261,9 +2345,31 @@ const Recorder = () => {timestampMs,});}+ webcodecsWritesQueued += 1;+ // Producer-side, so a stalled save still reports (queued climbs, saved stays flat).+ const progressNow = Date.now();+ // The session log keeps only 100 events: healthy takes report rarely, a backed-up queue each minute.+ const progressEveryMs = webcodecsWritesQueued >= 5 ? 60000 : 300000;+ if (progressNow - webcodecsProgressDiagAt >= progressEveryMs) {+ webcodecsProgressDiagAt = progressNow;+ chrome.runtime+ .sendMessage({+ type: "diag-forward",+ event: "recorder-save-progress",+ data: {+ savedCount: savedCount.current,+ queued: webcodecsWritesQueued,+ timestampMs,+ },+ })+ .catch(() => {});+ }webcodecsWriteChain = webcodecsWriteChain.catch(() => {})- .then(() => handleChunk(blob, timestampMs));+ .then(() => handleChunk(blob, timestampMs))+ .finally(() => {+ webcodecsWritesQueued -= 1;+ });},onError: (err) => {debugError("WebCodecsRecorder error", err);@@ -3258,7 +3364,20 @@ const Recorder = () => {} catch {}};- async function stopRecording() {+ function stopRecording() {+ const wasFinishing = isFinishing.current;+ const run = runStopRecording();+ if (!wasFinishing) {+ stopPromiseRef.current = run;+ const clear = () => {+ if (stopPromiseRef.current === run) stopPromiseRef.current = null;+ };+ run.then(clear, clear);+ }+ return run;+ }++ async function runStopRecording() {localStopInitiated.current = true;if (isFinishing.current) {debugWarn("stopRecording() called while already finishing");@@ -3897,7 +4016,20 @@ const Recorder = () => {debug("getDisplayMedia screen constraints", displayConstraints);slLog("getDisplayMedia-start");let stream;- const endGdm = perfSpan("Recorder getDisplayMedia(screen)");+ const endGdmSpan = perfSpan("Recorder getDisplayMedia(screen)");+ // Timer drift while the picker and capture start run: a starved machine+ // shows up here, a hung capture API does not.+ let maxLagMs = 0;+ let lastLagTick = performance.now();+ const lagTimer = setInterval(() => {+ const now = performance.now();+ maxLagMs = Math.max(maxLagMs, now - lastLagTick - 200);+ lastLagTick = now;+ }, 200);+ const endGdm = (meta) => {+ clearInterval(lagTimer);+ endGdmSpan({ ...meta, maxLagMs: Math.round(maxLagMs) });+ };const acquireDisplay = (constraints) =>acquireDisplayMediaWithFocusRetry({getDisplayMedia: (c) => navigator.mediaDevices.getDisplayMedia(c),@@ -3907,7 +4039,20 @@ const Recorder = () => {});try {try {- stream = await acquireDisplay(displayConstraints);+ try {+ stream = await acquireDisplay(displayConstraints);+ } catch (err) {+ if (err?.name !== "OverconstrainedError") throw err;+ // Some Windows setups reject the size ceiling. Re-pick without it+ // and encode at the tier size instead.+ debugWarn("Display size constraints rejected, re-picking", err);+ captureCapRef.current = { width, height, oversampled: false };+ displayConstraints.video = {+ frameRate: displayConstraints.video.frameRate,+ displaySurface: "monitor",+ };+ stream = await acquireDisplay(displayConstraints);+ }} catch (err) {// The audio rejection takes the video with it. getDisplayMedia only// fails after the user has picked, so the retry costs a second pick.@@ -3937,10 +4082,17 @@ const Recorder = () => {});} catch (err) {endGdm({ error: String(err?.message || err).slice(0, 80) });+ const errMessage = String(err?.message || "").toLowerCase();+ // Chrome also throws AbortError for a pick that never started+ // ("Timeout starting video source"); that is a failure, not a dismissal.+ const sourceStartFailed =+ err?.name === "AbortError" &&+ /timeout|starting video source|failed to start/.test(errMessage);const cancelled =- err?.name === "NotAllowedError" ||- err?.name === "AbortError" ||- String(err?.message || "").toLowerCase().includes("permission denied");+ !sourceStartFailed &&+ (err?.name === "NotAllowedError" ||+ err?.name === "AbortError" ||+ errMessage.includes("permission denied"));debugWarn("getDisplayMedia screen capture failed", err);resetGateState();sendRecordingError(@@ -5104,7 +5256,16 @@ const Recorder = () => {}// Don't stop capture tracks here: it raced a slow start (isRecording// not yet flipped, tracks live) and killed the screen track mid-start.- await new Promise((resolve) => setTimeout(resolve, 1000));+ if (shouldFinalize && stopPromiseRef.current) {+ // An in-flight stop (e.g. the timer alarm) makes the call above a no-op;+ // ack after its finalize, within the timeout.+ await Promise.race([+ stopPromiseRef.current.catch(() => {}),+ new Promise((resolve) => setTimeout(resolve, timeoutMs)),+ ]);+ } else {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ }} catch (err) {console.warn("[Recorder] offscreen-shutdown error", err);} finally {diff --git a/src/pages/Recorder/encoderPrewarm.js b/src/pages/Recorder/encoderPrewarm.jsindex 870fe78..13aef83 100644--- a/src/pages/Recorder/encoderPrewarm.js+++ b/src/pages/Recorder/encoderPrewarm.js@@ -23,6 +23,22 @@ import {} from "./webcodecs/startupFlags";let _activeWarmer = null;+let _lastHwError = null;+const PREWARM_HW_ERROR_TTL_MS = 60_000;++// An explicit hardware-encoder error from the prewarm, if recent. Only an+// error counts: a prewarm that merely ended with no chunks is not evidence.+export const getRecentPrewarmHwError = ({ width, height } = {}) => {+ if (!_lastHwError) return null;+ if (_lastHwError.width !== width || _lastHwError.height !== height) {+ return null;+ }+ if (performance.now() - _lastHwError.at > PREWARM_HW_ERROR_TTL_MS) {+ _lastHwError = null;+ return null;+ }+ return _lastHwError.name;+};const computeFramerate = (config) => {const fps = Number(config?.framerate);@@ -167,6 +183,7 @@ export const startEncoderPrewarm = async (cfg) => {state.encoder = new VideoEncoder({output: (chunk, meta) => {state.chunks += 1;+ _lastHwError = null;if (!state.warmDecoderConfig && meta?.decoderConfig) {state.warmDecoderConfig = meta.decoderConfig;}@@ -177,6 +194,12 @@ export const startEncoderPrewarm = async (cfg) => {state.errorSink(err);return;}+ _lastHwError = {+ at: performance.now(),+ name: String(err?.name || "error").slice(0, 40),+ width: cfg.width,+ height: cfg.height,+ };perfMark("Recorder.encoderPrewarm.encoderError", {msg: String(err?.message || err).slice(0, 120),});@@ -214,8 +237,12 @@ export const startEncoderPrewarm = async (cfg) => {i === 0,);}+ // close() drops queued frames, so close before the flush lands warms nothing.try {- state.encoder.flush().catch(() => {});+ await Promise.race([+ state.encoder.flush().catch(() => {}),+ new Promise((resolve) => setTimeout(resolve, 1500)),+ ]);} catch {}await handle.close();endStart({ chunks: state.chunks, ok: state.chunks > 0, mode: "burst" });diff --git a/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js b/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.jsindex cd86ce1..28c4665 100644--- a/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js+++ b/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js@@ -15,6 +15,11 @@ const CLOSE_TIMEOUT_BASE_MS = 30000;const CLOSE_TIMEOUT_PER_GB_MS = 30000;const CLOSE_TIMEOUT_MAX_MS = 180000;const ABORT_TIMEOUT_MS = 10000;+// A hung or crashed worker is replaced and the write retried on the same file.+const MAX_WRITER_RECOVERIES = 3;+// Recoveries are per stall episode: a long take on a slow disk can see several+// unrelated hiccups, so the budget refills after this many clean writes.+const HEALTHY_WRITES_TO_REFILL = 30;// Used by Recorder.jsx's handleChunk to detect OPFS writer failure.export const OPFS_WRITER_FAILED_CODE = "opfs-writer-failed";@@ -43,6 +48,26 @@ export class OpfsChunkWriter {// file state past the failure point is unknown.this._dead = false;this._deathError = null;+ this._recoveries = 0;+ this._healthyWrites = 0;+ }++ _isRecoverable(err) {+ return err?.errorName === "TimeoutError" || err?.errorName === "WorkerError";+ }++ _abandonWorker(err) {+ if (this.worker) {+ try {+ this.worker.terminate();+ } catch {}+ this.worker = null;+ }+ for (const [, entry] of this.pending) {+ if (entry.timeoutId) clearTimeout(entry.timeoutId);+ entry.reject(err);+ }+ this.pending.clear();}_markDead(err) {@@ -90,7 +115,11 @@ export class OpfsChunkWriter {this.worker.onerror = (e) => {const err = new Error(String(e?.message || "opfs-worker-crashed"));err.errorName = "WorkerError";- this._markDead(err);+ if (this._fileName && this._recoveries < MAX_WRITER_RECOVERIES) {+ this._abandonWorker(err);+ } else {+ this._markDead(err);+ }};}@@ -111,9 +140,24 @@ export class OpfsChunkWriter {`opfs-${message.type}-timeout after ${timeout}ms`,);timeoutErr.errorName = "TimeoutError";- this._markDead(timeoutErr);+ if (+ message.type === "write" &&+ this._recoveries < MAX_WRITER_RECOVERIES+ ) {+ this._abandonWorker(timeoutErr);+ reject(timeoutErr);+ } else {+ this._markDead(timeoutErr);+ reject(this._deathError);+ }}}, timeout);+ // E2E seam: swallow N writes so the worker never answers, like a hang.+ const g = /** @type {any} */ (globalThis);+ if (message.type === "write" && g.__screenityDropOpfsWrites > 0) {+ g.__screenityDropOpfsWrites -= 1;+ return;+ }this.worker.postMessage({ ...message, requestId });});}@@ -155,14 +199,80 @@ export class OpfsChunkWriter {}// index/timestamp accepted to match IdbChunkWriter; OPFS is ordered// by write position so they aren't stored.- const resp = await this._request({- type: "write",- chunk,- index,- timestamp,+ for (;;) {+ if (this._closed || this._aborted) {+ throw new Error("opfs-chunk-writer-closed");+ }+ try {+ // An onerror between writes leaves no worker; recover before posting.+ if (!this.worker && this._fileName && !this._dead) {+ if (this._recoveries >= MAX_WRITER_RECOVERIES) {+ this._markDead(new Error("opfs-worker-missing"));+ throw this._deathError;+ }+ await this._recover(new Error("opfs-worker-missing"));+ }+ const resp = await this._request({+ type: "write",+ chunk,+ index,+ timestamp,+ });+ this._byteSize = resp.totalSize ?? this._byteSize;+ this._chunkCount += 1;+ this._healthyWrites += 1;+ if (+ this._recoveries > 0 &&+ this._healthyWrites >= HEALTHY_WRITES_TO_REFILL+ ) {+ this._recoveries = 0;+ }+ return;+ } catch (err) {+ if (this._dead || !this._isRecoverable(err)) throw err;+ if (this._recoveries >= MAX_WRITER_RECOVERIES) {+ this._markDead(err);+ throw this._deathError;+ }+ await this._recover(err);+ }+ }+ }++ // Replace the worker and resume at the last acknowledged byte. The retried+ // write then lands exactly where the failed one started.+ async _recover(cause) {+ if (this._closed || this._aborted) {+ throw new Error("opfs-chunk-writer-closed");+ }+ this._recoveries += 1;+ this._healthyWrites = 0;+ opfsDiag("recovering", {+ attempt: this._recoveries,+ cause: String(cause?.message || cause).slice(0, 120),+ fileName: this._fileName,+ ackedBytes: this._byteSize,+ });+ this._abandonWorker(cause);+ this._attachWorker();+ try {+ await this._request(+ { type: "reopen", fileName: this._fileName, at: this._byteSize },+ OPEN_TIMEOUT_MS,+ );+ } catch (err) {+ this._markDead(err);+ throw this._deathError;+ }+ if (this._closed || this._aborted) {+ // close()/abort() raced the reopen; don't leave a second handle open.+ this._teardown();+ throw new Error("opfs-chunk-writer-closed");+ }+ opfsDiag("recovered", {+ attempt: this._recoveries,+ ackedBytes: this._byteSize,});- this._byteSize = resp.totalSize ?? this._byteSize;- this._chunkCount += 1;}async close() {@@ -190,7 +300,7 @@ export class OpfsChunkWriter {const resp = await this._request({ type: "close" }, closeTimeoutMs);const tAfterReq = (typeof performance !== "undefined" ? performance.now() : Date.now());this._byteSize = resp.byteSize ?? this._byteSize;- this._chunkCount = resp.chunkCount ?? this._chunkCount;+ this._chunkCount = Math.max(this._chunkCount, resp.chunkCount ?? 0);this._fileName = resp.fileName || this._fileName;// Surface per-phase timings so a diag can attribute the 10s// close-stall we've seen on macOS: flush vs handle.close vs@@ -278,6 +388,11 @@ export class OpfsChunkWriter {} catch {}this.worker = null;}+ const closedErr = new Error("opfs-chunk-writer-closed");+ for (const [, entry] of this.pending) {+ if (entry.timeoutId) clearTimeout(entry.timeoutId);+ entry.reject(closedErr);+ }this.pending.clear();}}diff --git a/src/pages/Recorder/recorderStorage/opfs/writerWorker.js b/src/pages/Recorder/recorderStorage/opfs/writerWorker.jsindex 62f766c..298701f 100644--- a/src/pages/Recorder/recorderStorage/opfs/writerWorker.js+++ b/src/pages/Recorder/recorderStorage/opfs/writerWorker.js@@ -39,8 +39,10 @@ const post = (payload) => {// crbug/453704691: createSyncAccessHandle can throw NoModificationAllowedError// briefly while GC reclaims a prior handle. Retry with backoff before failing.-const openSyncAccessHandleWithRetry = async (handle) => {- const delaysMs = [0, 200, 400, 600, 800];+const openSyncAccessHandleWithRetry = async (+ handle,+ delaysMs = [0, 200, 400, 600, 800],+) => {let lastErr = null;for (let i = 0; i < delaysMs.length; i += 1) {if (delaysMs[i] > 0) {@@ -76,6 +78,28 @@ const openFile = async (recordingId, extension, keepNames = []) => {return { fileName: name };};+// Resume on the same file after a hung worker was replaced. Truncating to the last+// acknowledged size drops any half-landed write, keeping the stream contiguous.+const reopenFile = async (name, at) => {+ const dir = await navigator.storage.getDirectory();+ const handle = await dir.getFileHandle(name);+ const sync = await openSyncAccessHandleWithRetry(+ handle,+ [0, 200, 400, 800, 1600, 3200, 3200],+ );+ if (sync.getSize() < at) {+ sync.close();+ throw new Error("opfs-reopen-file-shorter-than-acked");+ }+ sync.truncate(at);+ fileName = name;+ syncHandle = sync;+ offset = at;+ closed = false;+ devLog("reopen", { fileName: name, at });+ return { fileName: name };+};+const writeChunk = async (blob) => {if (closed) throw new Error("opfs-writer-closed");if (!syncHandle) throw new Error("opfs-writer-not-open");@@ -183,6 +207,23 @@ self.onmessage = (e) => {return;}+ if (msg.type === "reopen") {+ enqueue(async () => {+ try {+ const { fileName: fn } = await reopenFile(msg.fileName, msg.at);+ post({ type: "ready", requestId: msg.requestId, ok: true, fileName: fn });+ } catch (err) {+ post({+ type: "ready",+ requestId: msg.requestId,+ ok: false,+ ...errorPayload(err),+ });+ }+ });+ return;+ }+if (msg.type === "write") {enqueue(async () => {try {diff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.jsindex efa7cd5..f8c64ac 100644--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js@@ -45,7 +45,7 @@ import {} from "./startLeadIn";import { avcCodecForSize, exceedsAvcL42 } from "../../../media/avcLevel";import { RESOLUTION_UNSUPPORTED_CODE } from "../../../media/fastRecorderGate";-import { claimPrewarmedEncoder } from "../encoderPrewarm";+import { claimPrewarmedEncoder, getRecentPrewarmHwError } from "../encoderPrewarm";// Lazy-load Mp4MuxerWrapper so its ~3MB mediabunny static import doesn't// drag into recorder.bundle.js cold start (dominates click-record latency).let _mp4MuxerWrapperPromise = null;@@ -246,6 +246,8 @@ export class WebCodecsRecorder {this._startupWindowClosed = false;this._startupCaughtUpRun = 0;this._startupFirstFrameAt = null;+ this._heldFirstFrame = null;+ this._firstFrameVetted = false;this._startupFramesSeen = 0;this._startupBufferEngaged = false;this._framesBufferedAtStart = 0;@@ -269,6 +271,11 @@ export class WebCodecsRecorder {: STARTUP_HARD_FRAME_LIMIT;this._adoptedPrewarmEncoder = false;this._adoptedDecoderConfig = null;+ this._encErrDecisions = [];+ this._closedEncoderDrops = 0;+ this._closedEncoderRebuilds = 0;+ this._closedRebuildTried = false;+ this._firstFedAt = null;this._forceNextKeyframe = false;this._droppedForBackpressureCount = 0;// 100, not 10. At ~10-25ms per chunk, 10 was ~100-200ms of headroom against@@ -382,6 +389,7 @@ export class WebCodecsRecorder {// slots, not frames. Tells a quiet source from a loop discarding frames.this._framesDroppedAheadOfClock = 0;this._framesSkippedForGap = 0;+ this._heldGapSamples = 0;// Black placeholder frames synthesized before the first real frame to// bridge macOS static-screen first-frame starvation (see readVideoLoop).this._syntheticFirstFrameCount = 0;@@ -495,6 +503,13 @@ export class WebCodecsRecorder {// reused instance can salvage again on a second recording.this._didSwRetry = false;this._swRetryReason = null;+ this._encErrDecisions = [];+ this._closedEncoderDrops = 0;+ this._closedEncoderRebuilds = 0;+ this._closedRebuildTried = false;+ this._framesFed = 0;+ this._firstFedAt = null;+ this._videoCodecConfigsTried = [];this._hiddenRearmCount = 0;this._lastChunkAt = null;// A reused instance gets a fresh muxer, so neither latch may carry over.@@ -505,6 +520,8 @@ export class WebCodecsRecorder {this._startupWindowClosed = false;this._startupCaughtUpRun = 0;this._startupFirstFrameAt = null;+ this._heldFirstFrame = null;+ this._firstFrameVetted = false;this._startupFramesSeen = 0;this._startupBufferEngaged = false;this._framesBufferedAtStart = 0;@@ -517,6 +534,7 @@ export class WebCodecsRecorder {this._pendingAudioRead = null;this._framesDroppedAheadOfClock = 0;this._framesSkippedForGap = 0;+ this._heldGapSamples = 0;this._droppedForBackpressureCount = 0;this._droppedAudioForBackpressureCount = 0;this._peakVideoEncodeQueueSize = 0;@@ -1061,6 +1079,7 @@ export class WebCodecsRecorder {keyFrame: false,});this._framesFed += 1;+ if (this._firstFedAt == null) this._firstFedAt = performance.now();} finally {hold.close();}@@ -1202,6 +1221,7 @@ export class WebCodecsRecorder {// lastFailureCode names the cause on salvaged partials.await this.options.onFinalized({muxerFinalizeOk,+ muxerBytes: this.muxer?.getStats?.()?.totalEmittedBytes ?? null,framesEncoded: this.frameCount,firstChunkSeen: this._firstChunkSeen,droppedForBackpressure: {@@ -1426,10 +1446,14 @@ export class WebCodecsRecorder {staticFrameSyntheticCount: this._staticFrameSyntheticCount,framesDroppedAheadOfClock: this._framesDroppedAheadOfClock,framesSkippedForGap: this._framesSkippedForGap,+ heldGapSamples: this._heldGapSamples,trackStats: this._readTrackStats(),firstChunkLatencyMs,videoEncoderStateAtStop: this._videoEncoderStateAtStop,encoderConstructCount: this._encoderConstructCount,+ closedEncoderDrops: this._closedEncoderDrops,+ closedEncoderRebuilds: this._closedEncoderRebuilds,+ encoderErrorDecisions: this._encErrDecisions.slice(),lastWebCodecsFailureCode: this._lastFailureCode || null,};}@@ -1800,9 +1824,71 @@ export class WebCodecsRecorder {this._deviceChangeListener = null;}+ // Healthy starts emit within ~1.4s; a dead hardware encoder emits nothing until the+ // 12s watchdog. With nothing out by the early mark the picture is already frozen,+ // so a software rebuild costs nothing a wait would save. Hidden tabs are left to the watchdog.+ _armEarlyFirstChunkCheck(delayMs) {+ const earlyMs = Number.isFinite(this.options?.earlyFirstChunkMs)+ ? this.options.earlyFirstChunkMs+ : this._firstChunkWatchdogMs >= 8000+ ? 4000+ : 0;+ if (!(earlyMs > 0) || earlyMs >= this._firstChunkWatchdogMs) return;+ const minFedMs = Math.min(3000, earlyMs * 0.75);+ this._earlyFirstChunkTimer = setTimeout(() => {+ this._earlyFirstChunkTimer = null;+ if (+ !this.running ||+ this._stopping ||+ this.paused ||+ this.justResumed ||+ this._encodersClosedForPause ||+ this._firstChunkSeen ||+ this._didSwRetry ||+ this._failureReported ||+ !(this._framesFed > 0)+ ) {+ return;+ }+ // Measured from the first frame the encoder was given, so a late first+ // frame (static screen) does not make a healthy encoder look dead.+ const fedForMs = performance.now() - (this._firstFedAt ?? performance.now());+ if (fedForMs < minFedMs) {+ this._armEarlyFirstChunkCheck(minFedMs - fedForMs + 50);+ return;+ }+ if (+ typeof document !== "undefined" &&+ document.visibilityState === "hidden"+ ) {+ return;+ }+ const cfg = this._activeVideoConfig;+ if (!cfg || cfg.hardwareAcceleration === "prefer-software") return;+ this.warn("[WCR] no first chunk early; rebuilding prefer-software", {+ afterMs: earlyMs,+ });+ try {+ diagForward("recorder-no-first-chunk-sw-rebuild", {+ withinMs: earlyMs,+ early: true,+ });+ } catch {}+ if (this._rebuildVideoEncoder({ ...cfg, hardwareAcceleration: "prefer-software" })) {+ this._didSwRetry = true;+ this._swRetryReason = this._swRetryReason || "early-no-first-chunk";+ this._forceNextKeyframe = true;+ this._restartVideoTimelineBeforeFirstChunk();+ this._noteEncoderErrorDecision("early-rebuild");+ this._armFirstChunkWatchdog();+ }+ }, delayMs ?? earlyMs);+ }+_armFirstChunkWatchdog() {this._clearFirstChunkWatchdog();if (this._firstChunkSeen) return;+ this._armEarlyFirstChunkCheck();this._firstChunkWatchdog = setTimeout(() => {this._firstChunkWatchdog = null;if (!this.running || this._stopping || this._firstChunkSeen) return;@@ -1831,6 +1917,7 @@ export class WebCodecsRecorder {const isHwConfig =cfg &&(cfg.hardwareAcceleration === "prefer-hardware" ||+ cfg.hardwareAcceleration === "no-preference" ||!cfg.hardwareAcceleration);if (this.running &&@@ -1858,6 +1945,7 @@ export class WebCodecsRecorder {this._didSwRetry = true;this._swRetryReason = this._swRetryReason || "no-first-chunk";this._forceNextKeyframe = true;+ this._restartVideoTimelineBeforeFirstChunk();this._armFirstChunkWatchdog();return;}@@ -1875,6 +1963,10 @@ export class WebCodecsRecorder {}_clearFirstChunkWatchdog() {+ if (this._earlyFirstChunkTimer) {+ clearTimeout(this._earlyFirstChunkTimer);+ this._earlyFirstChunkTimer = null;+ }if (this._firstChunkWatchdog) {clearTimeout(this._firstChunkWatchdog);this._firstChunkWatchdog = null;@@ -2196,10 +2288,21 @@ export class WebCodecsRecorder {return;}- this.videoEncoder = new VideoEncoder({- output: videoEncoderOutput,- error: videoEncoderError,- });+ const newGuardedEncoder = () => {+ let enc = null;+ enc = new VideoEncoder({+ output: (chunk, meta) => {+ if (this.videoEncoder !== enc) return;+ videoEncoderOutput(chunk, meta);+ },+ error: (err) => {+ if (this.videoEncoder !== enc) return;+ videoEncoderError(err);+ },+ });+ return enc;+ };+ this.videoEncoder = newGuardedEncoder();this._encoderConstructCount += 1;// configure() can throw sync. retry hardware→software on quota/contention@@ -2245,10 +2348,7 @@ export class WebCodecsRecorder {try {this.videoEncoder.close();} catch {}- this.videoEncoder = new VideoEncoder({- output: videoEncoderOutput,- error: videoEncoderError,- });+ this.videoEncoder = newGuardedEncoder();this._encoderConstructCount += 1;};const isContention = (err) => {@@ -2527,12 +2627,14 @@ export class WebCodecsRecorder {// Re-entry guard: stop()'s flush during _finalizeOnFatal can fire// a second error from the same encoder.if (this._finalizingFromFatal) {+ this._noteEncoderErrorDecision("finalizing");return;}// Pause closed the encoder. Swallow the racing reclaim error;// resume() rebuilds from _activeVideoConfig.if (this._encodersClosedForPause && isReclaim) {+ this._noteEncoderErrorDecision("pause-swallow");return;}@@ -2558,6 +2660,7 @@ export class WebCodecsRecorder {this._reclaimRebuildThrottleMs,)) {+ this._noteEncoderErrorDecision("reclaim-throttled");return;}this._encoderReclaimCount += 1;@@ -2571,14 +2674,19 @@ export class WebCodecsRecorder {});if (this._rebuildVideoEncoder(this._activeVideoConfig)) {this._forceNextKeyframe = true;+ this._restartVideoTimelineBeforeFirstChunk();+ this._noteEncoderErrorDecision("reclaim-rebuild");return;}}const preFirstChunk = !this._firstChunkSeen;+ // no-preference can resolve to the hardware encoder, so a pre-first-chunk+ // error on that rung needs the same software retry as prefer-hardware.const isHwPreferred =this._activeVideoConfig &&(this._activeVideoConfig.hardwareAcceleration === "prefer-hardware" ||+ this._activeVideoConfig.hardwareAcceleration === "no-preference" ||!this._activeVideoConfig.hardwareAcceleration);if (preFirstChunk && canRecover && isHwPreferred && !this._didSwRetry) {this._didSwRetry = true;@@ -2593,11 +2701,23 @@ export class WebCodecsRecorder {};if (this._rebuildVideoEncoder(swConfig)) {this._forceNextKeyframe = true;+ this._restartVideoTimelineBeforeFirstChunk();+ this._noteEncoderErrorDecision("sw-retry-ok");return;}+ this._noteEncoderErrorDecision("sw-retry-failed");}this.err("[WCR] VideoEncoder error:", err);+ const decision = this._noteEncoderErrorDecision(+ "fell-to-onError",+ { canRecover: Boolean(canRecover), isHwPreferred: Boolean(isHwPreferred) },+ );+ try {+ if (err && typeof err === "object" && !err.detail) {+ err.detail = { decision };+ }+ } catch {}// Fatal mid-recording with chunks on disk. Run stop() so the muxer// writes moov, then surface the error tagged finalized for salvage.@@ -2682,6 +2802,74 @@ export class WebCodecsRecorder {this.options.onError?.(err);}+ // The first sample (held from 0 to the first frame's slot) can die with its encoder.+ // The muxer rebases video to its first chunk, so a replacement starting at a later+ // slot drops the lead-in and plays video early against the padded audio. Re-feed from slot 0.+ _restartVideoTimelineBeforeFirstChunk() {+ if (this._firstChunkSeen || !this._videoStartUs || this.justResumed) return;+ this._videoFrameIndex = 0;+ this._videoLeadInPending = true;+ }++ // An encoder that closed itself before any chunk (the browser tore down a+ // failed hardware encoder) looks like a pause race and its frames are+ // dropped silently. Rebuild in software once; any other case keeps the drop.+ _rebuildClosedEncoderBeforeFirstChunk() {+ const cfg = this._activeVideoConfig;+ if (+ this.paused ||+ this._encodersClosedForPause ||+ !this.running ||+ this._stopping ||+ this._finalizingFromFatal ||+ this._firstChunkSeen ||+ this._didSwRetry ||+ this._closedRebuildTried ||+ !cfg ||+ !this._videoEncoderOutputHandler ||+ !this._videoEncoderErrorHandler ||+ cfg.hardwareAcceleration === "prefer-software"+ ) {+ return false;+ }+ this._closedRebuildTried = true;+ this.warn("[WCR] VideoEncoder closed before first chunk, retrying prefer-software");+ if (+ !this._rebuildVideoEncoder({ ...cfg, hardwareAcceleration: "prefer-software" })+ ) {+ this._noteEncoderErrorDecision("closed-rebuild-failed");+ return false;+ }+ this._didSwRetry = true;+ this._swRetryReason = "closed-encoder-pre-first-chunk";+ this._armFirstChunkWatchdog();+ this._closedEncoderRebuilds += 1;+ this._forceNextKeyframe = true;+ this._restartVideoTimelineBeforeFirstChunk();+ this._noteEncoderErrorDecision("closed-rebuild");+ return true;+ }++ _noteEncoderErrorDecision(branch, extra) {+ const hw = this._activeVideoConfig?.hardwareAcceleration;+ const bits = extra+ ? `${extra.canRecover ? 1 : 0}${extra.isHwPreferred ? 1 : 0}`+ : "";+ const token = [+ branch,+ bits,+ hw ? hw.replace("prefer-", "p").replace("no-preference", "np") : "",+ this._didSwRetry ? "sw" : "",+ this._adoptedPrewarmEncoder ? "warm" : "",+ `f${this._framesFed || 0}`,+ ]+ .filter(Boolean)+ .join("/");+ this._encErrDecisions.push(token);+ if (this._encErrDecisions.length > 5) this._encErrDecisions.shift();+ return token;+ }+// Fresh construct/configure with the same handlers. Error handler is// wrapped per-instance to drop late errors from the closed predecessor._rebuildVideoEncoder(config) {@@ -2691,7 +2879,10 @@ export class WebCodecsRecorder {try {let nextEncoder = null;nextEncoder = new VideoEncoder({- output: this._videoEncoderOutputHandler,+ output: (chunk, meta) => {+ if (this.videoEncoder !== nextEncoder) return;+ this._videoEncoderOutputHandler(chunk, meta);+ },error: (err) => {if (this.videoEncoder !== nextEncoder) return;this._videoEncoderErrorHandler(err);@@ -2701,6 +2892,9 @@ export class WebCodecsRecorder {nextEncoder.configure(config);this.videoEncoder = nextEncoder;this._activeVideoConfig = config;+ if (this._firstFedAt != null && !this._firstChunkSeen) {+ this._firstFedAt = performance.now();+ }return true;} catch (rebuildErr) {this.err("[WCR] VideoEncoder rebuild failed:", rebuildErr);@@ -2856,6 +3050,23 @@ export class WebCodecsRecorder {{ codec: "avc1.42E028", containerCodec: "avc", hw: "prefer-software" },];+ // The prewarm opens a hardware encoder at this same size moments earlier;+ // if that one errored, try the software rungs first.+ const prewarmHwError =+ this.containerKind === "webm"+ ? null+ : getRecentPrewarmHwError({ width, height });+ if (prewarmHwError) {+ candidates.sort(+ (x, y) =>+ Number(x.hw !== "prefer-software") - Number(y.hw !== "prefer-software"),+ );+ this._videoCodecConfigsTried.push({+ prewarmHwError,+ succeeded: false,+ });+ }+// Past L4.2's coded-area limit (or above 30fps) the level must rise, or// Chrome rejects the frame at encode time (configure() still passes).const oversize = exceedsAvcL42(width, height) || fps > 30;@@ -2868,9 +3079,12 @@ export class WebCodecsRecorder {// Use the normalized config from isConfigSupported so a clamp// Chrome would have applied doesn't trigger a SW fallback later.let supported = null;+ let supportedError = null;try {supported = await VideoEncoder.isConfigSupported(config);- } catch {}+ } catch (e) {+ supportedError = String(e?.name || "error").slice(0, 40);+ }// configure() reports an unsupported size asynchronously, so a rung// isConfigSupported refused would be selected and die with zero chunks.// Only large frames skip on it.@@ -2884,13 +3098,40 @@ export class WebCodecsRecorder {}const resolvedConfig =supported?.supported && supported.config ? supported.config : config;- const test = new VideoEncoder({ output() {}, error() {} });+ let probeError = supportedError;+ let asyncProbeError = null;+ const test = new VideoEncoder({+ output() {},+ error(e) {+ probeError = String(e?.name || "error").slice(0, 40);+ asyncProbeError = probeError;+ },+ });try {test.configure(resolvedConfig);+ // A hardware encoder that cannot be created reports it from the error+ // callback a few ms after a clean configure(); closing at once hid that.+ if (+ c.hw !== "prefer-software" &&+ candidate !== candidates[candidates.length - 1] &&+ !(this.options?.skipProbeSettle === true)+ ) {+ await new Promise((r) => setTimeout(r, 60));+ if (asyncProbeError || test.state === "closed") {+ this._videoCodecConfigsTried.push({+ codec: c.codec,+ hw: c.hw,+ succeeded: false,+ probeError: probeError || "closed",+ });+ continue;+ }+ }this._videoCodecConfigsTried.push({codec: c.codec,hw: c.hw,succeeded: true,+ ...(probeError ? { probeError } : {}),});this.log("[WCR] Selected encoder:", c.codec, c.hw);try {@@ -2917,6 +3158,7 @@ export class WebCodecsRecorder {codec: c.codec,hw: c.hw,succeeded: false,+ probeError: String(e?.name || "error").slice(0, 40),});} finally {try { test.close(); } catch {}@@ -3003,6 +3245,245 @@ export class WebCodecsRecorder {this._videoLeadInPending = true;}+ // A real frame N slots late used to be copied into all N slots, stamping the new+ // picture before it existed. Those slots belong to the previous picture, so encode+ // it while the canvas still shows it. Skipped where start, lead-in and resume own the timeline.+ _encodeHeldGap() {+ if (+ !this._videoStartUs ||+ this._videoLeadInPending ||+ this.justResumed ||+ this.paused ||+ this.frameCount === 0 ||+ !this.videoEncoder+ ) {+ return;+ }+ const frameDurationUs = this._frameDurationUs || Math.round(1_000_000 / 30);+ const elapsedUs = Math.max(+ 0,+ performance.now() * 1000 -+ this._videoStartUs -+ (this.totalPausedDurationUs || 0),+ );+ const targetIndex = Math.floor(elapsedUs / frameDurationUs);+ const startIndex = this._videoFrameIndex;+ if (targetIndex <= startIndex) return;+ const encodedBefore = this.frameCount;+ // Ordinary lateness keeps one sample per slot; only a real stall is one long hold.+ if (targetIndex - startIndex <= 8) {+ this._encodeVideoSlots({+ startIndex,+ frameDurationUs,+ targetIndex: targetIndex - 1,+ });+ } else {+ this._encodeVideoSlots({+ startIndex,+ holdUntilIndex: targetIndex - 1,+ frameDurationUs,+ targetIndex,+ });+ }+ if (this.frameCount > encodedBefore) this._heldGapSamples += 1;+ }++ // Encodes grid slots startIndex..targetIndex off the resize canvas as it stands. With+ // holdUntilIndex, one sample at startIndex lasting through it (start lead-in, long holds).+ _encodeVideoSlots({+ startIndex,+ holdUntilIndex,+ frameDurationUs,+ targetIndex,+ }) {+ const endIndex = holdUntilIndex != null ? startIndex : targetIndex;+ for (let i = startIndex; i <= endIndex; i += 1) {+ const tsUs = i * frameDurationUs;++ // Track the peak observed queue depth as a leading indicator+ //; useful for tuning the threshold from real telemetry.+ // Closed-encoder pause race: treat as drained.+ let vQueueSize = 0;+ try {+ vQueueSize = this.videoEncoder?.encodeQueueSize ?? 0;+ } catch {+ vQueueSize = 0;+ }+ if (vQueueSize > this._peakVideoEncodeQueueSize) {+ this._peakVideoEncodeQueueSize = vQueueSize;+ }++ // Startup grace window: while the encoder ramps, buffer instead of+ // dropping. Frames carry wall-clock PTS, so they encode late but the+ // file stays complete. Latches to the steady cap once it closes.+ let effectiveQueueCap = this._encoderMaxQueueSize;+ if (!this._startupWindowClosed) {+ if (this._startupFirstFrameAt === null) {+ this._startupFirstFrameAt = performance.now();+ }+ this._startupFramesSeen += 1;+ if (vQueueSize <= STARTUP_CAUGHT_UP_QUEUE) {+ this._startupCaughtUpRun += 1;+ } else {+ this._startupCaughtUpRun = 0;+ }+ effectiveQueueCap = computeEffectiveQueueCap({+ framesSinceStart: this._startupFramesSeen,+ elapsedMs: performance.now() - this._startupFirstFrameAt,+ caughtUp: this._startupCaughtUpRun >= STARTUP_CAUGHT_UP_RUN,+ steadyCap: this._encoderMaxQueueSize,+ startupCap: this._startupMaxQueueSize,+ hardFrameLimit: this._startupHardFrameLimit,+ hardMs: this._startupHardMs,+ disabled: getStartupFlags().startupBufferDisabled,+ });+ if (effectiveQueueCap <= this._encoderMaxQueueSize) {+ this._startupWindowClosed = true;+ effectiveQueueCap = this._encoderMaxQueueSize;+ } else if (+ vQueueSize > this._encoderMaxQueueSize &&+ vQueueSize <= effectiveQueueCap+ ) {+ // Counts only frames the wider cap actually saves (above the+ // steady cap, still inside the grace cap). Counting ones that+ // drop anyway would overstate the fix in telemetry.+ this._startupBufferEngaged = true;+ this._framesBufferedAtStart += 1;+ }+ }++ // Backpressure: drop the frame and force a keyframe next so+ // the stream stays decodable. An unbounded queue can stop+ // emitting chunks entirely.+ if (vQueueSize > effectiveQueueCap) {+ this._droppedForBackpressureCount += 1;+ this._forceNextKeyframe = true;+ // A dropped lead-in hold leaves index 0 for the retry.+ if (holdUntilIndex == null) this._videoFrameIndex = i + 1;+ continue;+ }++ const resized = new VideoFrame(this.resizeCanvas, {+ timestamp: tsUs,+ duration:+ holdUntilIndex != null+ ? (holdUntilIndex + 1 - i) * frameDurationUs+ : frameDurationUs,+ });++ const keyFrame =+ i === 0 ||+ (this.justResumed && i === startIndex) ||+ this._forceNextKeyframe === true ||+ i - this._lastKeyFrameIndex >= this._keyFrameIntervalFrames;+ if (keyFrame) {+ this._lastKeyFrameIndex = i;+ this._forceNextKeyframe = false;+ }+ if (this.justResumed && i === startIndex) {+ this.justResumed = false;+ }++ // pause() can close the encoder between the top-of-loop check+ // and here. Drop the frame instead of bubbling a sync throw.+ if (+ this.paused ||+ !this.videoEncoder ||+ this.videoEncoder.state === "closed"+ ) {+ this._closedEncoderDrops += 1;+ resized.close();+ if (this._rebuildClosedEncoderBeforeFirstChunk()) break;+ if (holdUntilIndex == null) this._videoFrameIndex = i + 1;+ this._forceNextKeyframe = true;+ continue;+ }+ // try/finally so resized's GPU buffer closes on every exit+ // (pause-race continue, rethrown encoder error, success).+ try {+ try {+ this.videoEncoder.encode(resized, {+ timestamp: tsUs,+ keyFrame,+ });+ this._framesFed += 1;+ if (this._firstFedAt == null) this._firstFedAt = performance.now();+ } catch (encErr) {+ // Same race after the check. Only swallow when paused+ // so real encoder errors still surface.+ if (+ this.paused ||+ this.videoEncoder?.state === "closed"+ ) {+ this.warn("[WCR] encode() race during pause; dropping frame");+ this._closedEncoderDrops += 1;+ if (this._rebuildClosedEncoderBeforeFirstChunk()) break;+ if (holdUntilIndex == null) this._videoFrameIndex = i + 1;+ this._forceNextKeyframe = true;+ continue;+ }+ // QuotaExceededError means a full queue (Chrome 140+ backpressure,+ // drop the frame) or a reclaimed encoder (near-empty queue). Route+ // the reclaim case to a rebuild, not a drop into a dead encoder.+ if (encErr?.name === "QuotaExceededError") {+ const q = this.videoEncoder?.encodeQueueSize ?? 0;+ // A near-empty queue only meant reclaim while the cap was 4;+ // at 16 a real reclaim looks like backpressure and silently+ // skips the rebuild. Chrome names reclaims in the message.+ if (isReclaimErrorMessage(encErr) || q <= 5) {+ if (holdUntilIndex == null) this._videoFrameIndex = i + 1;+ this._forceNextKeyframe = true;+ this.warn(+ "[WCR] encode() QuotaExceededError with near-empty queue; treating as encoder reclaim, rebuilding",+ { queue: q },+ );+ this._handleVideoEncoderError(encErr, true);+ continue;+ }+ this._droppedForBackpressureCount += 1;+ this._forceNextKeyframe = true;+ if (holdUntilIndex == null) this._videoFrameIndex = i + 1;+ this.warn(+ "[WCR] encode() QuotaExceededError; dropping frame as backpressure",+ );+ continue;+ }+ throw encErr;+ }+ if (+ this.debug &&+ (this.frameCount < 5 || this.frameCount % 300 === 0)+ ) {+ this.log("[WCR] video pts", {+ frame: this.frameCount,+ tsUs,+ durUs: frameDurationUs,+ targetIndex,+ });+ }+ // Diag snapshot every 30 frames. encodeQueueSize > 10 means+ // the encoder can't keep up.+ if (this.frameCount > 0 && this.frameCount % 30 === 0) {+ perfMark("WCR.frame.progress", {+ frame: this.frameCount,+ videoQ: this.videoEncoder?.encodeQueueSize ?? -1,+ audioQ: this.audioEncoder?.encodeQueueSize ?? -1,+ });+ }+ this.frameCount++;+ this._fpsWindows.tick(+ this.frameCount,+ performance.now() - (this.totalPausedDurationUs || 0) / 1000,+ );+ this._videoLeadInPending = false;+ this._videoFrameIndex =+ holdUntilIndex != null ? holdUntilIndex + 1 : i + 1;+ } finally {+ resized.close();+ }+ }+ }+async readVideoLoop() {this.log("[WCR] video loop start");if (!this.videoReader || !this.videoEncoder) return;@@ -3080,6 +3561,10 @@ export class WebCodecsRecorder {// emitting and the stall watchdog would misfire. Reuse the// last canvas on timeout to keep chunks flowing.const STATIC_FRAME_FALLBACK_MS = 1500;+ // A late-attached reader is first handed the track's cached picture,+ // which can predate the start (the picker, the countdown). A frame that+ // follows within this window means the held one was that leftover.+ const FIRST_FRAME_VET_MS = 250;// Hoisted, not re-issued per iteration. A read that loses the race// isn't cancelled: it stays queued and later eats a frame nobody// encodes or closes, so on a static screen every timeout costs the@@ -3095,7 +3580,7 @@ export class WebCodecsRecorder {}));}let fallbackTimer = null;- const readResult = await Promise.race([+ let readResult = await Promise.race([this._pendingVideoRead,new Promise((resolve) => {fallbackTimer = setTimeout(@@ -3105,7 +3590,9 @@ export class WebCodecsRecorder {value: null,isSyntheticTimeout: true,}),- STATIC_FRAME_FALLBACK_MS,+ this._heldFirstFrame+ ? FIRST_FRAME_VET_MS+ : STATIC_FRAME_FALLBACK_MS,);}),]);@@ -3115,6 +3602,17 @@ export class WebCodecsRecorder {if (fallbackTimer) clearTimeout(fallbackTimer);}+ // Nothing followed the held frame: a static screen, so it is the picture.+ if (readResult.isSyntheticTimeout && this._heldFirstFrame) {+ readResult = {+ done: false,+ value: this._heldFirstFrame,+ isSyntheticTimeout: false,+ };+ this._heldFirstFrame = null;+ this._firstFrameVetted = true;+ }+let isSynthetic = false;let frame = null;if (readResult.isSyntheticTimeout) {@@ -3158,6 +3656,18 @@ export class WebCodecsRecorder {}if (readResult.done || !readResult.value) break;frame = readResult.value;+ if (!this._videoStartUs && !this._firstFrameVetted) {+ if (this._heldFirstFrame) {+ try {+ this._heldFirstFrame.close();+ } catch {}+ this._heldFirstFrame = null;+ this._firstFrameVetted = true;+ } else {+ this._heldFirstFrame = frame;+ continue;+ }+ }this._framesFromMSTP += 1;// Drives the sleep-gap detection above.this._lastFrameArrivalAt = performance.now();@@ -3174,6 +3684,9 @@ export class WebCodecsRecorder {ensureResizeCanvas();+ // Must run before the draw: the canvas still holds the picture the late slots should show.+ this._encodeHeldGap();+this.drawFrameToResizeCanvas(frame);if (!this._videoStartUs) {@@ -3221,187 +3734,12 @@ export class WebCodecsRecorder {}const startIndex = this._videoFrameIndex;- const endIndex = holdUntilIndex != null ? startIndex : targetIndex;- for (let i = startIndex; i <= endIndex; i += 1) {- const tsUs = i * frameDurationUs;-- // Track the peak observed queue depth as a leading indicator- //; useful for tuning the threshold from real telemetry.- // Closed-encoder pause race: treat as drained.- let vQueueSize = 0;- try {- vQueueSize = this.videoEncoder?.encodeQueueSize ?? 0;- } catch {- vQueueSize = 0;- }- if (vQueueSize > this._peakVideoEncodeQueueSize) {- this._peakVideoEncodeQueueSize = vQueueSize;- }-- // Startup grace window: while the encoder ramps, buffer instead of- // dropping. Frames carry wall-clock PTS, so they encode late but the- // file stays complete. Latches to the steady cap once it closes.- let effectiveQueueCap = this._encoderMaxQueueSize;- if (!this._startupWindowClosed) {- if (this._startupFirstFrameAt === null) {- this._startupFirstFrameAt = performance.now();- }- this._startupFramesSeen += 1;- if (vQueueSize <= STARTUP_CAUGHT_UP_QUEUE) {- this._startupCaughtUpRun += 1;- } else {- this._startupCaughtUpRun = 0;- }- effectiveQueueCap = computeEffectiveQueueCap({- framesSinceStart: this._startupFramesSeen,- elapsedMs: performance.now() - this._startupFirstFrameAt,- caughtUp: this._startupCaughtUpRun >= STARTUP_CAUGHT_UP_RUN,- steadyCap: this._encoderMaxQueueSize,- startupCap: this._startupMaxQueueSize,- hardFrameLimit: this._startupHardFrameLimit,- hardMs: this._startupHardMs,- disabled: getStartupFlags().startupBufferDisabled,- });- if (effectiveQueueCap <= this._encoderMaxQueueSize) {- this._startupWindowClosed = true;- effectiveQueueCap = this._encoderMaxQueueSize;- } else if (- vQueueSize > this._encoderMaxQueueSize &&- vQueueSize <= effectiveQueueCap- ) {- // Counts only frames the wider cap actually saves (above the- // steady cap, still inside the grace cap). Counting ones that- // drop anyway would overstate the fix in telemetry.- this._startupBufferEngaged = true;- this._framesBufferedAtStart += 1;- }- }-- // Backpressure: drop the frame and force a keyframe next so- // the stream stays decodable. An unbounded queue can stop- // emitting chunks entirely.- if (vQueueSize > effectiveQueueCap) {- this._droppedForBackpressureCount += 1;- this._forceNextKeyframe = true;- // A dropped lead-in hold leaves index 0 for the retry.- if (holdUntilIndex == null) this._videoFrameIndex = i + 1;- continue;- }-- const resized = new VideoFrame(this.resizeCanvas, {- timestamp: tsUs,- duration:- holdUntilIndex != null- ? (holdUntilIndex + 1 - i) * frameDurationUs- : frameDurationUs,- });-- const keyFrame =- i === 0 ||- (this.justResumed && i === startIndex) ||- this._forceNextKeyframe === true ||- i - this._lastKeyFrameIndex >= this._keyFrameIntervalFrames;- if (keyFrame) {- this._lastKeyFrameIndex = i;- this._forceNextKeyframe = false;- }- if (this.justResumed && i === startIndex) {- this.justResumed = false;- }-- // pause() can close the encoder between the top-of-loop check- // and here. Drop the frame instead of bubbling a sync throw.- if (- this.paused ||- !this.videoEncoder ||- this.videoEncoder.state === "closed"- ) {- resized.close();- if (holdUntilIndex == null) this._videoFrameIndex = i + 1;- this._forceNextKeyframe = true;- continue;- }- // try/finally so resized's GPU buffer closes on every exit- // (pause-race continue, rethrown encoder error, success).- try {- try {- this.videoEncoder.encode(resized, {- timestamp: tsUs,- keyFrame,- });- this._framesFed += 1;- } catch (encErr) {- // Same race after the check. Only swallow when paused- // so real encoder errors still surface.- if (- this.paused ||- this.videoEncoder?.state === "closed"- ) {- this.warn("[WCR] encode() race during pause; dropping frame");- if (holdUntilIndex == null) this._videoFrameIndex = i + 1;- this._forceNextKeyframe = true;- continue;- }- // QuotaExceededError means a full queue (Chrome 140+ backpressure,- // drop the frame) or a reclaimed encoder (near-empty queue). Route- // the reclaim case to a rebuild, not a drop into a dead encoder.- if (encErr?.name === "QuotaExceededError") {- const q = this.videoEncoder?.encodeQueueSize ?? 0;- // A near-empty queue only meant reclaim while the cap was 4;- // at 16 a real reclaim looks like backpressure and silently- // skips the rebuild. Chrome names reclaims in the message.- if (isReclaimErrorMessage(encErr) || q <= 5) {- if (holdUntilIndex == null) this._videoFrameIndex = i + 1;- this._forceNextKeyframe = true;- this.warn(- "[WCR] encode() QuotaExceededError with near-empty queue; treating as encoder reclaim, rebuilding",- { queue: q },- );- this._handleVideoEncoderError(encErr, true);- continue;- }- this._droppedForBackpressureCount += 1;- this._forceNextKeyframe = true;- if (holdUntilIndex == null) this._videoFrameIndex = i + 1;- this.warn(- "[WCR] encode() QuotaExceededError; dropping frame as backpressure",- );- continue;- }- throw encErr;- }- if (- this.debug &&- (this.frameCount < 5 || this.frameCount % 300 === 0)- ) {- this.log("[WCR] video pts", {- frame: this.frameCount,- tsUs,- durUs: frameDurationUs,- targetIndex,- });- }- // Diag snapshot every 30 frames. encodeQueueSize > 10 means- // the encoder can't keep up.- if (this.frameCount > 0 && this.frameCount % 30 === 0) {- perfMark("WCR.frame.progress", {- frame: this.frameCount,- videoQ: this.videoEncoder?.encodeQueueSize ?? -1,- audioQ: this.audioEncoder?.encodeQueueSize ?? -1,- });- }- this.frameCount++;- this._fpsWindows.tick(- this.frameCount,- performance.now() - (this.totalPausedDurationUs || 0) / 1000,- );- this._videoLeadInPending = false;- this._videoFrameIndex =- holdUntilIndex != null ? holdUntilIndex + 1 : i + 1;- } finally {- resized.close();- }- }+ this._encodeVideoSlots({+ startIndex,+ holdUntilIndex,+ frameDurationUs,+ targetIndex,+ });// Only close a real source frame; the synthetic path reuses// the existing resize-canvas content and has no incoming frame.@@ -3414,6 +3752,11 @@ export class WebCodecsRecorder {this._videoLoopError = err;}+ try {+ this._heldFirstFrame?.close();+ } catch {}+ this._heldFirstFrame = null;+this.log("[WCR] video loop exit", this.frameCount, "running=", this.running);// Loop exited while running; stop audio so it doesn't outlast video.if (this.running) {diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsxindex e8ceca7..412adb7 100644--- a/src/pages/Region/Recorder.jsx+++ b/src/pages/Region/Recorder.jsx@@ -384,7 +384,18 @@ const Recorder = () => {lastEstimateAt.current = now;try {- const { usage = 0, quota = 0 } = await navigator.storage.estimate();+ // A hung estimate() would freeze the drain, so bound it. A timeout is+ // "slow", not "low", and falls through to the catch's keep-going verdict.+ let estimateTimer = null;+ const { usage = 0, quota = 0 } = await Promise.race([+ navigator.storage.estimate(),+ new Promise((_, reject) => {+ estimateTimer = setTimeout(+ () => reject(new Error("storage-estimate-timeout")),+ 5000,+ );+ }),+ ]).finally(() => clearTimeout(estimateTimer));const remaining = quota - usage;const reserve = Math.max(MIN_HEADROOM,@@ -659,10 +670,23 @@ const Recorder = () => {}async function waitForDrain() {- // Cap so a wedged drain doesn't block stop forever.- const deadline = Date.now() + 30000;+ // Wait while fragments keep landing; give up only after a long stretch+ // with no progress, or an absolute cap, so a wedged drain can't block stop.+ const start = Date.now();+ let lastProgressAt = start;+ let lastSaved = savedCount.current;+ let lastPending = pending.current.length;while (draining.current || pending.current.length) {- if (Date.now() > deadline) {+ const now = Date.now();+ if (+ savedCount.current !== lastSaved ||+ pending.current.length !== lastPending+ ) {+ lastSaved = savedCount.current;+ lastPending = pending.current.length;+ lastProgressAt = now;+ }+ if (now - lastProgressAt > 30000 || now - start > 240000) {console.warn("[Region] waitForDrain timed out", {pending: pending.current.length,draining: draining.current,diff --git a/src/pages/utils/startProgress.js b/src/pages/utils/startProgress.jsindex 5d0b8d9..9cbbd98 100644--- a/src/pages/utils/startProgress.js+++ b/src/pages/utils/startProgress.js@@ -1,7 +1,10 @@+import { perfMark } from "./perfMarks";+// Stage heartbeat for the BG start-fail re-check. Startup outlasts one window// on a slow encoder probe, and the background reads that silence as a dead// recorder and tears the start down.export function markStartProgress(stage) {+ perfMark("Start.stage", { stage });try {chrome.storage.local.set({recorderStartProgress: { ts: Date.now(), stage },