diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000..c5f23bc8 --- /dev/null +++ b/.babelrc @@ -0,0 +1,8 @@ +{ + "presets": ["@babel/preset-react"], + "env": { + "development": { + "plugins": ["react-refresh/babel"] + } + } +} diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index b02cd657..1402dd70 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -9,4 +9,3 @@ community_bridge: # Replace with a single Community Bridge project-name e.g., cl liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username -custom: https://github.com/btzr-io/Villain/blob/master/SUPPORT.md#donations # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.gitignore b/.gitignore index 78477de3..980f5fe0 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,13 @@ logs npm-debug.log* yarn-debug.log* yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Test archives +playground/public/example_3.cbz # Runtime data pids @@ -16,11 +23,12 @@ lib-cov # Coverage directory used by tools like istanbul coverage +*.lcov # nyc test coverage .nyc_output -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) @@ -29,15 +37,18 @@ bower_components # node-waf configuration .lock-wscript -# Compiled binary addons (http://nodejs.org/api/addons.html) +# Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ -# Typescript v1 declaration files -typings/ +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo # Optional npm cache directory .npm @@ -45,6 +56,12 @@ typings/ # Optional eslint cache .eslintcache +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + # Optional REPL history .node_repl_history @@ -56,13 +73,47 @@ typings/ # dotenv environment variables file .env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ -# Test files -build/test_files +# DynamoDB Local files +.dynamodb/ -# IDE files -.idea/ +# TernJS port file +.tern-port +# Stores VSCode versions used for testing VSCode extensions +.vscode-test -# Deploy for github pages -.deploy/ +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* diff --git a/.nolluprc.js b/.nolluprc.js new file mode 100644 index 00000000..943f69b2 --- /dev/null +++ b/.nolluprc.js @@ -0,0 +1,5 @@ +module.exports = { + contentBase: "./playground/public", + port: 8080, + hot: true, +}; diff --git a/.prettierrc b/.prettierrc index 12a0d5e9..fea4a0fe 100644 --- a/.prettierrc +++ b/.prettierrc @@ -8,10 +8,6 @@ { "files": [".prettierrc", ".babelrc"], "options": { "parser": "json" } - }, - { - "files": "**/*.css.module", - "options": { "parser": "css" } } ] } diff --git a/README.md b/README.md index ed69e2d4..c1c36e97 100644 --- a/README.md +++ b/README.md @@ -68,28 +68,15 @@ Supported archives formats by [`libarchive.js`](https://github.com/nika-begiashv - `RAR v5` - `TAR` -## Development - -This repository is now a `mono-repo` and is maintained with [lerna](https://github.com/lerna/lerna) - -### Setup +## Development: Before you jump in the code please follow the initial setup guide for development: 1. Clone or fork this repository. 2. Run `yarn` command to install the project dependencies. -3. Run `yarn bootstrap` to install all dependencies from internal packages and link any cross-dependencies. - -Thats it! Now you are ready to start fixing bugs and implementing new features. :tada: - -### Packages -Available packages living inside this repository: +That's it! Now you are ready to start fixing bugs and implementing new features. :tada: -| Name | version | Description | -| -------------------------------------------------------------------------------------- | ------------ | ------------------- | -| [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) | 0.0.1 (beta) | web app + embed api | -| [villain-react](https://github.com/btzr-io/Villain/tree/master/packages/villain-react) | 1.0.7 | react component | ### Commands @@ -98,13 +85,6 @@ Available package scripts for development: | Name | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | deploy | Deploy [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) to github pages | -| bootstrap | Bootstrap the packages in the current mono repo | -| start:web | Start development webpack-dev-server (includes hot-reloading) of [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) | -| build:web | Build production version of [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) | -| start:react | Start development webpack-dev-server (includes hot-reloading) of [villain-react](https://github.com/btzr-io/Villain/tree/master/packages/villain-react) | -| build:react | Build production version of [villain-react](https://github.com/btzr-io/Villain/tree/master/packages/villain-react) | -| docs:copy | Prepare documents for docsify-cli | -| docsify:serve | Serve docsify generated document on localhost:3000 | ```sh yarn command-name diff --git a/SUPPORT.md b/SUPPORT.md deleted file mode 100644 index 7bcc524e..00000000 --- a/SUPPORT.md +++ /dev/null @@ -1,26 +0,0 @@ - -# :heart: Support - -If you'd like to help support the future of the project, here are some things you can do: - -### Feedback - -- Feel free to leave some feedback, ideas or share your insights. -- Also you can request new features that can improve usability or accesibility by creating a new [feature request](https://github.com/btzr-io/Villain/issues/new?assignees=&labels=&template=feature_request.md&title=) -### Report bugs - -- Found an issue ? Please report it so we can fix it. see the list of [bugs](https://github.com/btzr-io/Villain/issues?q=is%3Aissue+is%3Aopen+label%3Abug) - - -### Donations - -Consider making a donation: https://opencollective.com/villain - -| Crypto | Adress | -| ------ | ------ | -| **BAT** | 0xd3bcec62285b9209d96499f1d05d257eaf5b0439 | -| **Bitcoin** | 36StGtp6CVwYN8JkiqfcTnZKWeYiKbahuH | -| **Etherum** | 0xd3bcec62285b9209d96499f1d05d257eaf5b0439 | -| **Stellar** | GBEL2WZKLEVGGNJPXFNIXXNE62XNF75MYP6OJOC4IQRFMMG4DH5NQB4T | -| **Lite coin** | MHvsepTBqc7aqVocPQfFBpkTT7Wp331gRe | -| **LBRY credits** | bQaC73Mgs7D2vPk7oogej6Zx9YvGqf7znw | diff --git a/artworks/ARTWORKS_LICENSE.md b/artworks/ARTWORKS_LICENSE.md deleted file mode 100644 index b2670fde..00000000 --- a/artworks/ARTWORKS_LICENSE.md +++ /dev/null @@ -1,19 +0,0 @@ -### Villain Restricted Use Logo License - -Applies to this folder ... and all derivatives - ----- - Villain Restricted Use Logo Copyright Holders: - - Copyright (c) 2019 Baltazar Gomez - - 1. Artworks in this folder may only be used if: - - official approval is given by any listed copyright holder for its use in a defined purpose. - 2. We reserve the right to revoke a license for a product. - 3. We reserve the right to change this license at our sole discretion. - - Permission has been given to use the restricted logo on clothing (shirts, - hats, etc) and some objects. Anyone can do so as long as they have written authorization from - a listed Villain Restricted Use Logo copyright holder and not sold for profit. - -_This license is a derivative of Debian Restricted Use Logo License: https://www.debian.org/logos/_ diff --git a/artworks/Screenshot_2019-11-27 Villain Demo(1).png b/artworks/Screenshot_2019-11-27 Villain Demo(1).png deleted file mode 100644 index e62f44a4..00000000 Binary files a/artworks/Screenshot_2019-11-27 Villain Demo(1).png and /dev/null differ diff --git a/artworks/Screenshot_2019-11-27 Villain Demo.png b/artworks/Screenshot_2019-11-27 Villain Demo.png deleted file mode 100644 index 2ddb575f..00000000 Binary files a/artworks/Screenshot_2019-11-27 Villain Demo.png and /dev/null differ diff --git a/artworks/logo-small.png b/artworks/logo-small.png deleted file mode 100644 index 438ad586..00000000 Binary files a/artworks/logo-small.png and /dev/null differ diff --git a/artworks/logo.png b/artworks/logo.png deleted file mode 100644 index ca203011..00000000 Binary files a/artworks/logo.png and /dev/null differ diff --git a/artworks/logo.svg b/artworks/logo.svg deleted file mode 100644 index 697a7e60..00000000 --- a/artworks/logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/deploy.sh b/deploy.sh deleted file mode 100755 index 5dc7b34d..00000000 --- a/deploy.sh +++ /dev/null @@ -1,12 +0,0 @@ -# Deploy to github packes -rm -r .deploy -mkdir .deploy -cd .deploy -git clone -b gh-pages https://github.com/btzr-io/Villain.git -cd .. -ls -rsync -arv ./packages/villain-web/dist/ .deploy/Villain -cd .deploy/Villain -git add . -git commit -a -m "update and deploy" -git push diff --git a/docs/.nojekyll b/docs/.nojekyll deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/_404.md b/docs/_404.md deleted file mode 100644 index 9408cf8f..00000000 --- a/docs/_404.md +++ /dev/null @@ -1,3 +0,0 @@ -# 404 - Page not found - -> “Sorry, we can’t find the page you were looking for.” diff --git a/docs/_coverpage.md b/docs/_coverpage.md deleted file mode 100644 index 742dc90c..00000000 --- a/docs/_coverpage.md +++ /dev/null @@ -1,30 +0,0 @@ -

- Villain logo -

- -

-The open source web-based comic book reader that you need, but don't deserve. -

- -

- - npm - - - Open Collective sponsors - - - GitHub contributors - - - GitHub license - - - Lerna - -

-
- -[Get Started](get-started.md) - -

color

diff --git a/docs/_sidebar.md b/docs/_sidebar.md deleted file mode 100644 index 763140d8..00000000 --- a/docs/_sidebar.md +++ /dev/null @@ -1,3 +0,0 @@ -- [Get Started](get-started.md) -- [Villain web](villain-web.md) -- [Villain React](villain-react.md) diff --git a/docs/get-started.md b/docs/get-started.md deleted file mode 100644 index ed69e2d4..00000000 --- a/docs/get-started.md +++ /dev/null @@ -1,123 +0,0 @@ -

- Villain logo -

- -

-The open source web-based comic book reader that you need, but don't deserve. -

- -

- - npm - - - Open Collective sponsors - - - GitHub contributors - - - GitHub license - - - Lerna - -

-
-

- Screen preview -

- -## What? - -A simple open source web-based reader for: - -- Manga -- Comic books -- Graphic novels -- Illustrated books - -Works on the client side and is easy to integrate on any modern website or react application. - -## How? - -It relays on cutting-edge web apis and frameworks like react, webworkers and webAssembly: - -- Dont expect it to work on a hot potato -- Usage with modern browsers is recommended - -## Features - -- Dark / light theme -- Manga mode ( Read right to left or default left to right ) -- Full screen mode ( Browser fullscreen API integration ) -- Easy page navigation : prev / next page buttons, slider component as well and a text input for accessibility -- Keyboard shortcuts ( I need to document this ) -- Localization of strings ( Multi language support for the UI ) -- Layout mode : Single page / Book ( two pages ) - -A killer feature is missing ? Open a [feature request](https://github.com/btzr-io/Villain/issues/new?assignees=&labels=&template=feature_request.md&title=) - -## Formats - -Supported archives formats by [`libarchive.js`](https://github.com/nika-begiashvili/libarchivejs) - -- `ZIP` -- `7-Zip` -- `RAR v4` -- `RAR v5` -- `TAR` - -## Development - -This repository is now a `mono-repo` and is maintained with [lerna](https://github.com/lerna/lerna) - -### Setup - -Before you jump in the code please follow the initial setup guide for development: - -1. Clone or fork this repository. -2. Run `yarn` command to install the project dependencies. -3. Run `yarn bootstrap` to install all dependencies from internal packages and link any cross-dependencies. - -Thats it! Now you are ready to start fixing bugs and implementing new features. :tada: - -### Packages - -Available packages living inside this repository: - -| Name | version | Description | -| -------------------------------------------------------------------------------------- | ------------ | ------------------- | -| [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) | 0.0.1 (beta) | web app + embed api | -| [villain-react](https://github.com/btzr-io/Villain/tree/master/packages/villain-react) | 1.0.7 | react component | - -### Commands - -Available package scripts for development: - -| Name | Description | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| deploy | Deploy [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) to github pages | -| bootstrap | Bootstrap the packages in the current mono repo | -| start:web | Start development webpack-dev-server (includes hot-reloading) of [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) | -| build:web | Build production version of [villain-web](https://github.com/btzr-io/Villain/tree/master/packages/villain-web) | -| start:react | Start development webpack-dev-server (includes hot-reloading) of [villain-react](https://github.com/btzr-io/Villain/tree/master/packages/villain-react) | -| build:react | Build production version of [villain-react](https://github.com/btzr-io/Villain/tree/master/packages/villain-react) | -| docs:copy | Prepare documents for docsify-cli | -| docsify:serve | Serve docsify generated document on localhost:3000 | - -```sh -yarn command-name -``` - -## Known issues - -- Accessibility issues [#23](https://github.com/btzr-io/Villain/issues/23) -- Some `.rar` and `.cbr` fail to load [#1](https://github.com/btzr-io/Villain/issues/1) -- Encrypted archived are not yet supported [#26](https://github.com/btzr-io/Villain/issues/26) - -## Credits - -- :hammer_and_wrench: Created and maintained by [@btzr-io](https://github.com/btzr-io) with the help of some awesome [contributors](https://github.com/btzr-io/Villain/graphs/contributors). - -- :art: Logo and artworks designed by [@btzr-io](https://github.com/btzr-io), see [license](https://github.com/btzr-io/Villain/blob/master/artworks/ARTWORKS_LICENSE.md). diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index b227ebb3..00000000 --- a/docs/index.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - Villain - - - - - - - - - -
- - - - diff --git a/docs/index.js b/docs/index.js deleted file mode 100644 index bf987743..00000000 --- a/docs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env node -const { copyFileSync } = require('fs') - -copyFileSync('./README.md', './docs/get-started.md') -copyFileSync('./packages/villain-web/README.md', './docs/villain-web.md') -copyFileSync('./packages/villain-react/README.md', './docs/villain-react.md') diff --git a/docs/villain-react.md b/docs/villain-react.md deleted file mode 100644 index 14273785..00000000 --- a/docs/villain-react.md +++ /dev/null @@ -1,124 +0,0 @@ -

- Villain logo -

- -

-The open source web-based comic book reader that you need, but don't deserve. -

- -

- - npm - - - status - - - GitHub contributors - - - GitHub license - -

- -
- -## Installation - -```shell -$ yarn add villain-react -``` - -## WebWorker - -This project uses [libarchivejs](https://github.com/nika-begiashvili/libarchivejs) for extracting compressed archives, -so you will need to provide the path of `webworker`: - -> The webworker bundle lives in libarchive.js/dist folder so you need to make sure that it is available in your public folder since it will not get bundled if you're using bundler (it's all bundled up already) - -```js -const workerUrl = 'path to ../build/worker-bundle.js', -``` - -### Formats - -Supported archives formats by [`libarchive.js`](https://github.com/nika-begiashvili/libarchivejs) - -- `ZIP` -- `7-Zip` -- `RAR v4` -- `RAR v5` -- `TAR` - -## Usage - -Import the component and the css styles - -```js -// Component -import Villain from 'villain-react' - -// Css styles -import 'villain-react/dist/style.css' - -// Path of the comicbook archive, it can also be a file or blob -const url = './files/test.cbz' - -// Path of the libarchivejs webworker bundle -const workerUrl = 'path to ../build/worker-bundle.js', - -//... - - -``` - -### Props - -Available props of the component: - -| Name | Type | Default | Description | -| --------- | ------------------ | ----------------------------------------------------- | ----------------------------------------- | -| style | Object | null | Inline styles for root container. | -| source | string, file, blob | null | Path or file source of the archive. | -| options | object | [options](https://github.com/btzr-io/Villain#options) | Options to customize the reader component | -| className | string | null | Custom `css` class name | -| workerUrl | string | null | Path to libarchive.js `worker-bundle` | - -### Options - -Available options to customize the reader component: - -| Name | Type | Default | Description | -| -------------------- | ------ | ------- | ------------------------------------------------------------------------------- | -| theme | string | 'Light' | Choose CSS styling from between ('Light', 'Dark). | -| maxPages | number | 500 | Max number of pages to extract and render. | -| mangaMode | bool | false | Read right to left. | -| forceSort | bool | true | Fix sort order of pages ([#235](https://github.com/btzr-io/Villain/issues/235)) | -| allowFullScreen | bool | true | Show full screen button. | -| autoHideControls | bool | false | Set initial auto hide state of toolbar. | -| allowGlobalShortcuts | bool | false | Allows shortcuts without having to focus the viewer. | - -## Development - -Run `yarn` command to install the dependencies. - -To start the development run `yarn start`, this will open up `localhost:8080` on your default browser: - -- This uses webpack-dev-server and includes hot-reloading. - -An example archive has been provided to play around inside [`./packages/villain-react/dev-sandbox/static/archives`](https://github.com/xgirma/Villain/tree/master/packages/villain-react/dev-sandbox/static/archives) - -- A good resource for archives can be found here: https://archive.org/details/comics. -- Alternative, any compressed folder (zip, rar, tar, etc) with a few images will also do the job. - -## Known issues - -- Accessibility issues [#23](https://github.com/btzr-io/Villain/issues/23) -- Some `.rar` and `.cbr` fail to load [#1](https://github.com/btzr-io/Villain/issues/1) -- Encrypted archived are not yet supported [#26](https://github.com/btzr-io/Villain/issues/26) - -## Credits - -- :hammer_and_wrench: Created and maintained by [@btzr-io](https://github.com/btzr-io) with the help of some awesome [contributors](https://github.com/btzr-io/Villain/graphs/contributors). - -- :art: Logo and artworks designed by [@btzr-io](https://github.com/btzr-io), see [license](https://github.com/btzr-io/Villain/blob/master/artworks/ARTWORKS_LICENSE.md). diff --git a/docs/villain-web.md b/docs/villain-web.md deleted file mode 100644 index d9adc7fd..00000000 --- a/docs/villain-web.md +++ /dev/null @@ -1,122 +0,0 @@ -

- Villain logo -

- -

-The open source web-based comic book reader that you need, but don't deserve. -

- -

- - npm - - - status - - - GitHub contributors - - - GitHub license - -

- -
- -## Installation - -```shell -$ yarn add villain-react -``` - -## WebWorker - -This project uses [libarchivejs](https://github.com/nika-begiashvili/libarchivejs) for extracting compressed archives, -so you will need to provide the path of `webworker`: - -> The webworker bundle lives in libarchive.js/dist folder so you need to make sure that it is available in your public folder since it will not get bundled if you're using bundler (it's all bundled up already) - -```js -const workerUrl = 'path to ../build/worker-bundle.js', -``` - -### Formats - -Supported archives formats by [`libarchive.js`](https://github.com/nika-begiashvili/libarchivejs) - -- `ZIP` -- `7-Zip` -- `RAR v4` -- `RAR v5` -- `TAR` - -## Usage - -Import the component and the css styles - -```js -// Component -import Villain from 'villain-react' - -// Css styles -import 'villain-react/dist/style.css' - -// Path of the comicbook archive, it can also be a file or blob -const url = './files/test.cbz' - -// Path of the libarchivejs webworker bundle -const workerUrl = 'path to ../build/worker-bundle.js', - -//... - - -``` - -### Props - -Available props of the component: - -| Name | Type | Default | Description | -| --------- | ------------------ | ----------------------------------------------------- | ----------------------------------------- | -| style | Object | null | Inline styles for root container. | -| source | string, file, blob | null | Path or file source of the archive. | -| options | object | [options](https://github.com/btzr-io/Villain#options) | Options to customize the reader component | -| workerUrl | string | null | Path to libarchive.js `worker-bundle` | - -### Options - -Available options to customize the reader component: - -| Name | Type | Default | Description | -| -------------------- | ------ | ------- | ---------------------------------------------------- | -| theme | string | 'Dark' | Choose CSS styling from between ('Light', 'Dark). | -| maxPages | number | 500 | Max number of pages to extract and render. | -| mangaMode | bool | false | Read right to left. | -| allowFullScreen | bool | true | Show full screen button. | -| autoHideControls | bool | false | Set initial auto hide state of toolbar. | -| allowGlobalShortcuts | bool | false | Allows shortcuts without having to focus the viewer. | - -## Development - -Run `yarn` command to install the dependencies. - -To start the development run `yarn start`, this will open up `localhost:8080` on your default browser: - -- This uses webpack-dev-server and includes hot-reloading. - -An example archive has been provided to play around inside [`./packages/villain-web/dev-server/static/archives`](https://github.com/xgirma/Villain/tree/master/packages/villain-web/dev-server/static/archives) - -- A good resource for archives can be found here: https://archive.org/details/comics. -- Alternative, any compressed folder (zip, rar, tar, etc) with a few images will also do the job. - -## Known issues - -- Accessibility issues [#23](https://github.com/btzr-io/Villain/issues/23) -- Some `.rar` and `.cbr` fail to load [#1](https://github.com/btzr-io/Villain/issues/1) -- Encrypted archived are not yet supported [#26](https://github.com/btzr-io/Villain/issues/26) - -## Credits - -- :hammer_and_wrench: Created and maintained by [@btzr-io](https://github.com/btzr-io) with the help of some awesome [contributors](https://github.com/btzr-io/Villain/graphs/contributors). - -- :art: Logo and artworks designed by [@btzr-io](https://github.com/btzr-io), see [license](https://github.com/btzr-io/Villain/blob/master/artworks/ARTWORKS_LICENSE.md). diff --git a/lerna.json b/lerna.json deleted file mode 100644 index ad2a0290..00000000 --- a/lerna.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "lerna": "2.9.0", - "packages": ["packages/*"], - "version": "independent", - "npmClient": "yarn", - "useWorkspaces": true -} diff --git a/packages/villain-react/src/locales/messages.de.json b/locales/messages.de.json similarity index 72% rename from packages/villain-react/src/locales/messages.de.json rename to locales/messages.de.json index b1dc0898..45b0a900 100644 --- a/packages/villain-react/src/locales/messages.de.json +++ b/locales/messages.de.json @@ -2,13 +2,10 @@ "Previous page": "Vorherige Seite", "Next page": "Nächste Seite", "Page": "Seite", - "Pin controls": "Steuerung anheften", "Enter fullscreen": "Vollbildmodus öffnen", "Exit fullscreen": "Vollbildmodus beenden", "Book view": "Buchansicht", "Page view": "Seitenansicht", - "Light theme": "Tagmodus", - "Dark theme": "Nachtmodus", "Zoom in": "Vergrößern", "Zoom out": "Verkleinern", "Example test": "Beispiel Test!", @@ -18,7 +15,5 @@ "Languages": "Sprachen", "Settings": "Konfigurationen", "Keyboard shortcuts": "Tastatürkürzel", - "Manga mode": "Manga-Modus", - "Pin toolbar": "Pin die Symbolleiste", - "Unpin toolbar": "Löse die Symbolleiste" + "Manga mode": "Manga-Modus" } diff --git a/packages/villain-react/src/locales/messages.es.json b/locales/messages.es.json similarity index 70% rename from packages/villain-react/src/locales/messages.es.json rename to locales/messages.es.json index 98a17736..e69771fb 100644 --- a/packages/villain-react/src/locales/messages.es.json +++ b/locales/messages.es.json @@ -2,13 +2,10 @@ "Previous page": "Anterior", "Next page": "Siguiente", "Page": "Página", - "Pin controls": "Fijar controles", "Enter fullscreen": "Pantalla completa", "Exit fullscreen": "Salir de pantalla completa", "Book view": "Modo libro", "Page view": "Modo página", - "Light theme": "Tema claro", - "Dark theme": "Tema oscuro", "Zoom in": "Ampliar", "Zoom out": "Reducir", "Example test": "¡Test de ejemplo!", @@ -18,7 +15,5 @@ "Languages": "Idiomas", "Settings": "Configuraciones", "Keyboard shortcuts": "Atajos de teclado", - "Manga mode": "Modo manga", - "Pin toolbar": "Anclar la barra de herramientas", - "Unpin toolbar": "Anclar la barra de herramientas" + "Manga mode": "Modo manga" } diff --git a/packages/villain-react/src/locales/messages.fr.json b/locales/messages.fr.json similarity index 70% rename from packages/villain-react/src/locales/messages.fr.json rename to locales/messages.fr.json index 26d6e6bb..fd221600 100644 --- a/packages/villain-react/src/locales/messages.fr.json +++ b/locales/messages.fr.json @@ -2,13 +2,10 @@ "Previous page": "Page précédente", "Next page": "Page suivante", "Page": "Page", - "Pin controls": "Commandes Pin", "Enter fullscreen": "Entrer en plein écran", "Exit fullscreen": "Quitter le plein écran", "Book view": "Vue du livre", "Page view": "Page vue", - "Light theme": "Thème lumière", - "Dark theme": "Thème sombre", "Zoom in": "Zoom avant", "Zoom out": "Zoom arrière", "Example test": "Exemple de test!", @@ -18,7 +15,5 @@ "Languages": "Langues", "Settings": "Paramètres", "Keyboard shortcuts": "Raccourcis clavier", - "Manga mode": "Mode manga", - "Pin toolbar": "Épingler la barre d'outils", - "Unpin toolbar": "Détacher la barre d'outils" + "Manga mode": "Mode manga" } diff --git a/packages/villain-react/src/locales/messages.id.json b/locales/messages.id.json similarity index 76% rename from packages/villain-react/src/locales/messages.id.json rename to locales/messages.id.json index 9b20691f..75ae790a 100644 --- a/packages/villain-react/src/locales/messages.id.json +++ b/locales/messages.id.json @@ -7,8 +7,6 @@ "Exit fullscreen": "keluar skrin penuh", "Book view": "Lihat buku", "Page view": "Lihat halaman", - "Light theme": "Tema cerah", - "Dark theme": "Tema gelap", "Zoom in": "Zum masuk", "Zoom out": "Zum keluar", "Example test": "Contoh ujian!", @@ -18,7 +16,5 @@ "Languages": "Bahasa", "Settings": "Pengaturan", "Keyboard shortcuts": "Pintasan keyboard", - "Manga mode": "Mode manga", - "Pin toolbar": "Sematkan bilah alat", - "Unpin toolbar": "Lepas sematan bilah alat" + "Manga mode": "Mode manga" } diff --git a/packages/villain-react/src/locales/messages.json b/locales/messages.json similarity index 81% rename from packages/villain-react/src/locales/messages.json rename to locales/messages.json index b62a5c62..02460fee 100644 --- a/packages/villain-react/src/locales/messages.json +++ b/locales/messages.json @@ -2,15 +2,11 @@ "Previous page": "Previous page", "Next page": "Next page", "Page": "Page", - "Pin toolbar": "Pin toolbar", - "Unpin toolbar": "Unpin toolbar", "Enter fullscreen": "Enter fullscreen", "Exit fullscreen": "Exit fullscreen", "Book view": "Book view", "Page view": "Page view", "Manga mode": "Manga mode", - "Light theme": "Light theme", - "Dark theme": "Dark theme", "Zoom in": "Zoom in", "Zoom out": "Zoom out", "Example test": "Example test!", diff --git a/packages/villain-react/src/locales/messages.ko.json b/locales/messages.ko.json similarity index 78% rename from packages/villain-react/src/locales/messages.ko.json rename to locales/messages.ko.json index 4d1a3a17..e59fe31b 100644 --- a/packages/villain-react/src/locales/messages.ko.json +++ b/locales/messages.ko.json @@ -2,13 +2,10 @@ "Previous page": "이전 페이지", "Next page": "다음 페이지", "Page": "페이지", - "Pin toolbar": "툴바 고정", - "Unpin toolbar": "툴바 고정 해제", "Enter fullscreen": "전체화면", "Exit fullscreen": "전체화면 해제", "Book view": "두 쪽 보기", "Page view": "한 쪽 보기", - "Manga mode": "순서 반전(우→좌)", "Light theme": "밝은 테마", "Dark theme": "어두운 테마", "Zoom in": "확대", @@ -19,5 +16,6 @@ "Language": "언어", "Languages": "언어", "Settings": "설정", - "Keyboard shortcuts": "키보드 단축키" + "Keyboard shortcuts": "키보드 단축키", + "Manga mode": "순서 반전(우→좌)" } diff --git a/packages/villain-react/src/locales/messages.pt.json b/locales/messages.pt.json similarity index 72% rename from packages/villain-react/src/locales/messages.pt.json rename to locales/messages.pt.json index d9b4f204..b2372cdd 100644 --- a/packages/villain-react/src/locales/messages.pt.json +++ b/locales/messages.pt.json @@ -2,13 +2,10 @@ "Previous page": "Página anterior", "Next page": "Próxima página", "Page": "Página", - "Pin controls": "Fixar ferramentas", "Enter fullscreen": "Ativar tela cheia", "Exit fullscreen": "Desativar tela cheia", "Book view": "Visão de página dupla", "Page view": "Visão de página única", - "Light theme": "Tema claro", - "Dark theme": "Tema escuro", "Zoom in": "Aumentar zoom", "Zoom out": "Diminuir zoom", "Example test": "Teste de exemplo!", @@ -18,7 +15,5 @@ "Languages": "Línguas", "Settings": "Configurações", "Keyboard shortcuts": "Atalhos do teclado", - "Manga mode": "Modo Manga", - "Pin toolbar": "Fixar a barra de ferramentas", - "Unpin toolbar": "Soltar a barra de ferramentas" + "Manga mode": "Modo Manga" } diff --git a/packages/villain-react/src/locales/messages.ru.json b/locales/messages.ru.json similarity index 67% rename from packages/villain-react/src/locales/messages.ru.json rename to locales/messages.ru.json index 505e7bca..7f0dd5da 100644 --- a/packages/villain-react/src/locales/messages.ru.json +++ b/locales/messages.ru.json @@ -2,13 +2,10 @@ "Previous page": "Предыдущая", "Next page": "Следующая", "Page": "Страница", - "Pin controls": "Закрепить панель инструментов", "Enter fullscreen": "На весь экран", "Exit fullscreen": "Выйти из полноэкранного режима", "Book view": "Книжный вид", "Page view": "Страничный вид", - "Light theme": "Светлая тема", - "Dark theme": "Темная тема", "Zoom in": "Увеличить", "Zoom out": "Уменьшить", "Example test": "Тестовый пример!", @@ -18,7 +15,5 @@ "Languages": "языки", "Settings": "настройки", "Keyboard shortcuts": "Горячие клавиши", - "Manga mode": "Манга режим", - "Pin toolbar": "Закрепить панель инструментов", - "Unpin toolbar": "Открепить панель инструментов" + "Manga mode": "Манга режим" } diff --git a/packages/villain-react/src/locales/messages.zh.json b/locales/messages.zh.json similarity index 71% rename from packages/villain-react/src/locales/messages.zh.json rename to locales/messages.zh.json index 1dc32258..b08cc4e5 100644 --- a/packages/villain-react/src/locales/messages.zh.json +++ b/locales/messages.zh.json @@ -2,13 +2,10 @@ "Previous page": "上一頁", "Next page": "下一頁", "Page": "頁面", - "Pin controls": "固定控制", "Enter fullscreen": "進入全螢幕", "Exit fullscreen": "離開全螢幕", "Book view": "書本檢視", "Page view": "頁面檢視", - "Light theme": "亮色主題", - "Dark theme": "暗色主題", "Zoom in": "放大", "Zoom out": "縮小", "Example test": "範例測試!", @@ -18,7 +15,5 @@ "Languages": "语言能力", "Settings": "设定值", "Keyboard shortcuts": "键盘快捷键", - "Manga mode": "漫画模式", - "Pin toolbar": "固定工具栏", - "Unpin toolbar": "取消固定工具栏" + "Manga mode": "漫画模式" } diff --git a/logo-text.svg b/logo-text.svg deleted file mode 100644 index 1c74226e..00000000 --- a/logo-text.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/package.json b/package.json index 2cc6f29e..86f1bfbe 100644 --- a/package.json +++ b/package.json @@ -1,49 +1,54 @@ { - "name": "villain-project", - "private": true, - "description": "An open source web based comic book reader as a react component", - "scripts": { - "deploy": "chmod +x deploy.sh && ./deploy.sh", - "bootstrap": "lerna bootstrap", - "start:web": "lerna run --scope villain-web start --parallel", - "build:web": "lerna run --scope villain-web build --stream", - "start:react": "lerna run --scope villain-react start --parallel", - "build:react": "lerna run --scope villain-react build --stream", - "format": "pretty-quick", - "format:css": "npx prettier --config ./.prettierrc --write **/*.css.module", - "docs:copy": "node ./docs", - "docsify:serve": "npx docsify serve ./docs" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/btzr-io/Villain.git" - }, + "name": "villain-react", + "author": "Baltazar Gomez", + "version": "2.0.0", + "license": "MIT", + "homepage": "https://github.com/btzr-io/Villain", + "description": "An open source web based comic book reader", + "files": [ + "dist/" + ], "keywords": [ - "comic", - "comics", "comic book", "react", "reader", "viewer" ], - "workspaces": [ - "packages/*" - ], - "author": "Baltazar Gomez", - "license": "MIT", - "bugs": { - "url": "https://github.com/btzr-io/Villain/issues" + "scripts": { + "clean": "shx rm -rf dist", + "format": "yarn pretty-quick", + "start": "nollup -c --environment NODE_ENV:development", + "build": "npm run clean && rollup -c --environment NODE_ENV:production" }, - "homepage": "https://github.com/btzr-io/Villain#readme", - "devDependencies": { - "docsify-cli": "^4.4.1", - "lerna": "^3.20.2", - "prettier": "^1.17.0", - "pretty-quick": "^2.0.0" + "dependencies": { + "@mdi/js": "^7.0.96", + "@mdi/react": "^1.6.1", + "clsx": "^1.2.1", + "libarchive.js": "^1.3.0", + "openseadragon": "^3.1.0", + "react-compound-slider": "^3.4.0" }, "peerDependencies": { - "react": "^16.8.6", - "react-dom": "^16.8.6", - "reakit": "^1.0.0-beta.13" + "react": "^16.11.0", + "react-dom": "^16.11.0" + }, + "devDependencies": { + "@babel/core": "^7.15.5", + "@babel/preset-react": "^7.14.5", + "@rollup/plugin-alias": "^3.1.1", + "@rollup/plugin-babel": "^5.3.0", + "@rollup/plugin-node-resolve": "^13.0.4", + "nollup": "^0.18.4", + "prettier": "^2.7.1", + "pretty-quick": "^3.1.3", + "react": "^16.11.0", + "react-dom": "^16.11.0", + "react-refresh": "^0.10.0", + "rollup": "^2.56.3", + "rollup-plugin-commonjs-alternate": "^0.8.0", + "rollup-plugin-hot-css": "^0.5.1", + "rollup-plugin-react-refresh": "0.0.3", + "rollup-plugin-terser": "^7.0.2", + "shx": "^0.3.3" } } diff --git a/packages/villain-react/.babelrc b/packages/villain-react/.babelrc deleted file mode 100644 index 933f4b78..00000000 --- a/packages/villain-react/.babelrc +++ /dev/null @@ -1,29 +0,0 @@ -{ - "presets": [ - "@babel/preset-react" - ], - "plugins": [ - "transform-xregexp", - "@babel/plugin-proposal-class-properties", - ["module-resolver", { - "root": ["./"], - "alias": { - "@": "./src" - } - }] - ], - "env": { - "test": { - "presets": ["@babel/preset-env", "@babel/preset-react"], - "plugins": [ - "@babel/plugin-proposal-class-properties", - ["module-resolver", { - "root": ["./"], - "alias": { - "@": "./src" - } - }] - ] - } - } -} diff --git a/packages/villain-react/.eslintrc b/packages/villain-react/.eslintrc deleted file mode 100644 index a982168d..00000000 --- a/packages/villain-react/.eslintrc +++ /dev/null @@ -1,20 +0,0 @@ -module.exports = { - env: { - browser: true, - es6: true, - }, - extends: 'eslint:recommended', - globals: { - Atomics: 'readonly', - SharedArrayBuffer: 'readonly', - }, - parserOptions: { - ecmaFeatures: { - jsx: true, - }, - ecmaVersion: 2018, - sourceType: 'module', - }, - plugins: ['react'], - rules: {}, -} diff --git a/packages/villain-react/.gitignore b/packages/villain-react/.gitignore deleted file mode 100644 index ab8abe00..00000000 --- a/packages/villain-react/.gitignore +++ /dev/null @@ -1,64 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# Typescript v1 declaration files -typings/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env - -# Test files -build/test_files - -# IDE files -.idea/ diff --git a/packages/villain-react/CHANGELOG.md b/packages/villain-react/CHANGELOG.md deleted file mode 100644 index 1b18984b..00000000 --- a/packages/villain-react/CHANGELOG.md +++ /dev/null @@ -1,137 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - -## [1.0.8] - [2019-12-04] - -### Added - -- Option to force sorting order [(#237)](https://github.com/btzr-io/Villain/issues/237) - -### Fixed - -- Wrong sort order on some archives [(#235)](https://github.com/btzr-io/Villain/issues/235) - -## [1.0.7] - [2019-11-27] - -### Changed - -- Rename "file" prop to "source" [(See commit)](https://github.com/btzr-io/Villain/commit/cc59bfa8ec82ee090b4ccd3e427aa1eebad570cd) - -### Fixed - -- Worker is not terminated [(228)](https://github.com/btzr-io/Villain/issues/228) -- Incorrect target zoom on book mode [(See commit)](https://github.com/btzr-io/Villain/commit/8419754b36a43ad46c921238eeeb50420c844e0c) -- Use more inclusive regexp for matching file paths [(#227)](https://github.com/btzr-io/Villain/issues/227) -- Can't render more than one instance of the component [(#229)](https://github.com/btzr-io/Villain/issues/229) - -## [1.0.6] - [2019-11-24] - -### Added - -- Style prop to pass in-line styles to the main container [(See commit)](https://github.com/btzr-io/Villain/commit/8fbfa0d2a7d5bda3bcb713c80efd9a769bd0ef8f) - -### Changed - -- Minor css changes [(See commit)](https://github.com/btzr-io/Villain/commit/132825d32dd09b0b2852f201cb95c374fe68b41c) - -### Fixed - -- Minor patch for electron [(See commit)](https://github.com/btzr-io/Villain/commit/132825d32dd09b0b2852f201cb95c374fe68b41c) - - Fix css issues on electron - - Fix menu height not updating on electron - -## [1.0.5] - [2019-11-23] - -### Fixed - -- Fix scss styles not build on bundle [(See commit)](https://github.com/btzr-io/Villain/commit/e73fee8c762a9f571c986524d69c5c3629d6fc00) - -## [1.0.4] - [2019-11-23] - -### Changed - -- Update build - -## [1.0.3] - [2019-11-23] - -### Added - -- New `maxPages` prop [(See commit)](https://github.com/btzr-io/Villain/commit/8fbfa0d2a7d5bda3bcb713c80efd9a769bd0ef8f) - -### Changed - -- Improve toolbar auto-hide behavior [(See commit)](https://github.com/btzr-io/Villain/commit/146f50f323d44c3d732219c13f01b46449f945de) -- Better opacity for disabled buttons [(See commit)](https://github.com/btzr-io/Villain/commit/4d592a7f8e5abe4436f7adaa684d43cf23139cf8) -- Remove deprecated preview mode [(See commit)](https://github.com/btzr-io/Villain/commit/8fbfa0d2a7d5bda3bcb713c80efd9a769bd0ef8f) - -## [1.0.2] - [2019-11-21] - -### Added - -- Basic animations [(#213)](https://github.com/btzr-io/Villain/issues/213) - -### Changed - -- Render improvements [(#219)](https://github.com/btzr-io/Villain/issues/219) - -### Fixed - -- Localization not updating strings [(See commit)](https://github.com/btzr-io/Villain/commit/06a9831761c4599991033e55a24a15be2b086e1a) -- Reverse mode (manga) is not optimized [(#221)](https://github.com/Villain/issues/221) -- Can't properly fit pages to viewer bounds (book mode) [(#132)](https://github.com/btzr-io/Villain/issues/132) -- Performance issues on Focus / blur event listener [(#220)](https://github.com/btzr-io/Villain/issues/220) - -## [1.0.1] - [2019-11-12] - -### Added - -- New files of project's logo [(#180)](https://github.com/btzr-io/Villain/issues/180) - -### Changed - -- Css styles refactoring [(#140)](https://github.com/btzr-io/Villain/issues/140): - - Add `villain` prefix to css styles - - Better naming convention for css classes - -## [1.0.0] - [2019-11-11] - -### Added - -- Localization [(#76)](https://github.com/btzr-io/Villain/issues/76) -- Menu (options) [(#13)](<(https://github.com/btzr-io/Villain/issues/13)>) -- Dark and light theme [(#15)](https://github.com/btzr-io/Villain/issues/15) -- Theme toggler [(#14)](https://github.com/btzr-io/Villain/issues/14) -- Keyboard navigation for slider component [(#39)](https://github.com/btzr-io/Villain/issues/39) -- Preview mode [(#27)](https://github.com/btzr-io/Villain/issues/27) -- Manga mode [(#10)](https://github.com/btzr-io/Villain/issues/10) -- Keyboard shortcuts [(#20)](https://github.com/btzr-io/Villain/issues/20) -- Load archive from file object [(#129)](https://github.com/btzr-io/Villain/issues/129) -- Aria-labels and roles to buttons and inputs [(#84)](https://github.com/btzr-io/Villain/issues/84) -- Keyboard navigation for slider component [(#39)](https://github.com/btzr-io/Villain/issues/39) - -### Fixed - -- Slider component skipped key tab [(#40)](https://github.com/btzr-io/Villain/issues/40) -- Improve image type validation [(#50)](https://github.com/btzr-io/Villain/issues/50) -- Unified tooltip [(#93)](https://github.com/btzr-io/Villain/issues/93) - -### Changed - -- Reduce module size [(#60)](https://github.com/btzr-io/Villain/issues/60) -- Implement reakit [(#165)](https://github.com/btzr-io/Villain/issues/165) -- Renamed workerPath option to workerUrl [(#55)](https://github.com/btzr-io/Villain/issues/55) -- Move react/react-dom deps into `peerDependencies` [(#155)](https://github.com/btzr-io/Villain/issues/155) -- Split main css into different files for each component [(#99)](https://github.com/btzr-io/Villain/issues/99) - -## [0.0.9] - [2019-10-15] - -### Fixed - -- Bad zoom levels [(#3)](https://github.com/btzr-io/Villain/issues/3) -- Fullscreen mode not working [(#11)](https://github.com/btzr-io/Villain/issues/11) -- Change fullscreen icon on enter and exit events [(#17)](https://github.com/btzr-io/Villain/issues/17) - -### Changed - -- Update libarchive.js [(#28)](https://github.com/btzr-io/Villain/issues/28) diff --git a/packages/villain-react/LICENSE b/packages/villain-react/LICENSE deleted file mode 100644 index f55f24cc..00000000 --- a/packages/villain-react/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Baltazar Gomez - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/packages/villain-react/README.md b/packages/villain-react/README.md deleted file mode 100644 index 14273785..00000000 --- a/packages/villain-react/README.md +++ /dev/null @@ -1,124 +0,0 @@ -

- Villain logo -

- -

-The open source web-based comic book reader that you need, but don't deserve. -

- -

- - npm - - - status - - - GitHub contributors - - - GitHub license - -

- -
- -## Installation - -```shell -$ yarn add villain-react -``` - -## WebWorker - -This project uses [libarchivejs](https://github.com/nika-begiashvili/libarchivejs) for extracting compressed archives, -so you will need to provide the path of `webworker`: - -> The webworker bundle lives in libarchive.js/dist folder so you need to make sure that it is available in your public folder since it will not get bundled if you're using bundler (it's all bundled up already) - -```js -const workerUrl = 'path to ../build/worker-bundle.js', -``` - -### Formats - -Supported archives formats by [`libarchive.js`](https://github.com/nika-begiashvili/libarchivejs) - -- `ZIP` -- `7-Zip` -- `RAR v4` -- `RAR v5` -- `TAR` - -## Usage - -Import the component and the css styles - -```js -// Component -import Villain from 'villain-react' - -// Css styles -import 'villain-react/dist/style.css' - -// Path of the comicbook archive, it can also be a file or blob -const url = './files/test.cbz' - -// Path of the libarchivejs webworker bundle -const workerUrl = 'path to ../build/worker-bundle.js', - -//... - - -``` - -### Props - -Available props of the component: - -| Name | Type | Default | Description | -| --------- | ------------------ | ----------------------------------------------------- | ----------------------------------------- | -| style | Object | null | Inline styles for root container. | -| source | string, file, blob | null | Path or file source of the archive. | -| options | object | [options](https://github.com/btzr-io/Villain#options) | Options to customize the reader component | -| className | string | null | Custom `css` class name | -| workerUrl | string | null | Path to libarchive.js `worker-bundle` | - -### Options - -Available options to customize the reader component: - -| Name | Type | Default | Description | -| -------------------- | ------ | ------- | ------------------------------------------------------------------------------- | -| theme | string | 'Light' | Choose CSS styling from between ('Light', 'Dark). | -| maxPages | number | 500 | Max number of pages to extract and render. | -| mangaMode | bool | false | Read right to left. | -| forceSort | bool | true | Fix sort order of pages ([#235](https://github.com/btzr-io/Villain/issues/235)) | -| allowFullScreen | bool | true | Show full screen button. | -| autoHideControls | bool | false | Set initial auto hide state of toolbar. | -| allowGlobalShortcuts | bool | false | Allows shortcuts without having to focus the viewer. | - -## Development - -Run `yarn` command to install the dependencies. - -To start the development run `yarn start`, this will open up `localhost:8080` on your default browser: - -- This uses webpack-dev-server and includes hot-reloading. - -An example archive has been provided to play around inside [`./packages/villain-react/dev-sandbox/static/archives`](https://github.com/xgirma/Villain/tree/master/packages/villain-react/dev-sandbox/static/archives) - -- A good resource for archives can be found here: https://archive.org/details/comics. -- Alternative, any compressed folder (zip, rar, tar, etc) with a few images will also do the job. - -## Known issues - -- Accessibility issues [#23](https://github.com/btzr-io/Villain/issues/23) -- Some `.rar` and `.cbr` fail to load [#1](https://github.com/btzr-io/Villain/issues/1) -- Encrypted archived are not yet supported [#26](https://github.com/btzr-io/Villain/issues/26) - -## Credits - -- :hammer_and_wrench: Created and maintained by [@btzr-io](https://github.com/btzr-io) with the help of some awesome [contributors](https://github.com/btzr-io/Villain/graphs/contributors). - -- :art: Logo and artworks designed by [@btzr-io](https://github.com/btzr-io), see [license](https://github.com/btzr-io/Villain/blob/master/artworks/ARTWORKS_LICENSE.md). diff --git a/packages/villain-react/dev-sandbox/components/field.js b/packages/villain-react/dev-sandbox/components/field.js deleted file mode 100644 index 37b8b162..00000000 --- a/packages/villain-react/dev-sandbox/components/field.js +++ /dev/null @@ -1,32 +0,0 @@ -import React from 'react' -import clsx from 'clsx' -import Villain from '@/index.js' - -function Field({ name, type = 'text', value, options = [], onChange }) { - let input = - if (type === 'boolean') - input = ( - - ) - else if (type === 'select') - input = ( - - ) - return ( - - ) -} - -export default Field diff --git a/packages/villain-react/dev-sandbox/demo.css b/packages/villain-react/dev-sandbox/demo.css deleted file mode 100644 index 2e11d4e5..00000000 --- a/packages/villain-react/dev-sandbox/demo.css +++ /dev/null @@ -1,146 +0,0 @@ -html, -body { - height: 100%; - width: 100%; - margin: 0; - font-family: Segoe UI,Roboto, Helvetica, Arial, sans-serif; -} - -body, -h1, -h2, -h3 { - margin: 0; -} - -h3 { - margin: 16px 0; -} - -body, -#app, -.villain-demo { - display: flex; - flex: 1; -} - -.villain { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - margin: auto; - height: 80% !important; - width: 80% !important; - box-shadow: 0 1px 16px rgba(0, 0, 0, 0.12); - border-radius: 12px; -} - -.villain-demo label { - display: flex; - align-content: center; - align-items: center; - justify-content: space-between; - padding: 1rem; - border-bottom: 1px solid var(--input-border); -} - -.villain-demo label span { - opacity: 0.72; -} - -.villain-demo aside { - display: flex; - flex-direction: column; - min-width: 320px; - border-right: 1px solid rgba(0, 0, 0, 0.1); - margin: 0; - overflow: auto; - box-shadow: 0 1px 16px rgba(0, 0, 0, 0.12); - background-color: var(--card-bg); -} - -.villain-demo .form { - flex: 1; - padding: 16px; - overflow-y: auto; -} - -.villain-demo .field input { - color: var(--primary-text); - border: 1px solid var(--input-border); - background: var(--input-bg); - padding: 2px 6px; - max-width: 50%; - padding: 0.25em 0.5em; -} - -.villain-demo .field input[type='checkbox'] { - -moz-appearance: none; - -webkit-appearance: none; -} - -.villain-demo .field select { - padding: 0.25em 0.5em; - /* Targetting Webkit browsers only. FF will show the dropdown arrow with so much padding. */ - border: 1px solid var(--input-border); - border-radius: 0; - background-color: var(--input-bg); - color: var(--primary-text); - display: inline-block; -} - -.villain-demo .instance { - align-self: center; - margin: 0 auto; - width: 100%; - height: 100%; - position: relative; -} - -.villain-demo .field .custom-checkbox-input { - opacity: 1; - position: relative; - background: transparent; - border: 0; - outline: 0; -} - -.villain-demo .field .custom-checkbox-input::before { - content: ''; - position: absolute; - background: var(--input-bg); - left: 50%; - top: 50%; - width: 18px; - height: 18px; - display: block; - transform: translate(-50%, -50%); - cursor: pointer; - border: 2px solid var(--input-border); - border-radius: 0.3rem; -} - -.villain-demo .field .custom-checkbox-input:checked::before { - background: #ff5c65; -} - -.villain-demo .field .custom-checkbox-input::after { - content: ''; - position: absolute; - display: none; - left: 16%; - bottom: -20%; - width: 4px; - height: 8px; - transform: translate(-50%, -50%); - border: solid #fff; - border-width: 0 3px 3px 0; - transform: rotate(45deg); - cursor: pointer; -} - -.villain-demo .field .custom-checkbox-input:checked::after { - display: block; -} diff --git a/packages/villain-react/dev-sandbox/demo.js b/packages/villain-react/dev-sandbox/demo.js deleted file mode 100644 index d27cb24d..00000000 --- a/packages/villain-react/dev-sandbox/demo.js +++ /dev/null @@ -1,89 +0,0 @@ -import React, { useState } from 'react' -import clsx from 'clsx' -import Villain from '@/index.js' -import Field from './components/field.js' - -export const isObject = value => - value && typeof value === 'object' && value.constructor === Object - -export const isBoolean = value => typeof value === 'boolean' - -export const parseEvent = target => { - const name = target.name - let value = target.value - if (target.type === 'checkbox') value = target.checked - else if (target.type === 'file') value = target.files[0] - else if (!isNaN(Number(value))) value = value === '' ? '' : Number(value) - return { name, value } -} - -const Demo = () => { - const [file, setFile] = useState('static/archives/example.zip') - const [options, setOptions] = useState({ - theme: { type: 'select', value: 'Light', options: ['Dark', 'Light'] }, - maxPages: 500, - mangaMode: false, - forceSort: false, - allowFullScreen: true, - autoHideControls: false, - allowGlobalShortcuts: false, - }) - - const handleFileChange = ({ target }) => { - const { value } = parseEvent(target) - setFile(value) - } - - const handleOptionsChange = ({ target }) => { - let { name, value } = parseEvent(target) - if (isObject(options[name])) value = { ...options[name], value } - setOptions({ ...options, [name]: value }) - } - - const optionsToFields = () => { - return Object.entries(options).map(([key, value]) => { - let type = 'text' - if (isBoolean(value)) type = 'boolean' - if (isObject(options[key]) && value.type) type = value.type - return ( - - ) - }) - } - - const optionsToProps = () => { - return Object.entries(options).reduce((accOptions, [key, value]) => { - accOptions[key] = isObject(value) ? value.value : value - return accOptions - }, {}) - } - - const optionsProps = optionsToProps() - return ( -
- -
- -
-
- ) -} - -export default Demo diff --git a/packages/villain-react/dev-sandbox/index.html b/packages/villain-react/dev-sandbox/index.html deleted file mode 100644 index ceb89df9..00000000 --- a/packages/villain-react/dev-sandbox/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - Villain Demo - - -
- - - diff --git a/packages/villain-react/dev-sandbox/index.js b/packages/villain-react/dev-sandbox/index.js deleted file mode 100644 index d879e2a3..00000000 --- a/packages/villain-react/dev-sandbox/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import React from 'react' -import ReactDOM from 'react-dom' -import Demo from './demo.js' -import './theme.css' -import './demo.css' - -ReactDOM.render(, document.getElementById('app')) diff --git a/packages/villain-react/dev-sandbox/static/archives/example.zip b/packages/villain-react/dev-sandbox/static/archives/example.zip deleted file mode 100644 index 1da39ae7..00000000 Binary files a/packages/villain-react/dev-sandbox/static/archives/example.zip and /dev/null differ diff --git a/packages/villain-react/dev-sandbox/static/wasm-gen/libarchive.js b/packages/villain-react/dev-sandbox/static/wasm-gen/libarchive.js deleted file mode 100644 index 1b76be91..00000000 --- a/packages/villain-react/dev-sandbox/static/wasm-gen/libarchive.js +++ /dev/null @@ -1,5112 +0,0 @@ -var libarchive = (function() { - var _scriptDir = - typeof document !== 'undefined' && document.currentScript - ? document.currentScript.src - : undefined - return function(libarchive) { - libarchive = libarchive || {} - - var Module = typeof libarchive !== 'undefined' ? libarchive : {} - var moduleOverrides = {} - var key - for (key in Module) { - if (Module.hasOwnProperty(key)) { - moduleOverrides[key] = Module[key] - } - } - Module['arguments'] = [] - Module['thisProgram'] = './this.program' - Module['quit'] = function(status, toThrow) { - throw toThrow - } - Module['preRun'] = [] - Module['postRun'] = [] - var ENVIRONMENT_IS_WEB = false - var ENVIRONMENT_IS_WORKER = false - var ENVIRONMENT_IS_NODE = false - var ENVIRONMENT_IS_SHELL = false - ENVIRONMENT_IS_WEB = typeof window === 'object' - ENVIRONMENT_IS_WORKER = typeof importScripts === 'function' - ENVIRONMENT_IS_NODE = - typeof process === 'object' && - typeof require === 'function' && - !ENVIRONMENT_IS_WEB && - !ENVIRONMENT_IS_WORKER - ENVIRONMENT_IS_SHELL = - !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER - var scriptDirectory = '' - function locateFile(path) { - if (Module['locateFile']) { - return Module['locateFile'](path, scriptDirectory) - } else { - return scriptDirectory + path - } - } - if (ENVIRONMENT_IS_NODE) { - scriptDirectory = __dirname + '/' - var nodeFS - var nodePath - Module['read'] = function shell_read(filename, binary) { - var ret - if (!nodeFS) nodeFS = require('fs') - if (!nodePath) nodePath = require('path') - filename = nodePath['normalize'](filename) - ret = nodeFS['readFileSync'](filename) - return binary ? ret : ret.toString() - } - Module['readBinary'] = function readBinary(filename) { - var ret = Module['read'](filename, true) - if (!ret.buffer) { - ret = new Uint8Array(ret) - } - assert(ret.buffer) - return ret - } - if (process['argv'].length > 1) { - Module['thisProgram'] = process['argv'][1].replace(/\\/g, '/') - } - Module['arguments'] = process['argv'].slice(2) - process['on']('uncaughtException', function(ex) { - if (!(ex instanceof ExitStatus)) { - throw ex - } - }) - process['on']('unhandledRejection', abort) - Module['quit'] = function(status) { - process['exit'](status) - } - Module['inspect'] = function() { - return '[Emscripten Module object]' - } - } else if (ENVIRONMENT_IS_SHELL) { - if (typeof read != 'undefined') { - Module['read'] = function shell_read(f) { - return read(f) - } - } - Module['readBinary'] = function readBinary(f) { - var data - if (typeof readbuffer === 'function') { - return new Uint8Array(readbuffer(f)) - } - data = read(f, 'binary') - assert(typeof data === 'object') - return data - } - if (typeof scriptArgs != 'undefined') { - Module['arguments'] = scriptArgs - } else if (typeof arguments != 'undefined') { - Module['arguments'] = arguments - } - if (typeof quit === 'function') { - Module['quit'] = function(status) { - quit(status) - } - } - } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href - } else if (document.currentScript) { - scriptDirectory = document.currentScript.src - } - if (_scriptDir) { - scriptDirectory = _scriptDir - } - if (scriptDirectory.indexOf('blob:') !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/') + 1) - } else { - scriptDirectory = '' - } - Module['read'] = function shell_read(url) { - var xhr = new XMLHttpRequest() - xhr.open('GET', url, false) - xhr.send(null) - return xhr.responseText - } - if (ENVIRONMENT_IS_WORKER) { - Module['readBinary'] = function readBinary(url) { - var xhr = new XMLHttpRequest() - xhr.open('GET', url, false) - xhr.responseType = 'arraybuffer' - xhr.send(null) - return new Uint8Array(xhr.response) - } - } - Module['readAsync'] = function readAsync(url, onload, onerror) { - var xhr = new XMLHttpRequest() - xhr.open('GET', url, true) - xhr.responseType = 'arraybuffer' - xhr.onload = function xhr_onload() { - if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { - onload(xhr.response) - return - } - onerror() - } - xhr.onerror = onerror - xhr.send(null) - } - Module['setWindowTitle'] = function(title) { - document.title = title - } - } else { - } - var out = - Module['print'] || - (typeof console !== 'undefined' - ? console.log.bind(console) - : typeof print !== 'undefined' - ? print - : null) - var err = - Module['printErr'] || - (typeof printErr !== 'undefined' - ? printErr - : (typeof console !== 'undefined' && console.warn.bind(console)) || out) - for (key in moduleOverrides) { - if (moduleOverrides.hasOwnProperty(key)) { - Module[key] = moduleOverrides[key] - } - } - moduleOverrides = undefined - function dynamicAlloc(size) { - var ret = HEAP32[DYNAMICTOP_PTR >> 2] - var end = (ret + size + 15) & -16 - if (end <= _emscripten_get_heap_size()) { - HEAP32[DYNAMICTOP_PTR >> 2] = end - } else { - var success = _emscripten_resize_heap(end) - if (!success) return 0 - } - return ret - } - function getNativeTypeSize(type) { - switch (type) { - case 'i1': - case 'i8': - return 1 - case 'i16': - return 2 - case 'i32': - return 4 - case 'i64': - return 8 - case 'float': - return 4 - case 'double': - return 8 - default: { - if (type[type.length - 1] === '*') { - return 4 - } else if (type[0] === 'i') { - var bits = parseInt(type.substr(1)) - assert( - bits % 8 === 0, - 'getNativeTypeSize invalid bits ' + bits + ', type ' + type - ) - return bits / 8 - } else { - return 0 - } - } - } - } - var asm2wasmImports = { - 'f64-rem': function(x, y) { - return x % y - }, - debugger: function() { - debugger - }, - } - var functionPointers = new Array(0) - var tempRet0 = 0 - var setTempRet0 = function(value) { - tempRet0 = value - } - if (typeof WebAssembly !== 'object') { - err('no native wasm support detected') - } - var wasmMemory - var wasmTable - var ABORT = false - var EXITSTATUS = 0 - function assert(condition, text) { - if (!condition) { - abort('Assertion failed: ' + text) - } - } - function getCFunc(ident) { - var func = Module['_' + ident] - assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported') - return func - } - function ccall(ident, returnType, argTypes, args, opts) { - var toC = { - string: function(str) { - var ret = 0 - if (str !== null && str !== undefined && str !== 0) { - var len = (str.length << 2) + 1 - ret = stackAlloc(len) - stringToUTF8(str, ret, len) - } - return ret - }, - array: function(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.apply(null, cArgs) - ret = convertReturnValue(ret) - if (stack !== 0) stackRestore(stack) - return ret - } - function cwrap(ident, returnType, argTypes, opts) { - argTypes = argTypes || [] - var numericArgs = argTypes.every(function(type) { - return type === 'number' - }) - var numericRet = returnType !== 'string' - if (numericRet && numericArgs && !opts) { - return getCFunc(ident) - } - return function() { - return ccall(ident, returnType, argTypes, arguments, opts) - } - } - function setValue(ptr, value, type, noSafe) { - type = type || 'i8' - if (type.charAt(type.length - 1) === '*') type = 'i32' - switch (type) { - case 'i1': - HEAP8[ptr >> 0] = value - break - case 'i8': - HEAP8[ptr >> 0] = value - break - case 'i16': - HEAP16[ptr >> 1] = value - break - case 'i32': - HEAP32[ptr >> 2] = value - break - case 'i64': - ;(tempI64 = [ - value >>> 0, - ((tempDouble = value), - +Math_abs(tempDouble) >= 1 - ? tempDouble > 0 - ? (Math_min(+Math_floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 - : ~~+Math_ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (HEAP32[ptr >> 2] = tempI64[0]), - (HEAP32[(ptr + 4) >> 2] = tempI64[1]) - break - case 'float': - HEAPF32[ptr >> 2] = value - break - case 'double': - HEAPF64[ptr >> 3] = value - break - default: - abort('invalid type for setValue: ' + type) - } - } - var ALLOC_NORMAL = 0 - var ALLOC_NONE = 3 - function allocate(slab, types, allocator, ptr) { - var zeroinit, size - if (typeof slab === 'number') { - zeroinit = true - size = slab - } else { - zeroinit = false - size = slab.length - } - var singleType = typeof types === 'string' ? types : null - var ret - if (allocator == ALLOC_NONE) { - ret = ptr - } else { - ret = [_malloc, stackAlloc, dynamicAlloc][allocator]( - Math.max(size, singleType ? 1 : types.length) - ) - } - if (zeroinit) { - var stop - ptr = ret - assert((ret & 3) == 0) - stop = ret + (size & ~3) - for (; ptr < stop; ptr += 4) { - HEAP32[ptr >> 2] = 0 - } - stop = ret + size - while (ptr < stop) { - HEAP8[ptr++ >> 0] = 0 - } - return ret - } - if (singleType === 'i8') { - if (slab.subarray || slab.slice) { - HEAPU8.set(slab, ret) - } else { - HEAPU8.set(new Uint8Array(slab), ret) - } - return ret - } - var i = 0, - type, - typeSize, - previousType - while (i < size) { - var curr = slab[i] - type = singleType || types[i] - if (type === 0) { - i++ - continue - } - if (type == 'i64') type = 'i32' - setValue(ret + i, curr, type) - if (previousType !== type) { - typeSize = getNativeTypeSize(type) - previousType = type - } - i += typeSize - } - return ret - } - function getMemory(size) { - if (!runtimeInitialized) return dynamicAlloc(size) - return _malloc(size) - } - var UTF8Decoder = - typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined - function UTF8ArrayToString(u8Array, idx, maxBytesToRead) { - var endIdx = idx + maxBytesToRead - var endPtr = idx - while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr - if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) { - return UTF8Decoder.decode(u8Array.subarray(idx, endPtr)) - } else { - var str = '' - while (idx < endPtr) { - var u0 = u8Array[idx++] - if (!(u0 & 128)) { - str += String.fromCharCode(u0) - continue - } - var u1 = u8Array[idx++] & 63 - if ((u0 & 224) == 192) { - str += String.fromCharCode(((u0 & 31) << 6) | u1) - continue - } - var u2 = u8Array[idx++] & 63 - if ((u0 & 240) == 224) { - u0 = ((u0 & 15) << 12) | (u1 << 6) | u2 - } else { - u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (u8Array[idx++] & 63) - } - if (u0 < 65536) { - str += String.fromCharCode(u0) - } else { - var ch = u0 - 65536 - str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)) - } - } - } - return str - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '' - } - function stringToUTF8Array(str, outU8Array, 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.charCodeAt(i) - if (u >= 55296 && u <= 57343) { - var u1 = str.charCodeAt(++i) - u = (65536 + ((u & 1023) << 10)) | (u1 & 1023) - } - if (u <= 127) { - if (outIdx >= endIdx) break - outU8Array[outIdx++] = u - } else if (u <= 2047) { - if (outIdx + 1 >= endIdx) break - outU8Array[outIdx++] = 192 | (u >> 6) - outU8Array[outIdx++] = 128 | (u & 63) - } else if (u <= 65535) { - if (outIdx + 2 >= endIdx) break - outU8Array[outIdx++] = 224 | (u >> 12) - outU8Array[outIdx++] = 128 | ((u >> 6) & 63) - outU8Array[outIdx++] = 128 | (u & 63) - } else { - if (outIdx + 3 >= endIdx) break - outU8Array[outIdx++] = 240 | (u >> 18) - outU8Array[outIdx++] = 128 | ((u >> 12) & 63) - outU8Array[outIdx++] = 128 | ((u >> 6) & 63) - outU8Array[outIdx++] = 128 | (u & 63) - } - } - outU8Array[outIdx] = 0 - return outIdx - startIdx - } - function stringToUTF8(str, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) - } - function lengthBytesUTF8(str) { - var len = 0 - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i) - if (u >= 55296 && u <= 57343) - u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023) - if (u <= 127) ++len - else if (u <= 2047) len += 2 - else if (u <= 65535) len += 3 - else len += 4 - } - return len - } - var UTF16Decoder = - typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined - function writeArrayToMemory(array, buffer) { - HEAP8.set(array, buffer) - } - function writeAsciiToMemory(str, buffer, dontAddNull) { - for (var i = 0; i < str.length; ++i) { - HEAP8[buffer++ >> 0] = str.charCodeAt(i) - } - if (!dontAddNull) HEAP8[buffer >> 0] = 0 - } - function demangle(func) { - return func - } - function demangleAll(text) { - var regex = /__Z[\w\d_]+/g - return text.replace(regex, function(x) { - var y = demangle(x) - return x === y ? x : y + ' [' + x + ']' - }) - } - function jsStackTrace() { - var err = new Error() - if (!err.stack) { - try { - throw new Error(0) - } catch (e) { - err = e - } - if (!err.stack) { - return '(no stack trace available)' - } - } - return err.stack.toString() - } - function stackTrace() { - var js = jsStackTrace() - if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']() - return demangleAll(js) - } - var WASM_PAGE_SIZE = 65536 - function alignUp(x, multiple) { - if (x % multiple > 0) { - x += multiple - (x % multiple) - } - return x - } - var buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64 - function updateGlobalBufferViews() { - Module['HEAP8'] = HEAP8 = new Int8Array(buffer) - Module['HEAP16'] = HEAP16 = new Int16Array(buffer) - Module['HEAP32'] = HEAP32 = new Int32Array(buffer) - Module['HEAPU8'] = HEAPU8 = new Uint8Array(buffer) - Module['HEAPU16'] = HEAPU16 = new Uint16Array(buffer) - Module['HEAPU32'] = HEAPU32 = new Uint32Array(buffer) - Module['HEAPF32'] = HEAPF32 = new Float32Array(buffer) - Module['HEAPF64'] = HEAPF64 = new Float64Array(buffer) - } - var DYNAMIC_BASE = 5520464, - DYNAMICTOP_PTR = 277552 - var TOTAL_STACK = 5242880 - var INITIAL_TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 16777216 - if (INITIAL_TOTAL_MEMORY < TOTAL_STACK) - err( - 'TOTAL_MEMORY should be larger than TOTAL_STACK, was ' + - INITIAL_TOTAL_MEMORY + - '! (TOTAL_STACK=' + - TOTAL_STACK + - ')' - ) - if (Module['buffer']) { - buffer = Module['buffer'] - } else { - if (typeof WebAssembly === 'object' && typeof WebAssembly.Memory === 'function') { - wasmMemory = new WebAssembly.Memory({ - initial: INITIAL_TOTAL_MEMORY / WASM_PAGE_SIZE, - }) - buffer = wasmMemory.buffer - } else { - buffer = new ArrayBuffer(INITIAL_TOTAL_MEMORY) - } - } - updateGlobalBufferViews() - HEAP32[DYNAMICTOP_PTR >> 2] = DYNAMIC_BASE - function callRuntimeCallbacks(callbacks) { - while (callbacks.length > 0) { - var callback = callbacks.shift() - if (typeof callback == 'function') { - callback() - continue - } - var func = callback.func - if (typeof func === 'number') { - if (callback.arg === undefined) { - Module['dynCall_v'](func) - } else { - Module['dynCall_vi'](func, callback.arg) - } - } else { - func(callback.arg === undefined ? null : callback.arg) - } - } - } - var __ATPRERUN__ = [] - var __ATINIT__ = [] - var __ATMAIN__ = [] - var __ATPOSTRUN__ = [] - var runtimeInitialized = false - var runtimeExited = false - function preRun() { - if (Module['preRun']) { - if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']] - while (Module['preRun'].length) { - addOnPreRun(Module['preRun'].shift()) - } - } - callRuntimeCallbacks(__ATPRERUN__) - } - function ensureInitRuntime() { - if (runtimeInitialized) return - runtimeInitialized = true - if (!Module['noFSInit'] && !FS.init.initialized) FS.init() - TTY.init() - PIPEFS.root = FS.mount(PIPEFS, {}, null) - callRuntimeCallbacks(__ATINIT__) - } - function preMain() { - FS.ignorePermissions = false - callRuntimeCallbacks(__ATMAIN__) - } - function exitRuntime() { - runtimeExited = true - } - function postRun() { - if (Module['postRun']) { - if (typeof Module['postRun'] == 'function') - Module['postRun'] = [Module['postRun']] - while (Module['postRun'].length) { - addOnPostRun(Module['postRun'].shift()) - } - } - callRuntimeCallbacks(__ATPOSTRUN__) - } - function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb) - } - function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb) - } - var Math_abs = Math.abs - var Math_ceil = Math.ceil - var Math_floor = Math.floor - var Math_min = Math.min - var runDependencies = 0 - var runDependencyWatcher = null - var dependenciesFulfilled = null - function getUniqueRunDependency(id) { - return id - } - function addRunDependency(id) { - runDependencies++ - if (Module['monitorRunDependencies']) { - Module['monitorRunDependencies'](runDependencies) - } - } - function removeRunDependency(id) { - runDependencies-- - if (Module['monitorRunDependencies']) { - Module['monitorRunDependencies'](runDependencies) - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher) - runDependencyWatcher = null - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled - dependenciesFulfilled = null - callback() - } - } - } - Module['preloadedImages'] = {} - Module['preloadedAudios'] = {} - var dataURIPrefix = 'data:application/octet-stream;base64,' - function isDataURI(filename) { - return String.prototype.startsWith - ? filename.startsWith(dataURIPrefix) - : filename.indexOf(dataURIPrefix) === 0 - } - var wasmBinaryFile = 'libarchive.wasm' - if (!isDataURI(wasmBinaryFile)) { - wasmBinaryFile = locateFile(wasmBinaryFile) - } - function getBinary() { - try { - if (Module['wasmBinary']) { - return new Uint8Array(Module['wasmBinary']) - } - if (Module['readBinary']) { - return Module['readBinary'](wasmBinaryFile) - } else { - throw 'both async and sync fetching of the wasm failed' - } - } catch (err) { - abort(err) - } - } - function getBinaryPromise() { - if ( - !Module['wasmBinary'] && - (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && - typeof fetch === 'function' - ) { - return fetch(wasmBinaryFile, { credentials: 'same-origin' }) - .then(function(response) { - if (!response['ok']) { - throw "failed to load wasm binary file at '" + wasmBinaryFile + "'" - } - return response['arrayBuffer']() - }) - .catch(function() { - return getBinary() - }) - } - return new Promise(function(resolve, reject) { - resolve(getBinary()) - }) - } - function createWasm(env) { - var info = { - env: env, - global: { NaN: NaN, Infinity: Infinity }, - 'global.Math': Math, - asm2wasm: asm2wasmImports, - } - function receiveInstance(instance, module) { - var exports = instance.exports - Module['asm'] = exports - removeRunDependency('wasm-instantiate') - } - addRunDependency('wasm-instantiate') - if (Module['instantiateWasm']) { - try { - return Module['instantiateWasm'](info, receiveInstance) - } catch (e) { - err('Module.instantiateWasm callback failed with error: ' + e) - return false - } - } - function receiveInstantiatedSource(output) { - receiveInstance(output['instance']) - } - function instantiateArrayBuffer(receiver) { - getBinaryPromise() - .then(function(binary) { - return WebAssembly.instantiate(binary, info) - }) - .then(receiver, function(reason) { - err('failed to asynchronously prepare wasm: ' + reason) - abort(reason) - }) - } - if ( - !Module['wasmBinary'] && - typeof WebAssembly.instantiateStreaming === 'function' && - !isDataURI(wasmBinaryFile) && - typeof fetch === 'function' - ) { - WebAssembly.instantiateStreaming( - fetch(wasmBinaryFile, { credentials: 'same-origin' }), - info - ).then(receiveInstantiatedSource, function(reason) { - err('wasm streaming compile failed: ' + reason) - err('falling back to ArrayBuffer instantiation') - instantiateArrayBuffer(receiveInstantiatedSource) - }) - } else { - instantiateArrayBuffer(receiveInstantiatedSource) - } - return {} - } - Module['asm'] = function(global, env, providedBuffer) { - env['memory'] = wasmMemory - env['table'] = wasmTable = new WebAssembly.Table({ - initial: 507, - maximum: 507, - element: 'anyfunc', - }) - env['__memory_base'] = 1024 - env['__table_base'] = 0 - var exports = createWasm(env) - return exports - } - __ATINIT__.push({ - func: function() { - ___emscripten_environ_constructor() - }, - }) - var ENV = {} - function ___buildEnvironment(environ) { - var MAX_ENV_VALUES = 64 - var TOTAL_ENV_SIZE = 1024 - var poolPtr - var envPtr - if (!___buildEnvironment.called) { - ___buildEnvironment.called = true - ENV['USER'] = ENV['LOGNAME'] = 'web_user' - ENV['PATH'] = '/' - ENV['PWD'] = '/' - ENV['HOME'] = '/home/web_user' - ENV['LANG'] = 'C.UTF-8' - ENV['_'] = Module['thisProgram'] - poolPtr = getMemory(TOTAL_ENV_SIZE) - envPtr = getMemory(MAX_ENV_VALUES * 4) - HEAP32[envPtr >> 2] = poolPtr - HEAP32[environ >> 2] = envPtr - } else { - envPtr = HEAP32[environ >> 2] - poolPtr = HEAP32[envPtr >> 2] - } - var strings = [] - var totalSize = 0 - for (var key in ENV) { - if (typeof ENV[key] === 'string') { - var line = key + '=' + ENV[key] - strings.push(line) - totalSize += line.length - } - } - if (totalSize > TOTAL_ENV_SIZE) { - throw new Error('Environment size exceeded TOTAL_ENV_SIZE!') - } - var ptrSize = 4 - for (var i = 0; i < strings.length; i++) { - var line = strings[i] - writeAsciiToMemory(line, poolPtr) - HEAP32[(envPtr + i * ptrSize) >> 2] = poolPtr - poolPtr += line.length + 1 - } - HEAP32[(envPtr + strings.length * ptrSize) >> 2] = 0 - } - var PATH = { - splitPath: function(filename) { - var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/ - return splitPathRe.exec(filename).slice(1) - }, - normalizeArray: function(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: function(path) { - var isAbsolute = path.charAt(0) === '/', - trailingSlash = path.substr(-1) === '/' - path = PATH.normalizeArray( - path.split('/').filter(function(p) { - return !!p - }), - !isAbsolute - ).join('/') - if (!path && !isAbsolute) { - path = '.' - } - if (path && trailingSlash) { - path += '/' - } - return (isAbsolute ? '/' : '') + path - }, - dirname: function(path) { - var result = PATH.splitPath(path), - root = result[0], - dir = result[1] - if (!root && !dir) { - return '.' - } - if (dir) { - dir = dir.substr(0, dir.length - 1) - } - return root + dir - }, - basename: function(path) { - if (path === '/') return '/' - var lastSlash = path.lastIndexOf('/') - if (lastSlash === -1) return path - return path.substr(lastSlash + 1) - }, - extname: function(path) { - return PATH.splitPath(path)[3] - }, - join: function() { - var paths = Array.prototype.slice.call(arguments, 0) - return PATH.normalize(paths.join('/')) - }, - join2: function(l, r) { - return PATH.normalize(l + '/' + r) - }, - } - function ___setErrNo(value) { - if (Module['___errno_location']) HEAP32[Module['___errno_location']() >> 2] = value - return value - } - var PATH_FS = { - resolve: function() { - var resolvedPath = '', - resolvedAbsolute = false - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = i >= 0 ? arguments[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.charAt(0) === '/' - } - resolvedPath = PATH.normalizeArray( - resolvedPath.split('/').filter(function(p) { - return !!p - }), - !resolvedAbsolute - ).join('/') - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.' - }, - relative: function(from, to) { - from = PATH_FS.resolve(from).substr(1) - to = PATH_FS.resolve(to).substr(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 TTY = { - ttys: [], - init: function() {}, - shutdown: function() {}, - register: function(dev, ops) { - TTY.ttys[dev] = { input: [], output: [], ops: ops } - FS.registerDevice(dev, TTY.stream_ops) - }, - stream_ops: { - open: function(stream) { - var tty = TTY.ttys[stream.node.rdev] - if (!tty) { - throw new FS.ErrnoError(19) - } - stream.tty = tty - stream.seekable = false - }, - close: function(stream) { - stream.tty.ops.flush(stream.tty) - }, - flush: function(stream) { - stream.tty.ops.flush(stream.tty) - }, - read: function(stream, buffer, offset, length, pos) { - if (!stream.tty || !stream.tty.ops.get_char) { - throw new FS.ErrnoError(6) - } - 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(5) - } - if (result === undefined && bytesRead === 0) { - throw new FS.ErrnoError(11) - } - if (result === null || result === undefined) break - bytesRead++ - buffer[offset + i] = result - } - if (bytesRead) { - stream.node.timestamp = Date.now() - } - return bytesRead - }, - write: function(stream, buffer, offset, length, pos) { - if (!stream.tty || !stream.tty.ops.put_char) { - throw new FS.ErrnoError(6) - } - try { - for (var i = 0; i < length; i++) { - stream.tty.ops.put_char(stream.tty, buffer[offset + i]) - } - } catch (e) { - throw new FS.ErrnoError(5) - } - if (length) { - stream.node.timestamp = Date.now() - } - return i - }, - }, - default_tty_ops: { - get_char: function(tty) { - if (!tty.input.length) { - var result = null - if (ENVIRONMENT_IS_NODE) { - var BUFSIZE = 256 - var buf = new Buffer(BUFSIZE) - var bytesRead = 0 - var isPosixPlatform = process.platform != 'win32' - var fd = process.stdin.fd - if (isPosixPlatform) { - var usingDevice = false - try { - fd = fs.openSync('/dev/stdin', 'r') - usingDevice = true - } catch (e) {} - } - try { - bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null) - } catch (e) { - if (e.toString().indexOf('EOF') != -1) bytesRead = 0 - else throw e - } - if (usingDevice) { - fs.closeSync(fd) - } - if (bytesRead > 0) { - result = buf.slice(0, bytesRead).toString('utf-8') - } else { - result = null - } - } else if ( - typeof window != 'undefined' && - typeof window.prompt == 'function' - ) { - result = window.prompt('Input: ') - if (result !== null) { - result += '\n' - } - } else if (typeof readline == 'function') { - result = readline() - if (result !== null) { - result += '\n' - } - } - if (!result) { - return null - } - tty.input = intArrayFromString(result, true) - } - return tty.input.shift() - }, - put_char: function(tty, val) { - if (val === null || val === 10) { - out(UTF8ArrayToString(tty.output, 0)) - tty.output = [] - } else { - if (val != 0) tty.output.push(val) - } - }, - flush: function(tty) { - if (tty.output && tty.output.length > 0) { - out(UTF8ArrayToString(tty.output, 0)) - tty.output = [] - } - }, - }, - default_tty1_ops: { - put_char: function(tty, val) { - if (val === null || val === 10) { - err(UTF8ArrayToString(tty.output, 0)) - tty.output = [] - } else { - if (val != 0) tty.output.push(val) - } - }, - flush: function(tty) { - if (tty.output && tty.output.length > 0) { - err(UTF8ArrayToString(tty.output, 0)) - tty.output = [] - } - }, - }, - } - var MEMFS = { - ops_table: null, - mount: function(mount) { - return MEMFS.createNode(null, '/', 16384 | 511, 0) - }, - createNode: function(parent, name, mode, dev) { - if (FS.isBlkdev(mode) || FS.isFIFO(mode)) { - throw new FS.ErrnoError(1) - } - if (!MEMFS.ops_table) { - 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, - allocate: MEMFS.stream_ops.allocate, - 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.timestamp = Date.now() - if (parent) { - parent.contents[name] = node - } - return node - }, - getFileDataAsRegularArray: function(node) { - if (node.contents && node.contents.subarray) { - var arr = [] - for (var i = 0; i < node.usedBytes; ++i) arr.push(node.contents[i]) - return arr - } - return node.contents - }, - getFileDataAsTypedArray: function(node) { - if (!node.contents) return new Uint8Array() - if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes) - return new Uint8Array(node.contents) - }, - expandFileStorage: function(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) - return - }, - resizeFileStorage: function(node, newSize) { - if (node.usedBytes == newSize) return - if (newSize == 0) { - node.contents = null - node.usedBytes = 0 - return - } - if (!node.contents || node.contents.subarray) { - var oldContents = node.contents - node.contents = new Uint8Array(new ArrayBuffer(newSize)) - if (oldContents) { - node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))) - } - node.usedBytes = newSize - return - } - if (!node.contents) node.contents = [] - if (node.contents.length > newSize) node.contents.length = newSize - else while (node.contents.length < newSize) node.contents.push(0) - node.usedBytes = newSize - }, - node_ops: { - getattr: function(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.timestamp) - attr.mtime = new Date(node.timestamp) - attr.ctime = new Date(node.timestamp) - attr.blksize = 4096 - attr.blocks = Math.ceil(attr.size / attr.blksize) - return attr - }, - setattr: function(node, attr) { - if (attr.mode !== undefined) { - node.mode = attr.mode - } - if (attr.timestamp !== undefined) { - node.timestamp = attr.timestamp - } - if (attr.size !== undefined) { - MEMFS.resizeFileStorage(node, attr.size) - } - }, - lookup: function(parent, name) { - throw FS.genericErrors[2] - }, - mknod: function(parent, name, mode, dev) { - return MEMFS.createNode(parent, name, mode, dev) - }, - rename: function(old_node, new_dir, new_name) { - if (FS.isDir(old_node.mode)) { - var new_node - try { - new_node = FS.lookupNode(new_dir, new_name) - } catch (e) {} - if (new_node) { - for (var i in new_node.contents) { - throw new FS.ErrnoError(39) - } - } - } - delete old_node.parent.contents[old_node.name] - old_node.name = new_name - new_dir.contents[new_name] = old_node - old_node.parent = new_dir - }, - unlink: function(parent, name) { - delete parent.contents[name] - }, - rmdir: function(parent, name) { - var node = FS.lookupNode(parent, name) - for (var i in node.contents) { - throw new FS.ErrnoError(39) - } - delete parent.contents[name] - }, - readdir: function(node) { - var entries = ['.', '..'] - for (var key in node.contents) { - if (!node.contents.hasOwnProperty(key)) { - continue - } - entries.push(key) - } - return entries - }, - symlink: function(parent, newname, oldpath) { - var node = MEMFS.createNode(parent, newname, 511 | 40960, 0) - node.link = oldpath - return node - }, - readlink: function(node) { - if (!FS.isLink(node.mode)) { - throw new FS.ErrnoError(22) - } - return node.link - }, - }, - stream_ops: { - read: function(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: function(stream, buffer, offset, length, position, canOwn) { - canOwn = false - if (!length) return 0 - var node = stream.node - node.timestamp = 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 = new Uint8Array(buffer.subarray(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: function(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(22) - } - return position - }, - allocate: function(stream, offset, length) { - MEMFS.expandFileStorage(stream.node, offset + length) - stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length) - }, - mmap: function(stream, buffer, offset, length, position, prot, flags) { - if (!FS.isFile(stream.node.mode)) { - throw new FS.ErrnoError(19) - } - var ptr - var allocated - var contents = stream.node.contents - if ( - !(flags & 2) && - (contents.buffer === buffer || contents.buffer === buffer.buffer) - ) { - allocated = false - ptr = contents.byteOffset - } else { - if (position > 0 || position + length < stream.node.usedBytes) { - if (contents.subarray) { - contents = contents.subarray(position, position + length) - } else { - contents = Array.prototype.slice.call( - contents, - position, - position + length - ) - } - } - allocated = true - ptr = _malloc(length) - if (!ptr) { - throw new FS.ErrnoError(12) - } - buffer.set(contents, ptr) - } - return { ptr: ptr, allocated: allocated } - }, - msync: function(stream, buffer, offset, length, mmapFlags) { - if (!FS.isFile(stream.node.mode)) { - throw new FS.ErrnoError(19) - } - if (mmapFlags & 2) { - return 0 - } - var bytesWritten = MEMFS.stream_ops.write( - stream, - buffer, - 0, - length, - offset, - false - ) - return 0 - }, - }, - } - var IDBFS = { - dbs: {}, - indexedDB: function() { - if (typeof indexedDB !== 'undefined') return indexedDB - var ret = null - if (typeof window === 'object') - ret = - window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB - assert(ret, 'IDBFS used, but indexedDB not supported') - return ret - }, - DB_VERSION: 21, - DB_STORE_NAME: 'FILE_DATA', - mount: function(mount) { - return MEMFS.mount.apply(null, arguments) - }, - syncfs: function(mount, populate, callback) { - IDBFS.getLocalSet(mount, function(err, local) { - if (err) return callback(err) - IDBFS.getRemoteSet(mount, function(err, remote) { - if (err) return callback(err) - var src = populate ? remote : local - var dst = populate ? local : remote - IDBFS.reconcile(src, dst, callback) - }) - }) - }, - getDB: function(name, callback) { - var db = IDBFS.dbs[name] - if (db) { - return callback(null, db) - } - var req - try { - req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION) - } catch (e) { - return callback(e) - } - if (!req) { - return callback('Unable to connect to IndexedDB') - } - req.onupgradeneeded = function(e) { - var db = e.target.result - var transaction = e.target.transaction - var fileStore - if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) { - fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME) - } else { - fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME) - } - if (!fileStore.indexNames.contains('timestamp')) { - fileStore.createIndex('timestamp', 'timestamp', { unique: false }) - } - } - req.onsuccess = function() { - db = req.result - IDBFS.dbs[name] = db - callback(null, db) - } - req.onerror = function(e) { - callback(this.error) - e.preventDefault() - } - }, - getLocalSet: function(mount, callback) { - var entries = {} - function isRealDir(p) { - return p !== '.' && p !== '..' - } - function toAbsolute(root) { - return function(p) { - return PATH.join2(root, p) - } - } - var check = FS.readdir(mount.mountpoint) - .filter(isRealDir) - .map(toAbsolute(mount.mountpoint)) - while (check.length) { - var path = check.pop() - var stat - try { - stat = FS.stat(path) - } catch (e) { - return callback(e) - } - if (FS.isDir(stat.mode)) { - check.push.apply( - check, - FS.readdir(path) - .filter(isRealDir) - .map(toAbsolute(path)) - ) - } - entries[path] = { timestamp: stat.mtime } - } - return callback(null, { type: 'local', entries: entries }) - }, - getRemoteSet: function(mount, callback) { - var entries = {} - IDBFS.getDB(mount.mountpoint, function(err, db) { - if (err) return callback(err) - try { - var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly') - transaction.onerror = function(e) { - callback(this.error) - e.preventDefault() - } - var store = transaction.objectStore(IDBFS.DB_STORE_NAME) - var index = store.index('timestamp') - index.openKeyCursor().onsuccess = function(event) { - var cursor = event.target.result - if (!cursor) { - return callback(null, { type: 'remote', db: db, entries: entries }) - } - entries[cursor.primaryKey] = { timestamp: cursor.key } - cursor.continue() - } - } catch (e) { - return callback(e) - } - }) - }, - loadLocalEntry: function(path, callback) { - var stat, node - try { - var lookup = FS.lookupPath(path) - node = lookup.node - stat = FS.stat(path) - } catch (e) { - return callback(e) - } - if (FS.isDir(stat.mode)) { - return callback(null, { timestamp: stat.mtime, mode: stat.mode }) - } else if (FS.isFile(stat.mode)) { - node.contents = MEMFS.getFileDataAsTypedArray(node) - return callback(null, { - timestamp: stat.mtime, - mode: stat.mode, - contents: node.contents, - }) - } else { - return callback(new Error('node type not supported')) - } - }, - storeLocalEntry: function(path, entry, callback) { - try { - if (FS.isDir(entry.mode)) { - FS.mkdir(path, entry.mode) - } else if (FS.isFile(entry.mode)) { - FS.writeFile(path, entry.contents, { canOwn: true }) - } else { - return callback(new Error('node type not supported')) - } - FS.chmod(path, entry.mode) - FS.utime(path, entry.timestamp, entry.timestamp) - } catch (e) { - return callback(e) - } - callback(null) - }, - removeLocalEntry: function(path, callback) { - try { - var lookup = FS.lookupPath(path) - var stat = FS.stat(path) - if (FS.isDir(stat.mode)) { - FS.rmdir(path) - } else if (FS.isFile(stat.mode)) { - FS.unlink(path) - } - } catch (e) { - return callback(e) - } - callback(null) - }, - loadRemoteEntry: function(store, path, callback) { - var req = store.get(path) - req.onsuccess = function(event) { - callback(null, event.target.result) - } - req.onerror = function(e) { - callback(this.error) - e.preventDefault() - } - }, - storeRemoteEntry: function(store, path, entry, callback) { - var req = store.put(entry, path) - req.onsuccess = function() { - callback(null) - } - req.onerror = function(e) { - callback(this.error) - e.preventDefault() - } - }, - removeRemoteEntry: function(store, path, callback) { - var req = store.delete(path) - req.onsuccess = function() { - callback(null) - } - req.onerror = function(e) { - callback(this.error) - e.preventDefault() - } - }, - reconcile: function(src, dst, callback) { - var total = 0 - var create = [] - Object.keys(src.entries).forEach(function(key) { - var e = src.entries[key] - var e2 = dst.entries[key] - if (!e2 || e.timestamp > e2.timestamp) { - create.push(key) - total++ - } - }) - var remove = [] - Object.keys(dst.entries).forEach(function(key) { - var e = dst.entries[key] - var e2 = src.entries[key] - if (!e2) { - remove.push(key) - total++ - } - }) - if (!total) { - return callback(null) - } - var errored = false - var completed = 0 - var db = src.type === 'remote' ? src.db : dst.db - var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite') - var store = transaction.objectStore(IDBFS.DB_STORE_NAME) - function done(err) { - if (err) { - if (!done.errored) { - done.errored = true - return callback(err) - } - return - } - if (++completed >= total) { - return callback(null) - } - } - transaction.onerror = function(e) { - done(this.error) - e.preventDefault() - } - create.sort().forEach(function(path) { - if (dst.type === 'local') { - IDBFS.loadRemoteEntry(store, path, function(err, entry) { - if (err) return done(err) - IDBFS.storeLocalEntry(path, entry, done) - }) - } else { - IDBFS.loadLocalEntry(path, function(err, entry) { - if (err) return done(err) - IDBFS.storeRemoteEntry(store, path, entry, done) - }) - } - }) - remove - .sort() - .reverse() - .forEach(function(path) { - if (dst.type === 'local') { - IDBFS.removeLocalEntry(path, done) - } else { - IDBFS.removeRemoteEntry(store, path, done) - } - }) - }, - } - var NODEFS = { - isWindows: false, - staticInit: function() { - NODEFS.isWindows = !!process.platform.match(/^win/) - var flags = process['binding']('constants') - if (flags['fs']) { - flags = flags['fs'] - } - NODEFS.flagsForNodeMap = { - 1024: flags['O_APPEND'], - 64: flags['O_CREAT'], - 128: flags['O_EXCL'], - 0: flags['O_RDONLY'], - 2: flags['O_RDWR'], - 4096: flags['O_SYNC'], - 512: flags['O_TRUNC'], - 1: flags['O_WRONLY'], - } - }, - bufferFrom: function(arrayBuffer) { - return Buffer.alloc ? Buffer.from(arrayBuffer) : new Buffer(arrayBuffer) - }, - mount: function(mount) { - assert(ENVIRONMENT_IS_NODE) - return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0) - }, - createNode: function(parent, name, mode, dev) { - if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) { - throw new FS.ErrnoError(22) - } - var node = FS.createNode(parent, name, mode) - node.node_ops = NODEFS.node_ops - node.stream_ops = NODEFS.stream_ops - return node - }, - getMode: function(path) { - var stat - try { - stat = fs.lstatSync(path) - if (NODEFS.isWindows) { - stat.mode = stat.mode | ((stat.mode & 292) >> 2) - } - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - return stat.mode - }, - realPath: function(node) { - var parts = [] - while (node.parent !== node) { - parts.push(node.name) - node = node.parent - } - parts.push(node.mount.opts.root) - parts.reverse() - return PATH.join.apply(null, parts) - }, - flagsForNode: function(flags) { - flags &= ~2097152 - flags &= ~2048 - flags &= ~32768 - flags &= ~524288 - var newFlags = 0 - for (var k in NODEFS.flagsForNodeMap) { - if (flags & k) { - newFlags |= NODEFS.flagsForNodeMap[k] - flags ^= k - } - } - if (!flags) { - return newFlags - } else { - throw new FS.ErrnoError(22) - } - }, - node_ops: { - getattr: function(node) { - var path = NODEFS.realPath(node) - var stat - try { - stat = fs.lstatSync(path) - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - if (NODEFS.isWindows && !stat.blksize) { - stat.blksize = 4096 - } - if (NODEFS.isWindows && !stat.blocks) { - stat.blocks = ((stat.size + stat.blksize - 1) / stat.blksize) | 0 - } - return { - dev: stat.dev, - ino: stat.ino, - mode: stat.mode, - nlink: stat.nlink, - uid: stat.uid, - gid: stat.gid, - rdev: stat.rdev, - size: stat.size, - atime: stat.atime, - mtime: stat.mtime, - ctime: stat.ctime, - blksize: stat.blksize, - blocks: stat.blocks, - } - }, - setattr: function(node, attr) { - var path = NODEFS.realPath(node) - try { - if (attr.mode !== undefined) { - fs.chmodSync(path, attr.mode) - node.mode = attr.mode - } - if (attr.timestamp !== undefined) { - var date = new Date(attr.timestamp) - fs.utimesSync(path, date, date) - } - if (attr.size !== undefined) { - fs.truncateSync(path, attr.size) - } - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - lookup: function(parent, name) { - var path = PATH.join2(NODEFS.realPath(parent), name) - var mode = NODEFS.getMode(path) - return NODEFS.createNode(parent, name, mode) - }, - mknod: function(parent, name, mode, dev) { - var node = NODEFS.createNode(parent, name, mode, dev) - var path = NODEFS.realPath(node) - try { - if (FS.isDir(node.mode)) { - fs.mkdirSync(path, node.mode) - } else { - fs.writeFileSync(path, '', { mode: node.mode }) - } - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - return node - }, - rename: function(oldNode, newDir, newName) { - var oldPath = NODEFS.realPath(oldNode) - var newPath = PATH.join2(NODEFS.realPath(newDir), newName) - try { - fs.renameSync(oldPath, newPath) - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - unlink: function(parent, name) { - var path = PATH.join2(NODEFS.realPath(parent), name) - try { - fs.unlinkSync(path) - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - rmdir: function(parent, name) { - var path = PATH.join2(NODEFS.realPath(parent), name) - try { - fs.rmdirSync(path) - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - readdir: function(node) { - var path = NODEFS.realPath(node) - try { - return fs.readdirSync(path) - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - symlink: function(parent, newName, oldPath) { - var newPath = PATH.join2(NODEFS.realPath(parent), newName) - try { - fs.symlinkSync(oldPath, newPath) - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - readlink: function(node) { - var path = NODEFS.realPath(node) - try { - path = fs.readlinkSync(path) - path = NODEJS_PATH.relative(NODEJS_PATH.resolve(node.mount.opts.root), path) - return path - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - }, - stream_ops: { - open: function(stream) { - var path = NODEFS.realPath(stream.node) - try { - if (FS.isFile(stream.node.mode)) { - stream.nfd = fs.openSync(path, NODEFS.flagsForNode(stream.flags)) - } - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - close: function(stream) { - try { - if (FS.isFile(stream.node.mode) && stream.nfd) { - fs.closeSync(stream.nfd) - } - } catch (e) { - if (!e.code) throw e - throw new FS.ErrnoError(-e.errno) - } - }, - read: function(stream, buffer, offset, length, position) { - if (length === 0) return 0 - try { - return fs.readSync( - stream.nfd, - NODEFS.bufferFrom(buffer.buffer), - offset, - length, - position - ) - } catch (e) { - throw new FS.ErrnoError(-e.errno) - } - }, - write: function(stream, buffer, offset, length, position) { - try { - return fs.writeSync( - stream.nfd, - NODEFS.bufferFrom(buffer.buffer), - offset, - length, - position - ) - } catch (e) { - throw new FS.ErrnoError(-e.errno) - } - }, - llseek: function(stream, offset, whence) { - var position = offset - if (whence === 1) { - position += stream.position - } else if (whence === 2) { - if (FS.isFile(stream.node.mode)) { - try { - var stat = fs.fstatSync(stream.nfd) - position += stat.size - } catch (e) { - throw new FS.ErrnoError(-e.errno) - } - } - } - if (position < 0) { - throw new FS.ErrnoError(22) - } - return position - }, - }, - } - var WORKERFS = { - DIR_MODE: 16895, - FILE_MODE: 33279, - reader: null, - mount: function(mount) { - assert(ENVIRONMENT_IS_WORKER) - if (!WORKERFS.reader) WORKERFS.reader = new FileReaderSync() - var root = WORKERFS.createNode(null, '/', WORKERFS.DIR_MODE, 0) - var createdParents = {} - function ensureParent(path) { - var parts = path.split('/') - var parent = root - for (var i = 0; i < parts.length - 1; i++) { - var curr = parts.slice(0, i + 1).join('/') - if (!createdParents[curr]) { - createdParents[curr] = WORKERFS.createNode( - parent, - parts[i], - WORKERFS.DIR_MODE, - 0 - ) - } - parent = createdParents[curr] - } - return parent - } - function base(path) { - var parts = path.split('/') - return parts[parts.length - 1] - } - Array.prototype.forEach.call(mount.opts['files'] || [], function(file) { - WORKERFS.createNode( - ensureParent(file.name), - base(file.name), - WORKERFS.FILE_MODE, - 0, - file, - file.lastModifiedDate - ) - }) - ;(mount.opts['blobs'] || []).forEach(function(obj) { - WORKERFS.createNode( - ensureParent(obj['name']), - base(obj['name']), - WORKERFS.FILE_MODE, - 0, - obj['data'] - ) - }) - ;(mount.opts['packages'] || []).forEach(function(pack) { - pack['metadata'].files.forEach(function(file) { - var name = file.filename.substr(1) - WORKERFS.createNode( - ensureParent(name), - base(name), - WORKERFS.FILE_MODE, - 0, - pack['blob'].slice(file.start, file.end) - ) - }) - }) - return root - }, - createNode: function(parent, name, mode, dev, contents, mtime) { - var node = FS.createNode(parent, name, mode) - node.mode = mode - node.node_ops = WORKERFS.node_ops - node.stream_ops = WORKERFS.stream_ops - node.timestamp = (mtime || new Date()).getTime() - assert(WORKERFS.FILE_MODE !== WORKERFS.DIR_MODE) - if (mode === WORKERFS.FILE_MODE) { - node.size = contents.size - node.contents = contents - } else { - node.size = 4096 - node.contents = {} - } - if (parent) { - parent.contents[name] = node - } - return node - }, - node_ops: { - getattr: function(node) { - return { - dev: 1, - ino: undefined, - mode: node.mode, - nlink: 1, - uid: 0, - gid: 0, - rdev: undefined, - size: node.size, - atime: new Date(node.timestamp), - mtime: new Date(node.timestamp), - ctime: new Date(node.timestamp), - blksize: 4096, - blocks: Math.ceil(node.size / 4096), - } - }, - setattr: function(node, attr) { - if (attr.mode !== undefined) { - node.mode = attr.mode - } - if (attr.timestamp !== undefined) { - node.timestamp = attr.timestamp - } - }, - lookup: function(parent, name) { - throw new FS.ErrnoError(2) - }, - mknod: function(parent, name, mode, dev) { - throw new FS.ErrnoError(1) - }, - rename: function(oldNode, newDir, newName) { - throw new FS.ErrnoError(1) - }, - unlink: function(parent, name) { - throw new FS.ErrnoError(1) - }, - rmdir: function(parent, name) { - throw new FS.ErrnoError(1) - }, - readdir: function(node) { - var entries = ['.', '..'] - for (var key in node.contents) { - if (!node.contents.hasOwnProperty(key)) { - continue - } - entries.push(key) - } - return entries - }, - symlink: function(parent, newName, oldPath) { - throw new FS.ErrnoError(1) - }, - readlink: function(node) { - throw new FS.ErrnoError(1) - }, - }, - stream_ops: { - read: function(stream, buffer, offset, length, position) { - if (position >= stream.node.size) return 0 - var chunk = stream.node.contents.slice(position, position + length) - var ab = WORKERFS.reader.readAsArrayBuffer(chunk) - buffer.set(new Uint8Array(ab), offset) - return chunk.size - }, - write: function(stream, buffer, offset, length, position) { - throw new FS.ErrnoError(5) - }, - llseek: function(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.size - } - } - if (position < 0) { - throw new FS.ErrnoError(22) - } - return position - }, - }, - } - var FS = { - root: null, - mounts: [], - devices: {}, - streams: [], - nextInode: 1, - nameTable: null, - currentPath: '/', - initialized: false, - ignorePermissions: true, - trackingDelegate: {}, - tracking: { openFlags: { READ: 1, WRITE: 2 } }, - ErrnoError: null, - genericErrors: {}, - filesystems: null, - syncFSRequests: 0, - handleFSError: function(e) { - if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace() - return ___setErrNo(e.errno) - }, - lookupPath: function(path, opts) { - path = PATH_FS.resolve(FS.cwd(), path) - opts = opts || {} - if (!path) return { path: '', node: null } - var defaults = { follow_mount: true, recurse_count: 0 } - for (var key in defaults) { - if (opts[key] === undefined) { - opts[key] = defaults[key] - } - } - if (opts.recurse_count > 8) { - throw new FS.ErrnoError(40) - } - var parts = PATH.normalizeArray( - path.split('/').filter(function(p) { - return !!p - }), - false - ) - 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 - } - current = FS.lookupNode(current, parts[i]) - current_path = PATH.join2(current_path, parts[i]) - if (FS.isMountpoint(current)) { - if (!islast || (islast && opts.follow_mount)) { - current = current.mounted.root - } - } - if (!islast || opts.follow) { - var count = 0 - while (FS.isLink(current.mode)) { - var link = FS.readlink(current_path) - current_path = PATH_FS.resolve(PATH.dirname(current_path), link) - var lookup = FS.lookupPath(current_path, { - recurse_count: opts.recurse_count, - }) - current = lookup.node - if (count++ > 40) { - throw new FS.ErrnoError(40) - } - } - } - } - return { path: current_path, node: current } - }, - getPath: function(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: function(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: function(node) { - var hash = FS.hashName(node.parent.id, node.name) - node.name_next = FS.nameTable[hash] - FS.nameTable[hash] = node - }, - hashRemoveNode: function(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: function(parent, name) { - var err = FS.mayLookup(parent) - if (err) { - throw new FS.ErrnoError(err, parent) - } - 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: function(parent, name, mode, rdev) { - if (!FS.FSNode) { - FS.FSNode = function(parent, name, mode, rdev) { - if (!parent) { - parent = this - } - this.parent = parent - this.mount = parent.mount - this.mounted = null - this.id = FS.nextInode++ - this.name = name - this.mode = mode - this.node_ops = {} - this.stream_ops = {} - this.rdev = rdev - } - FS.FSNode.prototype = {} - var readMode = 292 | 73 - var writeMode = 146 - Object.defineProperties(FS.FSNode.prototype, { - read: { - get: function() { - return (this.mode & readMode) === readMode - }, - set: function(val) { - val ? (this.mode |= readMode) : (this.mode &= ~readMode) - }, - }, - write: { - get: function() { - return (this.mode & writeMode) === writeMode - }, - set: function(val) { - val ? (this.mode |= writeMode) : (this.mode &= ~writeMode) - }, - }, - isFolder: { - get: function() { - return FS.isDir(this.mode) - }, - }, - isDevice: { - get: function() { - return FS.isChrdev(this.mode) - }, - }, - }) - } - var node = new FS.FSNode(parent, name, mode, rdev) - FS.hashAddNode(node) - return node - }, - destroyNode: function(node) { - FS.hashRemoveNode(node) - }, - isRoot: function(node) { - return node === node.parent - }, - isMountpoint: function(node) { - return !!node.mounted - }, - isFile: function(mode) { - return (mode & 61440) === 32768 - }, - isDir: function(mode) { - return (mode & 61440) === 16384 - }, - isLink: function(mode) { - return (mode & 61440) === 40960 - }, - isChrdev: function(mode) { - return (mode & 61440) === 8192 - }, - isBlkdev: function(mode) { - return (mode & 61440) === 24576 - }, - isFIFO: function(mode) { - return (mode & 61440) === 4096 - }, - isSocket: function(mode) { - return (mode & 49152) === 49152 - }, - flagModes: { - r: 0, - rs: 1052672, - 'r+': 2, - w: 577, - wx: 705, - xw: 705, - 'w+': 578, - 'wx+': 706, - 'xw+': 706, - a: 1089, - ax: 1217, - xa: 1217, - 'a+': 1090, - 'ax+': 1218, - 'xa+': 1218, - }, - modeStringToFlags: function(str) { - var flags = FS.flagModes[str] - if (typeof flags === 'undefined') { - throw new Error('Unknown file open mode: ' + str) - } - return flags - }, - flagsToPermissionString: function(flag) { - var perms = ['r', 'w', 'rw'][flag & 3] - if (flag & 512) { - perms += 'w' - } - return perms - }, - nodePermissions: function(node, perms) { - if (FS.ignorePermissions) { - return 0 - } - if (perms.indexOf('r') !== -1 && !(node.mode & 292)) { - return 13 - } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) { - return 13 - } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) { - return 13 - } - return 0 - }, - mayLookup: function(dir) { - var err = FS.nodePermissions(dir, 'x') - if (err) return err - if (!dir.node_ops.lookup) return 13 - return 0 - }, - mayCreate: function(dir, name) { - try { - var node = FS.lookupNode(dir, name) - return 17 - } catch (e) {} - return FS.nodePermissions(dir, 'wx') - }, - mayDelete: function(dir, name, isdir) { - var node - try { - node = FS.lookupNode(dir, name) - } catch (e) { - return e.errno - } - var err = FS.nodePermissions(dir, 'wx') - if (err) { - return err - } - if (isdir) { - if (!FS.isDir(node.mode)) { - return 20 - } - if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) { - return 16 - } - } else { - if (FS.isDir(node.mode)) { - return 21 - } - } - return 0 - }, - mayOpen: function(node, flags) { - if (!node) { - return 2 - } - if (FS.isLink(node.mode)) { - return 40 - } else if (FS.isDir(node.mode)) { - if (FS.flagsToPermissionString(flags) !== 'r' || flags & 512) { - return 21 - } - } - return FS.nodePermissions(node, FS.flagsToPermissionString(flags)) - }, - MAX_OPEN_FDS: 4096, - nextfd: function(fd_start, fd_end) { - fd_start = fd_start || 0 - fd_end = fd_end || FS.MAX_OPEN_FDS - for (var fd = fd_start; fd <= fd_end; fd++) { - if (!FS.streams[fd]) { - return fd - } - } - throw new FS.ErrnoError(24) - }, - getStream: function(fd) { - return FS.streams[fd] - }, - createStream: function(stream, fd_start, fd_end) { - if (!FS.FSStream) { - FS.FSStream = function() {} - FS.FSStream.prototype = {} - Object.defineProperties(FS.FSStream.prototype, { - object: { - get: function() { - return this.node - }, - set: function(val) { - this.node = val - }, - }, - isRead: { - get: function() { - return (this.flags & 2097155) !== 1 - }, - }, - isWrite: { - get: function() { - return (this.flags & 2097155) !== 0 - }, - }, - isAppend: { - get: function() { - return this.flags & 1024 - }, - }, - }) - } - var newStream = new FS.FSStream() - for (var p in stream) { - newStream[p] = stream[p] - } - stream = newStream - var fd = FS.nextfd(fd_start, fd_end) - stream.fd = fd - FS.streams[fd] = stream - return stream - }, - closeStream: function(fd) { - FS.streams[fd] = null - }, - chrdev_stream_ops: { - open: function(stream) { - var device = FS.getDevice(stream.node.rdev) - stream.stream_ops = device.stream_ops - if (stream.stream_ops.open) { - stream.stream_ops.open(stream) - } - }, - llseek: function() { - throw new FS.ErrnoError(29) - }, - }, - major: function(dev) { - return dev >> 8 - }, - minor: function(dev) { - return dev & 255 - }, - makedev: function(ma, mi) { - return (ma << 8) | mi - }, - registerDevice: function(dev, ops) { - FS.devices[dev] = { stream_ops: ops } - }, - getDevice: function(dev) { - return FS.devices[dev] - }, - getMounts: function(mount) { - var mounts = [] - var check = [mount] - while (check.length) { - var m = check.pop() - mounts.push(m) - check.push.apply(check, m.mounts) - } - return mounts - }, - syncfs: function(populate, callback) { - if (typeof populate === 'function') { - callback = populate - populate = false - } - FS.syncFSRequests++ - if (FS.syncFSRequests > 1) { - console.log( - '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(err) { - FS.syncFSRequests-- - return callback(err) - } - function done(err) { - if (err) { - if (!done.errored) { - done.errored = true - return doCallback(err) - } - return - } - if (++completed >= mounts.length) { - doCallback(null) - } - } - mounts.forEach(function(mount) { - if (!mount.type.syncfs) { - return done(null) - } - mount.type.syncfs(mount, populate, done) - }) - }, - mount: function(type, opts, mountpoint) { - var root = mountpoint === '/' - var pseudo = !mountpoint - var node - if (root && FS.root) { - throw new FS.ErrnoError(16) - } 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(16) - } - if (!FS.isDir(node.mode)) { - throw new FS.ErrnoError(20) - } - } - var mount = { type: type, opts: opts, mountpoint: 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: function(mountpoint) { - var lookup = FS.lookupPath(mountpoint, { follow_mount: false }) - if (!FS.isMountpoint(lookup.node)) { - throw new FS.ErrnoError(22) - } - var node = lookup.node - var mount = node.mounted - var mounts = FS.getMounts(mount) - Object.keys(FS.nameTable).forEach(function(hash) { - var current = FS.nameTable[hash] - while (current) { - var next = current.name_next - if (mounts.indexOf(current.mount) !== -1) { - FS.destroyNode(current) - } - current = next - } - }) - node.mounted = null - var idx = node.mount.mounts.indexOf(mount) - node.mount.mounts.splice(idx, 1) - }, - lookup: function(parent, name) { - return parent.node_ops.lookup(parent, name) - }, - mknod: function(path, mode, dev) { - var lookup = FS.lookupPath(path, { parent: true }) - var parent = lookup.node - var name = PATH.basename(path) - if (!name || name === '.' || name === '..') { - throw new FS.ErrnoError(22) - } - var err = FS.mayCreate(parent, name) - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.mknod) { - throw new FS.ErrnoError(1) - } - return parent.node_ops.mknod(parent, name, mode, dev) - }, - create: function(path, mode) { - mode = mode !== undefined ? mode : 438 - mode &= 4095 - mode |= 32768 - return FS.mknod(path, mode, 0) - }, - mkdir: function(path, mode) { - mode = mode !== undefined ? mode : 511 - mode &= 511 | 512 - mode |= 16384 - return FS.mknod(path, mode, 0) - }, - mkdirTree: function(path, mode) { - var dirs = path.split('/') - var d = '' - for (var i = 0; i < dirs.length; ++i) { - if (!dirs[i]) continue - d += '/' + dirs[i] - try { - FS.mkdir(d, mode) - } catch (e) { - if (e.errno != 17) throw e - } - } - }, - mkdev: function(path, mode, dev) { - if (typeof dev === 'undefined') { - dev = mode - mode = 438 - } - mode |= 8192 - return FS.mknod(path, mode, dev) - }, - symlink: function(oldpath, newpath) { - if (!PATH_FS.resolve(oldpath)) { - throw new FS.ErrnoError(2) - } - var lookup = FS.lookupPath(newpath, { parent: true }) - var parent = lookup.node - if (!parent) { - throw new FS.ErrnoError(2) - } - var newname = PATH.basename(newpath) - var err = FS.mayCreate(parent, newname) - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.symlink) { - throw new FS.ErrnoError(1) - } - return parent.node_ops.symlink(parent, newname, oldpath) - }, - rename: function(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 - try { - lookup = FS.lookupPath(old_path, { parent: true }) - old_dir = lookup.node - lookup = FS.lookupPath(new_path, { parent: true }) - new_dir = lookup.node - } catch (e) { - throw new FS.ErrnoError(16) - } - if (!old_dir || !new_dir) throw new FS.ErrnoError(2) - if (old_dir.mount !== new_dir.mount) { - throw new FS.ErrnoError(18) - } - 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(22) - } - relative = PATH_FS.relative(new_path, old_dirname) - if (relative.charAt(0) !== '.') { - throw new FS.ErrnoError(39) - } - 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 err = FS.mayDelete(old_dir, old_name, isdir) - if (err) { - throw new FS.ErrnoError(err) - } - err = new_node - ? FS.mayDelete(new_dir, new_name, isdir) - : FS.mayCreate(new_dir, new_name) - if (err) { - throw new FS.ErrnoError(err) - } - if (!old_dir.node_ops.rename) { - throw new FS.ErrnoError(1) - } - if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) { - throw new FS.ErrnoError(16) - } - if (new_dir !== old_dir) { - err = FS.nodePermissions(old_dir, 'w') - if (err) { - throw new FS.ErrnoError(err) - } - } - try { - if (FS.trackingDelegate['willMovePath']) { - FS.trackingDelegate['willMovePath'](old_path, new_path) - } - } catch (e) { - console.log( - "FS.trackingDelegate['willMovePath']('" + - old_path + - "', '" + - new_path + - "') threw an exception: " + - e.message - ) - } - FS.hashRemoveNode(old_node) - try { - old_dir.node_ops.rename(old_node, new_dir, new_name) - } catch (e) { - throw e - } finally { - FS.hashAddNode(old_node) - } - try { - if (FS.trackingDelegate['onMovePath']) - FS.trackingDelegate['onMovePath'](old_path, new_path) - } catch (e) { - console.log( - "FS.trackingDelegate['onMovePath']('" + - old_path + - "', '" + - new_path + - "') threw an exception: " + - e.message - ) - } - }, - rmdir: function(path) { - var lookup = FS.lookupPath(path, { parent: true }) - var parent = lookup.node - var name = PATH.basename(path) - var node = FS.lookupNode(parent, name) - var err = FS.mayDelete(parent, name, true) - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.rmdir) { - throw new FS.ErrnoError(1) - } - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(16) - } - try { - if (FS.trackingDelegate['willDeletePath']) { - FS.trackingDelegate['willDeletePath'](path) - } - } catch (e) { - console.log( - "FS.trackingDelegate['willDeletePath']('" + - path + - "') threw an exception: " + - e.message - ) - } - parent.node_ops.rmdir(parent, name) - FS.destroyNode(node) - try { - if (FS.trackingDelegate['onDeletePath']) - FS.trackingDelegate['onDeletePath'](path) - } catch (e) { - console.log( - "FS.trackingDelegate['onDeletePath']('" + - path + - "') threw an exception: " + - e.message - ) - } - }, - readdir: function(path) { - var lookup = FS.lookupPath(path, { follow: true }) - var node = lookup.node - if (!node.node_ops.readdir) { - throw new FS.ErrnoError(20) - } - return node.node_ops.readdir(node) - }, - unlink: function(path) { - var lookup = FS.lookupPath(path, { parent: true }) - var parent = lookup.node - var name = PATH.basename(path) - var node = FS.lookupNode(parent, name) - var err = FS.mayDelete(parent, name, false) - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.unlink) { - throw new FS.ErrnoError(1) - } - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(16) - } - try { - if (FS.trackingDelegate['willDeletePath']) { - FS.trackingDelegate['willDeletePath'](path) - } - } catch (e) { - console.log( - "FS.trackingDelegate['willDeletePath']('" + - path + - "') threw an exception: " + - e.message - ) - } - parent.node_ops.unlink(parent, name) - FS.destroyNode(node) - try { - if (FS.trackingDelegate['onDeletePath']) - FS.trackingDelegate['onDeletePath'](path) - } catch (e) { - console.log( - "FS.trackingDelegate['onDeletePath']('" + - path + - "') threw an exception: " + - e.message - ) - } - }, - readlink: function(path) { - var lookup = FS.lookupPath(path) - var link = lookup.node - if (!link) { - throw new FS.ErrnoError(2) - } - if (!link.node_ops.readlink) { - throw new FS.ErrnoError(22) - } - return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link)) - }, - stat: function(path, dontFollow) { - var lookup = FS.lookupPath(path, { follow: !dontFollow }) - var node = lookup.node - if (!node) { - throw new FS.ErrnoError(2) - } - if (!node.node_ops.getattr) { - throw new FS.ErrnoError(1) - } - return node.node_ops.getattr(node) - }, - lstat: function(path) { - return FS.stat(path, true) - }, - chmod: function(path, mode, dontFollow) { - var node - if (typeof path === 'string') { - var lookup = FS.lookupPath(path, { follow: !dontFollow }) - node = lookup.node - } else { - node = path - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(1) - } - node.node_ops.setattr(node, { - mode: (mode & 4095) | (node.mode & ~4095), - timestamp: Date.now(), - }) - }, - lchmod: function(path, mode) { - FS.chmod(path, mode, true) - }, - fchmod: function(fd, mode) { - var stream = FS.getStream(fd) - if (!stream) { - throw new FS.ErrnoError(9) - } - FS.chmod(stream.node, mode) - }, - chown: function(path, uid, gid, dontFollow) { - var node - if (typeof path === 'string') { - var lookup = FS.lookupPath(path, { follow: !dontFollow }) - node = lookup.node - } else { - node = path - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(1) - } - node.node_ops.setattr(node, { timestamp: Date.now() }) - }, - lchown: function(path, uid, gid) { - FS.chown(path, uid, gid, true) - }, - fchown: function(fd, uid, gid) { - var stream = FS.getStream(fd) - if (!stream) { - throw new FS.ErrnoError(9) - } - FS.chown(stream.node, uid, gid) - }, - truncate: function(path, len) { - if (len < 0) { - throw new FS.ErrnoError(22) - } - var node - if (typeof path === 'string') { - var lookup = FS.lookupPath(path, { follow: true }) - node = lookup.node - } else { - node = path - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(1) - } - if (FS.isDir(node.mode)) { - throw new FS.ErrnoError(21) - } - if (!FS.isFile(node.mode)) { - throw new FS.ErrnoError(22) - } - var err = FS.nodePermissions(node, 'w') - if (err) { - throw new FS.ErrnoError(err) - } - node.node_ops.setattr(node, { size: len, timestamp: Date.now() }) - }, - ftruncate: function(fd, len) { - var stream = FS.getStream(fd) - if (!stream) { - throw new FS.ErrnoError(9) - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(22) - } - FS.truncate(stream.node, len) - }, - utime: function(path, atime, mtime) { - var lookup = FS.lookupPath(path, { follow: true }) - var node = lookup.node - node.node_ops.setattr(node, { timestamp: Math.max(atime, mtime) }) - }, - open: function(path, flags, mode, fd_start, fd_end) { - if (path === '') { - throw new FS.ErrnoError(2) - } - flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags - mode = typeof mode === 'undefined' ? 438 : mode - if (flags & 64) { - mode = (mode & 4095) | 32768 - } else { - mode = 0 - } - var node - if (typeof path === 'object') { - node = path - } else { - path = PATH.normalize(path) - try { - var lookup = FS.lookupPath(path, { follow: !(flags & 131072) }) - node = lookup.node - } catch (e) {} - } - var created = false - if (flags & 64) { - if (node) { - if (flags & 128) { - throw new FS.ErrnoError(17) - } - } else { - node = FS.mknod(path, mode, 0) - created = true - } - } - if (!node) { - throw new FS.ErrnoError(2) - } - if (FS.isChrdev(node.mode)) { - flags &= ~512 - } - if (flags & 65536 && !FS.isDir(node.mode)) { - throw new FS.ErrnoError(20) - } - if (!created) { - var err = FS.mayOpen(node, flags) - if (err) { - throw new FS.ErrnoError(err) - } - } - if (flags & 512) { - FS.truncate(node, 0) - } - flags &= ~(128 | 512) - var stream = FS.createStream( - { - node: node, - path: FS.getPath(node), - flags: flags, - seekable: true, - position: 0, - stream_ops: node.stream_ops, - ungotten: [], - error: false, - }, - fd_start, - fd_end - ) - if (stream.stream_ops.open) { - stream.stream_ops.open(stream) - } - if (Module['logReadFiles'] && !(flags & 1)) { - if (!FS.readFiles) FS.readFiles = {} - if (!(path in FS.readFiles)) { - FS.readFiles[path] = 1 - console.log('FS.trackingDelegate error on read file: ' + path) - } - } - try { - if (FS.trackingDelegate['onOpenFile']) { - var trackingFlags = 0 - if ((flags & 2097155) !== 1) { - trackingFlags |= FS.tracking.openFlags.READ - } - if ((flags & 2097155) !== 0) { - trackingFlags |= FS.tracking.openFlags.WRITE - } - FS.trackingDelegate['onOpenFile'](path, trackingFlags) - } - } catch (e) { - console.log( - "FS.trackingDelegate['onOpenFile']('" + - path + - "', flags) threw an exception: " + - e.message - ) - } - return stream - }, - close: function(stream) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(9) - } - 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: function(stream) { - return stream.fd === null - }, - llseek: function(stream, offset, whence) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(9) - } - if (!stream.seekable || !stream.stream_ops.llseek) { - throw new FS.ErrnoError(29) - } - if (whence != 0 && whence != 1 && whence != 2) { - throw new FS.ErrnoError(22) - } - stream.position = stream.stream_ops.llseek(stream, offset, whence) - stream.ungotten = [] - return stream.position - }, - read: function(stream, buffer, offset, length, position) { - if (length < 0 || position < 0) { - throw new FS.ErrnoError(22) - } - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(9) - } - if ((stream.flags & 2097155) === 1) { - throw new FS.ErrnoError(9) - } - if (FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(21) - } - if (!stream.stream_ops.read) { - throw new FS.ErrnoError(22) - } - var seeking = typeof position !== 'undefined' - if (!seeking) { - position = stream.position - } else if (!stream.seekable) { - throw new FS.ErrnoError(29) - } - var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position) - if (!seeking) stream.position += bytesRead - return bytesRead - }, - write: function(stream, buffer, offset, length, position, canOwn) { - if (length < 0 || position < 0) { - throw new FS.ErrnoError(22) - } - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(9) - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(9) - } - if (FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(21) - } - if (!stream.stream_ops.write) { - throw new FS.ErrnoError(22) - } - if (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(29) - } - var bytesWritten = stream.stream_ops.write( - stream, - buffer, - offset, - length, - position, - canOwn - ) - if (!seeking) stream.position += bytesWritten - try { - if (stream.path && FS.trackingDelegate['onWriteToFile']) - FS.trackingDelegate['onWriteToFile'](stream.path) - } catch (e) { - console.log( - "FS.trackingDelegate['onWriteToFile']('" + - stream.path + - "') threw an exception: " + - e.message - ) - } - return bytesWritten - }, - allocate: function(stream, offset, length) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(9) - } - if (offset < 0 || length <= 0) { - throw new FS.ErrnoError(22) - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(9) - } - if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(19) - } - if (!stream.stream_ops.allocate) { - throw new FS.ErrnoError(95) - } - stream.stream_ops.allocate(stream, offset, length) - }, - mmap: function(stream, buffer, offset, length, position, prot, flags) { - if ((stream.flags & 2097155) === 1) { - throw new FS.ErrnoError(13) - } - if (!stream.stream_ops.mmap) { - throw new FS.ErrnoError(19) - } - return stream.stream_ops.mmap( - stream, - buffer, - offset, - length, - position, - prot, - flags - ) - }, - msync: function(stream, buffer, offset, length, mmapFlags) { - if (!stream || !stream.stream_ops.msync) { - return 0 - } - return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags) - }, - munmap: function(stream) { - return 0 - }, - ioctl: function(stream, cmd, arg) { - if (!stream.stream_ops.ioctl) { - throw new FS.ErrnoError(25) - } - return stream.stream_ops.ioctl(stream, cmd, arg) - }, - readFile: function(path, opts) { - opts = opts || {} - opts.flags = opts.flags || 'r' - opts.encoding = opts.encoding || 'binary' - if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') { - throw new Error('Invalid encoding type "' + opts.encoding + '"') - } - var ret - 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') { - ret = UTF8ArrayToString(buf, 0) - } else if (opts.encoding === 'binary') { - ret = buf - } - FS.close(stream) - return ret - }, - writeFile: function(path, data, opts) { - opts = opts || {} - opts.flags = opts.flags || 'w' - var stream = FS.open(path, opts.flags, opts.mode) - if (typeof data === 'string') { - var buf = new Uint8Array(lengthBytesUTF8(data) + 1) - var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length) - FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn) - } else if (ArrayBuffer.isView(data)) { - FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn) - } else { - throw new Error('Unsupported data type') - } - FS.close(stream) - }, - cwd: function() { - return FS.currentPath - }, - chdir: function(path) { - var lookup = FS.lookupPath(path, { follow: true }) - if (lookup.node === null) { - throw new FS.ErrnoError(2) - } - if (!FS.isDir(lookup.node.mode)) { - throw new FS.ErrnoError(20) - } - var err = FS.nodePermissions(lookup.node, 'x') - if (err) { - throw new FS.ErrnoError(err) - } - FS.currentPath = lookup.path - }, - createDefaultDirectories: function() { - FS.mkdir('/tmp') - FS.mkdir('/home') - FS.mkdir('/home/web_user') - }, - createDefaultDevices: function() { - FS.mkdir('/dev') - FS.registerDevice(FS.makedev(1, 3), { - read: function() { - return 0 - }, - write: function(stream, buffer, offset, length, pos) { - return length - }, - }) - 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 random_device - if ( - typeof crypto === 'object' && - typeof crypto['getRandomValues'] === 'function' - ) { - var randomBuffer = new Uint8Array(1) - random_device = function() { - crypto.getRandomValues(randomBuffer) - return randomBuffer[0] - } - } else if (ENVIRONMENT_IS_NODE) { - try { - var crypto_module = require('crypto') - random_device = function() { - return crypto_module['randomBytes'](1)[0] - } - } catch (e) {} - } else { - } - if (!random_device) { - random_device = function() { - abort('random_device') - } - } - FS.createDevice('/dev', 'random', random_device) - FS.createDevice('/dev', 'urandom', random_device) - FS.mkdir('/dev/shm') - FS.mkdir('/dev/shm/tmp') - }, - createSpecialDirectories: function() { - FS.mkdir('/proc') - FS.mkdir('/proc/self') - FS.mkdir('/proc/self/fd') - FS.mount( - { - mount: function() { - var node = FS.createNode('/proc/self', 'fd', 16384 | 511, 73) - node.node_ops = { - lookup: function(parent, name) { - var fd = +name - var stream = FS.getStream(fd) - if (!stream) throw new FS.ErrnoError(9) - var ret = { - parent: null, - mount: { mountpoint: 'fake' }, - node_ops: { - readlink: function() { - return stream.path - }, - }, - } - ret.parent = ret - return ret - }, - } - return node - }, - }, - {}, - '/proc/self/fd' - ) - }, - createStandardStreams: function() { - if (Module['stdin']) { - FS.createDevice('/dev', 'stdin', Module['stdin']) - } else { - FS.symlink('/dev/tty', '/dev/stdin') - } - if (Module['stdout']) { - FS.createDevice('/dev', 'stdout', null, Module['stdout']) - } else { - FS.symlink('/dev/tty', '/dev/stdout') - } - if (Module['stderr']) { - FS.createDevice('/dev', 'stderr', null, Module['stderr']) - } else { - FS.symlink('/dev/tty1', '/dev/stderr') - } - var stdin = FS.open('/dev/stdin', 'r') - var stdout = FS.open('/dev/stdout', 'w') - var stderr = FS.open('/dev/stderr', 'w') - }, - ensureErrnoError: function() { - if (FS.ErrnoError) return - FS.ErrnoError = function ErrnoError(errno, node) { - this.node = node - this.setErrno = function(errno) { - this.errno = errno - } - this.setErrno(errno) - this.message = 'FS error' - if (this.stack) - Object.defineProperty(this, 'stack', { - value: new Error().stack, - writable: true, - }) - } - FS.ErrnoError.prototype = new Error() - FS.ErrnoError.prototype.constructor = FS.ErrnoError - ;[2].forEach(function(code) { - FS.genericErrors[code] = new FS.ErrnoError(code) - FS.genericErrors[code].stack = '' - }) - }, - staticInit: function() { - FS.ensureErrnoError() - FS.nameTable = new Array(4096) - FS.mount(MEMFS, {}, '/') - FS.createDefaultDirectories() - FS.createDefaultDevices() - FS.createSpecialDirectories() - FS.filesystems = { - MEMFS: MEMFS, - IDBFS: IDBFS, - NODEFS: NODEFS, - WORKERFS: WORKERFS, - } - }, - init: function(input, output, error) { - FS.init.initialized = true - FS.ensureErrnoError() - Module['stdin'] = input || Module['stdin'] - Module['stdout'] = output || Module['stdout'] - Module['stderr'] = error || Module['stderr'] - FS.createStandardStreams() - }, - quit: function() { - FS.init.initialized = false - var fflush = Module['_fflush'] - if (fflush) fflush(0) - for (var i = 0; i < FS.streams.length; i++) { - var stream = FS.streams[i] - if (!stream) { - continue - } - FS.close(stream) - } - }, - getMode: function(canRead, canWrite) { - var mode = 0 - if (canRead) mode |= 292 | 73 - if (canWrite) mode |= 146 - return mode - }, - joinPath: function(parts, forceRelative) { - var path = PATH.join.apply(null, parts) - if (forceRelative && path[0] == '/') path = path.substr(1) - return path - }, - absolutePath: function(relative, base) { - return PATH_FS.resolve(base, relative) - }, - standardizePath: function(path) { - return PATH.normalize(path) - }, - findObject: function(path, dontResolveLastLink) { - var ret = FS.analyzePath(path, dontResolveLastLink) - if (ret.exists) { - return ret.object - } else { - ___setErrNo(ret.error) - return null - } - }, - analyzePath: function(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 - }, - createFolder: function(parent, name, canRead, canWrite) { - var path = PATH.join2( - typeof parent === 'string' ? parent : FS.getPath(parent), - name - ) - var mode = FS.getMode(canRead, canWrite) - return FS.mkdir(path, mode) - }, - createPath: function(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) {} - parent = current - } - return current - }, - createFile: function(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: function(parent, name, data, canRead, canWrite, canOwn) { - var path = name - ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(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, 'w') - FS.write(stream, data, 0, data.length, 0, canOwn) - FS.close(stream) - FS.chmod(node, mode) - } - return node - }, - createDevice: function(parent, name, input, output) { - var path = PATH.join2( - typeof parent === 'string' ? parent : FS.getPath(parent), - name - ) - var mode = FS.getMode(!!input, !!output) - if (!FS.createDevice.major) FS.createDevice.major = 64 - var dev = FS.makedev(FS.createDevice.major++, 0) - FS.registerDevice(dev, { - open: function(stream) { - stream.seekable = false - }, - close: function(stream) { - if (output && output.buffer && output.buffer.length) { - output(10) - } - }, - read: function(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(5) - } - if (result === undefined && bytesRead === 0) { - throw new FS.ErrnoError(11) - } - if (result === null || result === undefined) break - bytesRead++ - buffer[offset + i] = result - } - if (bytesRead) { - stream.node.timestamp = Date.now() - } - return bytesRead - }, - write: function(stream, buffer, offset, length, pos) { - for (var i = 0; i < length; i++) { - try { - output(buffer[offset + i]) - } catch (e) { - throw new FS.ErrnoError(5) - } - } - if (length) { - stream.node.timestamp = Date.now() - } - return i - }, - }) - return FS.mkdev(path, mode, dev) - }, - createLink: function(parent, name, target, canRead, canWrite) { - var path = PATH.join2( - typeof parent === 'string' ? parent : FS.getPath(parent), - name - ) - return FS.symlink(target, path) - }, - forceLoadFile: function(obj) { - if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true - var success = true - if (typeof XMLHttpRequest !== 'undefined') { - throw new Error( - '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 if (Module['read']) { - try { - obj.contents = intArrayFromString(Module['read'](obj.url), true) - obj.usedBytes = obj.contents.length - } catch (e) { - success = false - } - } else { - throw new Error('Cannot load without read() or XMLHttpRequest.') - } - if (!success) ___setErrNo(5) - return success - }, - createLazyFile: function(parent, name, url, canRead, canWrite) { - function LazyUint8Array() { - this.lengthKnown = false - this.chunks = [] - } - LazyUint8Array.prototype.get = function LazyUint8Array_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] - } - LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter( - getter - ) { - this.getter = getter - } - LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() { - var xhr = new XMLHttpRequest() - xhr.open('HEAD', url, false) - xhr.send(null) - if (!((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) - throw new Error("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 = function(from, to) { - if (from > to) - throw new Error( - 'invalid range (' + from + ', ' + to + ') or no bytes requested!' - ) - if (to > datalength - 1) - throw new Error( - 'only ' + datalength + ' bytes available! programmer error!' - ) - var xhr = new XMLHttpRequest() - xhr.open('GET', url, false) - if (datalength !== chunkSize) - xhr.setRequestHeader('Range', 'bytes=' + from + '-' + to) - if (typeof Uint8Array != 'undefined') 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)) - throw new Error("Couldn't load " + url + '. Status: ' + xhr.status) - if (xhr.response !== undefined) { - return new Uint8Array(xhr.response || []) - } else { - return intArrayFromString(xhr.responseText || '', true) - } - } - var lazyArray = this - lazyArray.setDataGetter(function(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') - throw new Error('doXHR failed!') - return lazyArray.chunks[chunkNum] - }) - if (usesGzip || !datalength) { - chunkSize = datalength = 1 - datalength = this.getter(0).length - chunkSize = datalength - console.log( - 'LazyFiles on gzip forces download of the whole file when length is accessed' - ) - } - this._length = datalength - this._chunkSize = chunkSize - this.lengthKnown = true - } - if (typeof XMLHttpRequest !== 'undefined') { - if (!ENVIRONMENT_IS_WORKER) - throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc' - var lazyArray = new LazyUint8Array() - Object.defineProperties(lazyArray, { - length: { - get: function() { - if (!this.lengthKnown) { - this.cacheLength() - } - return this._length - }, - }, - chunkSize: { - get: function() { - if (!this.lengthKnown) { - this.cacheLength() - } - return this._chunkSize - }, - }, - }) - var properties = { isDevice: false, contents: lazyArray } - } else { - var properties = { isDevice: false, url: 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(function(key) { - var fn = node.stream_ops[key] - stream_ops[key] = function forceLoadLazyFile() { - if (!FS.forceLoadFile(node)) { - throw new FS.ErrnoError(5) - } - return fn.apply(null, arguments) - } - }) - stream_ops.read = function stream_ops_read( - stream, - buffer, - offset, - length, - position - ) { - if (!FS.forceLoadFile(node)) { - throw new FS.ErrnoError(5) - } - 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 - } - node.stream_ops = stream_ops - return node - }, - createPreloadedFile: function( - parent, - name, - url, - canRead, - canWrite, - onload, - onerror, - dontCreateFile, - canOwn, - preFinish - ) { - Browser.init() - var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent - var dep = getUniqueRunDependency('cp ' + fullname) - function processData(byteArray) { - function finish(byteArray) { - if (preFinish) preFinish() - if (!dontCreateFile) { - FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn) - } - if (onload) onload() - removeRunDependency(dep) - } - var handled = false - Module['preloadPlugins'].forEach(function(plugin) { - if (handled) return - if (plugin['canHandle'](fullname)) { - plugin['handle'](byteArray, fullname, finish, function() { - if (onerror) onerror() - removeRunDependency(dep) - }) - handled = true - } - }) - if (!handled) finish(byteArray) - } - addRunDependency(dep) - if (typeof url == 'string') { - Browser.asyncLoad( - url, - function(byteArray) { - processData(byteArray) - }, - onerror - ) - } else { - processData(url) - } - }, - indexedDB: function() { - return ( - window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB - ) - }, - DB_NAME: function() { - return 'EM_FS_' + window.location.pathname - }, - DB_VERSION: 20, - DB_STORE_NAME: 'FILE_DATA', - saveFilesToDB: function(paths, onload, onerror) { - onload = onload || function() {} - onerror = onerror || function() {} - var indexedDB = FS.indexedDB() - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION) - } catch (e) { - return onerror(e) - } - openRequest.onupgradeneeded = function openRequest_onupgradeneeded() { - console.log('creating db') - var db = openRequest.result - db.createObjectStore(FS.DB_STORE_NAME) - } - openRequest.onsuccess = function openRequest_onsuccess() { - var db = openRequest.result - var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite') - var files = transaction.objectStore(FS.DB_STORE_NAME) - var ok = 0, - fail = 0, - total = paths.length - function finish() { - if (fail == 0) onload() - else onerror() - } - paths.forEach(function(path) { - var putRequest = files.put(FS.analyzePath(path).object.contents, path) - putRequest.onsuccess = function putRequest_onsuccess() { - ok++ - if (ok + fail == total) finish() - } - putRequest.onerror = function putRequest_onerror() { - fail++ - if (ok + fail == total) finish() - } - }) - transaction.onerror = onerror - } - openRequest.onerror = onerror - }, - loadFilesFromDB: function(paths, onload, onerror) { - onload = onload || function() {} - onerror = onerror || function() {} - var indexedDB = FS.indexedDB() - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION) - } catch (e) { - return onerror(e) - } - openRequest.onupgradeneeded = onerror - openRequest.onsuccess = function openRequest_onsuccess() { - var db = openRequest.result - try { - var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly') - } catch (e) { - onerror(e) - return - } - var files = transaction.objectStore(FS.DB_STORE_NAME) - var ok = 0, - fail = 0, - total = paths.length - function finish() { - if (fail == 0) onload() - else onerror() - } - paths.forEach(function(path) { - var getRequest = files.get(path) - getRequest.onsuccess = function getRequest_onsuccess() { - if (FS.analyzePath(path).exists) { - FS.unlink(path) - } - FS.createDataFile( - PATH.dirname(path), - PATH.basename(path), - getRequest.result, - true, - true, - true - ) - ok++ - if (ok + fail == total) finish() - } - getRequest.onerror = function getRequest_onerror() { - fail++ - if (ok + fail == total) finish() - } - }) - transaction.onerror = onerror - } - openRequest.onerror = onerror - }, - } - var SYSCALLS = { - DEFAULT_POLLMASK: 5, - mappings: {}, - umask: 511, - calculateAt: function(dirfd, path) { - if (path[0] !== '/') { - var dir - if (dirfd === -100) { - dir = FS.cwd() - } else { - var dirstream = FS.getStream(dirfd) - if (!dirstream) throw new FS.ErrnoError(9) - dir = dirstream.path - } - path = PATH.join2(dir, path) - } - return path - }, - doStat: function(func, path, buf) { - try { - var stat = func(path) - } catch (e) { - if ( - e && - e.node && - PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node)) - ) { - return -20 - } - throw e - } - HEAP32[buf >> 2] = stat.dev - HEAP32[(buf + 4) >> 2] = 0 - HEAP32[(buf + 8) >> 2] = stat.ino - HEAP32[(buf + 12) >> 2] = stat.mode - HEAP32[(buf + 16) >> 2] = stat.nlink - HEAP32[(buf + 20) >> 2] = stat.uid - HEAP32[(buf + 24) >> 2] = stat.gid - HEAP32[(buf + 28) >> 2] = stat.rdev - HEAP32[(buf + 32) >> 2] = 0 - ;(tempI64 = [ - stat.size >>> 0, - ((tempDouble = stat.size), - +Math_abs(tempDouble) >= 1 - ? tempDouble > 0 - ? (Math_min(+Math_floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 - : ~~+Math_ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (HEAP32[(buf + 40) >> 2] = tempI64[0]), - (HEAP32[(buf + 44) >> 2] = tempI64[1]) - HEAP32[(buf + 48) >> 2] = 4096 - HEAP32[(buf + 52) >> 2] = stat.blocks - HEAP32[(buf + 56) >> 2] = (stat.atime.getTime() / 1e3) | 0 - HEAP32[(buf + 60) >> 2] = 0 - HEAP32[(buf + 64) >> 2] = (stat.mtime.getTime() / 1e3) | 0 - HEAP32[(buf + 68) >> 2] = 0 - HEAP32[(buf + 72) >> 2] = (stat.ctime.getTime() / 1e3) | 0 - HEAP32[(buf + 76) >> 2] = 0 - ;(tempI64 = [ - stat.ino >>> 0, - ((tempDouble = stat.ino), - +Math_abs(tempDouble) >= 1 - ? tempDouble > 0 - ? (Math_min(+Math_floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 - : ~~+Math_ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (HEAP32[(buf + 80) >> 2] = tempI64[0]), - (HEAP32[(buf + 84) >> 2] = tempI64[1]) - return 0 - }, - doMsync: function(addr, stream, len, flags) { - var buffer = new Uint8Array(HEAPU8.subarray(addr, addr + len)) - FS.msync(stream, buffer, 0, len, flags) - }, - doMkdir: function(path, mode) { - path = PATH.normalize(path) - if (path[path.length - 1] === '/') path = path.substr(0, path.length - 1) - FS.mkdir(path, mode, 0) - return 0 - }, - doMknod: function(path, mode, dev) { - switch (mode & 61440) { - case 32768: - case 8192: - case 24576: - case 4096: - case 49152: - break - default: - return -22 - } - FS.mknod(path, mode, dev) - return 0 - }, - doReadlink: function(path, buf, bufsize) { - if (bufsize <= 0) return -22 - var ret = FS.readlink(path) - var len = Math.min(bufsize, lengthBytesUTF8(ret)) - var endChar = HEAP8[buf + len] - stringToUTF8(ret, buf, bufsize + 1) - HEAP8[buf + len] = endChar - return len - }, - doAccess: function(path, amode) { - if (amode & ~7) { - return -22 - } - var node - var lookup = FS.lookupPath(path, { follow: true }) - node = lookup.node - var perms = '' - if (amode & 4) perms += 'r' - if (amode & 2) perms += 'w' - if (amode & 1) perms += 'x' - if (perms && FS.nodePermissions(node, perms)) { - return -13 - } - return 0 - }, - doDup: function(path, flags, suggestFD) { - var suggest = FS.getStream(suggestFD) - if (suggest) FS.close(suggest) - return FS.open(path, flags, 0, suggestFD, suggestFD).fd - }, - doReadv: function(stream, iov, iovcnt, offset) { - var ret = 0 - for (var i = 0; i < iovcnt; i++) { - var ptr = HEAP32[(iov + i * 8) >> 2] - var len = HEAP32[(iov + (i * 8 + 4)) >> 2] - var curr = FS.read(stream, HEAP8, ptr, len, offset) - if (curr < 0) return -1 - ret += curr - if (curr < len) break - } - return ret - }, - doWritev: function(stream, iov, iovcnt, offset) { - var ret = 0 - for (var i = 0; i < iovcnt; i++) { - var ptr = HEAP32[(iov + i * 8) >> 2] - var len = HEAP32[(iov + (i * 8 + 4)) >> 2] - var curr = FS.write(stream, HEAP8, ptr, len, offset) - if (curr < 0) return -1 - ret += curr - } - return ret - }, - varargs: 0, - get: function(varargs) { - SYSCALLS.varargs += 4 - var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2] - return ret - }, - getStr: function() { - var ret = UTF8ToString(SYSCALLS.get()) - return ret - }, - getStreamFromFD: function() { - var stream = FS.getStream(SYSCALLS.get()) - if (!stream) throw new FS.ErrnoError(9) - return stream - }, - get64: function() { - var low = SYSCALLS.get(), - high = SYSCALLS.get() - return low - }, - getZero: function() { - SYSCALLS.get() - }, - } - function ___syscall140(which, varargs) { - SYSCALLS.varargs = varargs - try { - var stream = SYSCALLS.getStreamFromFD(), - offset_high = SYSCALLS.get(), - offset_low = SYSCALLS.get(), - result = SYSCALLS.get(), - whence = SYSCALLS.get() - if ( - !(offset_high == -1 && offset_low < 0) && - !(offset_high == 0 && offset_low >= 0) - ) { - return -75 - } - var offset = offset_low - FS.llseek(stream, offset, whence) - ;(tempI64 = [ - stream.position >>> 0, - ((tempDouble = stream.position), - +Math_abs(tempDouble) >= 1 - ? tempDouble > 0 - ? (Math_min(+Math_floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 - : ~~+Math_ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (HEAP32[result >> 2] = tempI64[0]), - (HEAP32[(result + 4) >> 2] = tempI64[1]) - if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null - return 0 - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall146(which, varargs) { - SYSCALLS.varargs = varargs - try { - var stream = SYSCALLS.getStreamFromFD(), - iov = SYSCALLS.get(), - iovcnt = SYSCALLS.get() - return SYSCALLS.doWritev(stream, iov, iovcnt) - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall168(which, varargs) { - SYSCALLS.varargs = varargs - try { - var fds = SYSCALLS.get(), - nfds = SYSCALLS.get(), - timeout = SYSCALLS.get() - var nonzero = 0 - for (var i = 0; i < nfds; i++) { - var pollfd = fds + 8 * i - var fd = HEAP32[pollfd >> 2] - var events = HEAP16[(pollfd + 4) >> 1] - var mask = 32 - var stream = FS.getStream(fd) - if (stream) { - mask = SYSCALLS.DEFAULT_POLLMASK - if (stream.stream_ops.poll) { - mask = stream.stream_ops.poll(stream) - } - } - mask &= events | 8 | 16 - if (mask) nonzero++ - HEAP16[(pollfd + 6) >> 1] = mask - } - return nonzero - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall195(which, varargs) { - SYSCALLS.varargs = varargs - try { - var path = SYSCALLS.getStr(), - buf = SYSCALLS.get() - return SYSCALLS.doStat(FS.stat, path, buf) - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall196(which, varargs) { - SYSCALLS.varargs = varargs - try { - var path = SYSCALLS.getStr(), - buf = SYSCALLS.get() - return SYSCALLS.doStat(FS.lstat, path, buf) - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall197(which, varargs) { - SYSCALLS.varargs = varargs - try { - var stream = SYSCALLS.getStreamFromFD(), - buf = SYSCALLS.get() - return SYSCALLS.doStat(FS.stat, stream.path, buf) - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall221(which, varargs) { - SYSCALLS.varargs = varargs - try { - var stream = SYSCALLS.getStreamFromFD(), - cmd = SYSCALLS.get() - switch (cmd) { - case 0: { - var arg = SYSCALLS.get() - if (arg < 0) { - return -22 - } - var newStream - newStream = FS.open(stream.path, stream.flags, 0, arg) - return newStream.fd - } - case 1: - case 2: - return 0 - case 3: - return stream.flags - case 4: { - var arg = SYSCALLS.get() - stream.flags |= arg - return 0 - } - case 12: { - var arg = SYSCALLS.get() - var offset = 0 - HEAP16[(arg + offset) >> 1] = 2 - return 0 - } - case 13: - case 14: - return 0 - case 16: - case 8: - return -22 - case 9: - ___setErrNo(22) - return -1 - default: { - return -22 - } - } - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall3(which, varargs) { - SYSCALLS.varargs = varargs - try { - var stream = SYSCALLS.getStreamFromFD(), - buf = SYSCALLS.get(), - count = SYSCALLS.get() - return FS.read(stream, HEAP8, buf, count) - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall4(which, varargs) { - SYSCALLS.varargs = varargs - try { - var stream = SYSCALLS.getStreamFromFD(), - buf = SYSCALLS.get(), - count = SYSCALLS.get() - return FS.write(stream, HEAP8, buf, count) - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall41(which, varargs) { - SYSCALLS.varargs = varargs - try { - var old = SYSCALLS.getStreamFromFD() - return FS.open(old.path, old.flags, 0).fd - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - var ERRNO_CODES = { - EPERM: 1, - ENOENT: 2, - ESRCH: 3, - EINTR: 4, - EIO: 5, - ENXIO: 6, - E2BIG: 7, - ENOEXEC: 8, - EBADF: 9, - ECHILD: 10, - EAGAIN: 11, - EWOULDBLOCK: 11, - ENOMEM: 12, - EACCES: 13, - EFAULT: 14, - ENOTBLK: 15, - EBUSY: 16, - EEXIST: 17, - EXDEV: 18, - ENODEV: 19, - ENOTDIR: 20, - EISDIR: 21, - EINVAL: 22, - ENFILE: 23, - EMFILE: 24, - ENOTTY: 25, - ETXTBSY: 26, - EFBIG: 27, - ENOSPC: 28, - ESPIPE: 29, - EROFS: 30, - EMLINK: 31, - EPIPE: 32, - EDOM: 33, - ERANGE: 34, - ENOMSG: 42, - EIDRM: 43, - ECHRNG: 44, - EL2NSYNC: 45, - EL3HLT: 46, - EL3RST: 47, - ELNRNG: 48, - EUNATCH: 49, - ENOCSI: 50, - EL2HLT: 51, - EDEADLK: 35, - ENOLCK: 37, - EBADE: 52, - EBADR: 53, - EXFULL: 54, - ENOANO: 55, - EBADRQC: 56, - EBADSLT: 57, - EDEADLOCK: 35, - EBFONT: 59, - ENOSTR: 60, - ENODATA: 61, - ETIME: 62, - ENOSR: 63, - ENONET: 64, - ENOPKG: 65, - EREMOTE: 66, - ENOLINK: 67, - EADV: 68, - ESRMNT: 69, - ECOMM: 70, - EPROTO: 71, - EMULTIHOP: 72, - EDOTDOT: 73, - EBADMSG: 74, - ENOTUNIQ: 76, - EBADFD: 77, - EREMCHG: 78, - ELIBACC: 79, - ELIBBAD: 80, - ELIBSCN: 81, - ELIBMAX: 82, - ELIBEXEC: 83, - ENOSYS: 38, - ENOTEMPTY: 39, - ENAMETOOLONG: 36, - ELOOP: 40, - EOPNOTSUPP: 95, - EPFNOSUPPORT: 96, - ECONNRESET: 104, - ENOBUFS: 105, - EAFNOSUPPORT: 97, - EPROTOTYPE: 91, - ENOTSOCK: 88, - ENOPROTOOPT: 92, - ESHUTDOWN: 108, - ECONNREFUSED: 111, - EADDRINUSE: 98, - ECONNABORTED: 103, - ENETUNREACH: 101, - ENETDOWN: 100, - ETIMEDOUT: 110, - EHOSTDOWN: 112, - EHOSTUNREACH: 113, - EINPROGRESS: 115, - EALREADY: 114, - EDESTADDRREQ: 89, - EMSGSIZE: 90, - EPROTONOSUPPORT: 93, - ESOCKTNOSUPPORT: 94, - EADDRNOTAVAIL: 99, - ENETRESET: 102, - EISCONN: 106, - ENOTCONN: 107, - ETOOMANYREFS: 109, - EUSERS: 87, - EDQUOT: 122, - ESTALE: 116, - ENOTSUP: 95, - ENOMEDIUM: 123, - EILSEQ: 84, - EOVERFLOW: 75, - ECANCELED: 125, - ENOTRECOVERABLE: 131, - EOWNERDEAD: 130, - ESTRPIPE: 86, - } - var PIPEFS = { - BUCKET_BUFFER_SIZE: 8192, - mount: function(mount) { - return FS.createNode(null, '/', 16384 | 511, 0) - }, - createPipe: function() { - var pipe = { buckets: [] } - pipe.buckets.push({ - buffer: new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE), - offset: 0, - roffset: 0, - }) - var rName = PIPEFS.nextname() - var wName = PIPEFS.nextname() - var rNode = FS.createNode(PIPEFS.root, rName, 4096, 0) - var wNode = FS.createNode(PIPEFS.root, wName, 4096, 0) - rNode.pipe = pipe - wNode.pipe = pipe - var readableStream = FS.createStream({ - path: rName, - node: rNode, - flags: FS.modeStringToFlags('r'), - seekable: false, - stream_ops: PIPEFS.stream_ops, - }) - rNode.stream = readableStream - var writableStream = FS.createStream({ - path: wName, - node: wNode, - flags: FS.modeStringToFlags('w'), - seekable: false, - stream_ops: PIPEFS.stream_ops, - }) - wNode.stream = writableStream - return { readable_fd: readableStream.fd, writable_fd: writableStream.fd } - }, - stream_ops: { - poll: function(stream) { - var pipe = stream.node.pipe - if ((stream.flags & 2097155) === 1) { - return 256 | 4 - } else { - if (pipe.buckets.length > 0) { - for (var i = 0; i < pipe.buckets.length; i++) { - var bucket = pipe.buckets[i] - if (bucket.offset - bucket.roffset > 0) { - return 64 | 1 - } - } - } - } - return 0 - }, - ioctl: function(stream, request, varargs) { - return ERRNO_CODES.EINVAL - }, - read: function(stream, buffer, offset, length, position) { - var pipe = stream.node.pipe - var currentLength = 0 - for (var i = 0; i < pipe.buckets.length; i++) { - var bucket = pipe.buckets[i] - currentLength += bucket.offset - bucket.roffset - } - assert(buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer)) - var data = buffer.subarray(offset, offset + length) - if (length <= 0) { - return 0 - } - if (currentLength == 0) { - throw new FS.ErrnoError(ERRNO_CODES.EAGAIN) - } - var toRead = Math.min(currentLength, length) - var totalRead = toRead - var toRemove = 0 - for (var i = 0; i < pipe.buckets.length; i++) { - var currBucket = pipe.buckets[i] - var bucketSize = currBucket.offset - currBucket.roffset - if (toRead <= bucketSize) { - var tmpSlice = currBucket.buffer.subarray( - currBucket.roffset, - currBucket.offset - ) - if (toRead < bucketSize) { - tmpSlice = tmpSlice.subarray(0, toRead) - currBucket.roffset += toRead - } else { - toRemove++ - } - data.set(tmpSlice) - break - } else { - var tmpSlice = currBucket.buffer.subarray( - currBucket.roffset, - currBucket.offset - ) - data.set(tmpSlice) - data = data.subarray(tmpSlice.byteLength) - toRead -= tmpSlice.byteLength - toRemove++ - } - } - if (toRemove && toRemove == pipe.buckets.length) { - toRemove-- - pipe.buckets[toRemove].offset = 0 - pipe.buckets[toRemove].roffset = 0 - } - pipe.buckets.splice(0, toRemove) - return totalRead - }, - write: function(stream, buffer, offset, length, position) { - var pipe = stream.node.pipe - assert(buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer)) - var data = buffer.subarray(offset, offset + length) - var dataLen = data.byteLength - if (dataLen <= 0) { - return 0 - } - var currBucket = null - if (pipe.buckets.length == 0) { - currBucket = { - buffer: new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE), - offset: 0, - roffset: 0, - } - pipe.buckets.push(currBucket) - } else { - currBucket = pipe.buckets[pipe.buckets.length - 1] - } - assert(currBucket.offset <= PIPEFS.BUCKET_BUFFER_SIZE) - var freeBytesInCurrBuffer = PIPEFS.BUCKET_BUFFER_SIZE - currBucket.offset - if (freeBytesInCurrBuffer >= dataLen) { - currBucket.buffer.set(data, currBucket.offset) - currBucket.offset += dataLen - return dataLen - } else if (freeBytesInCurrBuffer > 0) { - currBucket.buffer.set( - data.subarray(0, freeBytesInCurrBuffer), - currBucket.offset - ) - currBucket.offset += freeBytesInCurrBuffer - data = data.subarray(freeBytesInCurrBuffer, data.byteLength) - } - var numBuckets = (data.byteLength / PIPEFS.BUCKET_BUFFER_SIZE) | 0 - var remElements = data.byteLength % PIPEFS.BUCKET_BUFFER_SIZE - for (var i = 0; i < numBuckets; i++) { - var newBucket = { - buffer: new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE), - offset: PIPEFS.BUCKET_BUFFER_SIZE, - roffset: 0, - } - pipe.buckets.push(newBucket) - newBucket.buffer.set(data.subarray(0, PIPEFS.BUCKET_BUFFER_SIZE)) - data = data.subarray(PIPEFS.BUCKET_BUFFER_SIZE, data.byteLength) - } - if (remElements > 0) { - var newBucket = { - buffer: new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE), - offset: data.byteLength, - roffset: 0, - } - pipe.buckets.push(newBucket) - newBucket.buffer.set(data) - } - return dataLen - }, - close: function(stream) { - var pipe = stream.node.pipe - pipe.buckets = null - }, - }, - nextname: function() { - if (!PIPEFS.nextname.current) { - PIPEFS.nextname.current = 0 - } - return 'pipe[' + PIPEFS.nextname.current++ + ']' - }, - } - function ___syscall42(which, varargs) { - SYSCALLS.varargs = varargs - try { - var fdPtr = SYSCALLS.get() - if (fdPtr == 0) { - throw new FS.ErrnoError(14) - } - var res = PIPEFS.createPipe() - HEAP32[fdPtr >> 2] = res.readable_fd - HEAP32[(fdPtr + 4) >> 2] = res.writable_fd - return 0 - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall5(which, varargs) { - SYSCALLS.varargs = varargs - try { - var pathname = SYSCALLS.getStr(), - flags = SYSCALLS.get(), - mode = SYSCALLS.get() - var stream = FS.open(pathname, flags, mode) - return stream.fd - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function ___syscall6(which, varargs) { - SYSCALLS.varargs = varargs - try { - var stream = SYSCALLS.getStreamFromFD() - FS.close(stream) - return 0 - } catch (e) { - if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e) - return -e.errno - } - } - function _abort() { - Module['abort']() - } - function _emscripten_get_heap_size() { - return HEAP8.length - } - function abortOnCannotGrowMemory(requestedSize) { - abort('OOM') - } - function emscripten_realloc_buffer(size) { - var PAGE_MULTIPLE = 65536 - size = alignUp(size, PAGE_MULTIPLE) - var oldSize = buffer.byteLength - try { - var result = wasmMemory.grow((size - oldSize) / 65536) - if (result !== (-1 | 0)) { - buffer = wasmMemory.buffer - return true - } else { - return false - } - } catch (e) { - return false - } - } - function _emscripten_resize_heap(requestedSize) { - var oldSize = _emscripten_get_heap_size() - var PAGE_MULTIPLE = 65536 - var LIMIT = 2147483648 - PAGE_MULTIPLE - if (requestedSize > LIMIT) { - return false - } - var MIN_TOTAL_MEMORY = 16777216 - var newSize = Math.max(oldSize, MIN_TOTAL_MEMORY) - while (newSize < requestedSize) { - if (newSize <= 536870912) { - newSize = alignUp(2 * newSize, PAGE_MULTIPLE) - } else { - newSize = Math.min( - alignUp((3 * newSize + 2147483648) / 4, PAGE_MULTIPLE), - LIMIT - ) - } - } - if (!emscripten_realloc_buffer(newSize)) { - return false - } - updateGlobalBufferViews() - return true - } - function _exit(status) { - exit(status) - } - var ___tm_current = 277408 - var ___tm_timezone = (stringToUTF8('GMT', 277456, 4), 277456) - function _tzset() { - if (_tzset.called) return - _tzset.called = true - HEAP32[__get_timezone() >> 2] = new Date().getTimezoneOffset() * 60 - var winter = new Date(2e3, 0, 1) - var summer = new Date(2e3, 6, 1) - HEAP32[__get_daylight() >> 2] = Number( - winter.getTimezoneOffset() != summer.getTimezoneOffset() - ) - function extractZone(date) { - var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/) - return match ? match[1] : 'GMT' - } - var winterName = extractZone(winter) - var summerName = extractZone(summer) - var winterNamePtr = allocate(intArrayFromString(winterName), 'i8', ALLOC_NORMAL) - var summerNamePtr = allocate(intArrayFromString(summerName), 'i8', ALLOC_NORMAL) - if (summer.getTimezoneOffset() < winter.getTimezoneOffset()) { - HEAP32[__get_tzname() >> 2] = winterNamePtr - HEAP32[(__get_tzname() + 4) >> 2] = summerNamePtr - } else { - HEAP32[__get_tzname() >> 2] = summerNamePtr - HEAP32[(__get_tzname() + 4) >> 2] = winterNamePtr - } - } - function _localtime_r(time, tmPtr) { - _tzset() - var date = new Date(HEAP32[time >> 2] * 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 start = new Date(date.getFullYear(), 0, 1) - var yday = ((date.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24)) | 0 - HEAP32[(tmPtr + 28) >> 2] = yday - HEAP32[(tmPtr + 36) >> 2] = -(date.getTimezoneOffset() * 60) - var summerOffset = new Date(2e3, 6, 1).getTimezoneOffset() - var winterOffset = start.getTimezoneOffset() - var dst = - (summerOffset != winterOffset && - date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0 - HEAP32[(tmPtr + 32) >> 2] = dst - var zonePtr = HEAP32[(__get_tzname() + (dst ? 4 : 0)) >> 2] - HEAP32[(tmPtr + 40) >> 2] = zonePtr - return tmPtr - } - function _localtime(time) { - return _localtime_r(time, ___tm_current) - } - function _emscripten_memcpy_big(dest, src, num) { - HEAPU8.set(HEAPU8.subarray(src, src + num), dest) - } - function _mktime(tmPtr) { - _tzset() - 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(2e3, 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 = ((date.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24)) | 0 - HEAP32[(tmPtr + 28) >> 2] = yday - return (date.getTime() / 1e3) | 0 - } - function _posix_spawn_file_actions_addclose() { - err('missing function: posix_spawn_file_actions_addclose') - abort(-1) - } - function _posix_spawn_file_actions_adddup2() { - err('missing function: posix_spawn_file_actions_adddup2') - abort(-1) - } - function _posix_spawn_file_actions_destroy() { - err('missing function: posix_spawn_file_actions_destroy') - abort(-1) - } - function _posix_spawn_file_actions_init() { - err('missing function: posix_spawn_file_actions_init') - abort(-1) - } - function _fork() { - ___setErrNo(11) - return -1 - } - function _posix_spawnp() { - return _fork.apply(null, arguments) - } - function _timegm(tmPtr) { - _tzset() - var time = Date.UTC( - 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 date = new Date(time) - 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 (date.getTime() / 1e3) | 0 - } - function _wait(stat_loc) { - ___setErrNo(10) - return -1 - } - function _waitpid() { - return _wait.apply(null, arguments) - } - FS.staticInit() - if (ENVIRONMENT_IS_NODE) { - var fs = require('fs') - var NODEJS_PATH = require('path') - NODEFS.staticInit() - } - function 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 asmGlobalArg = {} - var asmLibraryArg = { - b: abort, - q: setTempRet0, - G: ___buildEnvironment, - l: ___setErrNo, - s: ___syscall140, - i: ___syscall146, - p: ___syscall168, - o: ___syscall195, - n: ___syscall196, - m: ___syscall197, - c: ___syscall221, - F: ___syscall3, - E: ___syscall4, - D: ___syscall41, - C: ___syscall42, - B: ___syscall5, - h: ___syscall6, - g: _abort, - A: _emscripten_get_heap_size, - z: _emscripten_memcpy_big, - y: _emscripten_resize_heap, - f: _exit, - x: _localtime, - d: _mktime, - e: _posix_spawn_file_actions_addclose, - k: _posix_spawn_file_actions_adddup2, - j: _posix_spawn_file_actions_destroy, - w: _posix_spawn_file_actions_init, - v: _posix_spawnp, - u: _timegm, - t: _waitpid, - r: abortOnCannotGrowMemory, - a: DYNAMICTOP_PTR, - } - var asm = Module['asm'](asmGlobalArg, asmLibraryArg, buffer) - Module['asm'] = asm - var ___emscripten_environ_constructor = (Module[ - '___emscripten_environ_constructor' - ] = function() { - return Module['asm']['H'].apply(null, arguments) - }) - var ___errno_location = (Module['___errno_location'] = function() { - return Module['asm']['I'].apply(null, arguments) - }) - var __get_daylight = (Module['__get_daylight'] = function() { - return Module['asm']['J'].apply(null, arguments) - }) - var __get_timezone = (Module['__get_timezone'] = function() { - return Module['asm']['K'].apply(null, arguments) - }) - var __get_tzname = (Module['__get_tzname'] = function() { - return Module['asm']['L'].apply(null, arguments) - }) - var _archive_close = (Module['_archive_close'] = function() { - return Module['asm']['M'].apply(null, arguments) - }) - var _archive_entry_filetype = (Module['_archive_entry_filetype'] = function() { - return Module['asm']['N'].apply(null, arguments) - }) - var _archive_entry_is_encrypted = (Module[ - '_archive_entry_is_encrypted' - ] = function() { - return Module['asm']['O'].apply(null, arguments) - }) - var _archive_entry_pathname = (Module['_archive_entry_pathname'] = function() { - return Module['asm']['P'].apply(null, arguments) - }) - var _archive_entry_pathname_utf8 = (Module[ - '_archive_entry_pathname_utf8' - ] = function() { - return Module['asm']['Q'].apply(null, arguments) - }) - var _archive_entry_size = (Module['_archive_entry_size'] = function() { - return Module['asm']['R'].apply(null, arguments) - }) - var _archive_error_string = (Module['_archive_error_string'] = function() { - return Module['asm']['S'].apply(null, arguments) - }) - var _archive_open = (Module['_archive_open'] = function() { - return Module['asm']['T'].apply(null, arguments) - }) - var _archive_read_add_passphrase = (Module[ - '_archive_read_add_passphrase' - ] = function() { - return Module['asm']['U'].apply(null, arguments) - }) - var _archive_read_data_skip = (Module['_archive_read_data_skip'] = function() { - return Module['asm']['V'].apply(null, arguments) - }) - var _archive_read_has_encrypted_entries = (Module[ - '_archive_read_has_encrypted_entries' - ] = function() { - return Module['asm']['W'].apply(null, arguments) - }) - var _free = (Module['_free'] = function() { - return Module['asm']['X'].apply(null, arguments) - }) - var _get_filedata = (Module['_get_filedata'] = function() { - return Module['asm']['Y'].apply(null, arguments) - }) - var _get_next_entry = (Module['_get_next_entry'] = function() { - return Module['asm']['Z'].apply(null, arguments) - }) - var _get_version = (Module['_get_version'] = function() { - return Module['asm']['_'].apply(null, arguments) - }) - var _malloc = (Module['_malloc'] = function() { - return Module['asm']['$'].apply(null, arguments) - }) - var stackAlloc = (Module['stackAlloc'] = function() { - return Module['asm']['ca'].apply(null, arguments) - }) - var stackRestore = (Module['stackRestore'] = function() { - return Module['asm']['da'].apply(null, arguments) - }) - var stackSave = (Module['stackSave'] = function() { - return Module['asm']['ea'].apply(null, arguments) - }) - var dynCall_v = (Module['dynCall_v'] = function() { - return Module['asm']['aa'].apply(null, arguments) - }) - var dynCall_vi = (Module['dynCall_vi'] = function() { - return Module['asm']['ba'].apply(null, arguments) - }) - Module['asm'] = asm - Module['intArrayFromString'] = intArrayFromString - Module['cwrap'] = cwrap - Module['allocate'] = allocate - Module['then'] = function(func) { - if (Module['calledRun']) { - func(Module) - } else { - var old = Module['onRuntimeInitialized'] - Module['onRuntimeInitialized'] = function() { - if (old) old() - func(Module) - } - } - return Module - } - function ExitStatus(status) { - this.name = 'ExitStatus' - this.message = 'Program terminated with exit(' + status + ')' - this.status = status - } - ExitStatus.prototype = new Error() - ExitStatus.prototype.constructor = ExitStatus - dependenciesFulfilled = function runCaller() { - if (!Module['calledRun']) run() - if (!Module['calledRun']) dependenciesFulfilled = runCaller - } - function run(args) { - args = args || Module['arguments'] - if (runDependencies > 0) { - return - } - preRun() - if (runDependencies > 0) return - if (Module['calledRun']) return - function doRun() { - if (Module['calledRun']) return - Module['calledRun'] = true - if (ABORT) return - ensureInitRuntime() - preMain() - if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']() - postRun() - } - if (Module['setStatus']) { - Module['setStatus']('Running...') - setTimeout(function() { - setTimeout(function() { - Module['setStatus']('') - }, 1) - doRun() - }, 1) - } else { - doRun() - } - } - Module['run'] = run - function exit(status, implicit) { - if (implicit && Module['noExitRuntime'] && status === 0) { - return - } - if (Module['noExitRuntime']) { - } else { - ABORT = true - EXITSTATUS = status - exitRuntime() - if (Module['onExit']) Module['onExit'](status) - } - Module['quit'](status, new ExitStatus(status)) - } - function abort(what) { - if (Module['onAbort']) { - Module['onAbort'](what) - } - if (what !== undefined) { - out(what) - err(what) - what = JSON.stringify(what) - } else { - what = '' - } - ABORT = true - EXITSTATUS = 1 - throw 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.' - } - Module['abort'] = abort - if (Module['preInit']) { - if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']] - while (Module['preInit'].length > 0) { - Module['preInit'].pop()() - } - } - Module['noExitRuntime'] = true - run() - - return libarchive - } -})() -export default libarchive diff --git a/packages/villain-react/dev-sandbox/static/worker-bundle.js b/packages/villain-react/dev-sandbox/static/worker-bundle.js deleted file mode 100644 index be9885c5..00000000 --- a/packages/villain-react/dev-sandbox/static/worker-bundle.js +++ /dev/null @@ -1,3960 +0,0 @@ -!(function() { - 'use strict' - const e = { - 32768: 'FILE', - 16384: 'DIR', - 40960: 'SYMBOLIC_LINK', - 49152: 'SOCKET', - 8192: 'CHARACTER_DEVICE', - 24576: 'BLOCK_DEVICE', - 4096: 'NAMED_PIPE', - } - class r { - constructor(e) { - ;(this._wasmModule = e), - (this._runCode = e.runCode), - (this._file = null), - (this._passphrase = null) - } - open(e) { - null !== this._file && (console.warn('Closing previous file'), this.close()) - const { promise: r, resolve: t, reject: n } = this._promiseHandles() - this._file = e - const o = new FileReader() - return (o.onload = () => this._loadFile(o.result, t, n)), o.readAsArrayBuffer(e), r - } - close() { - this._runCode.closeArchive(this._archive), - this._wasmModule._free(this._filePtr), - (this._file = null), - (this._filePtr = null), - (this._archive = null) - } - hasEncryptedData() { - ;(this._archive = this._runCode.openArchive( - this._filePtr, - this._fileLength, - this._passphrase - )), - this._runCode.getNextEntry(this._archive) - const e = this._runCode.hasEncryptedEntries(this._archive) - return 0 !== e && (e > 0 || null) - } - setPassphrase(e) { - this._passphrase = e - } - *entries(r = !1, t = null) { - let n - for ( - this._archive = this._runCode.openArchive( - this._filePtr, - this._fileLength, - this._passphrase - ); - 0 !== (n = this._runCode.getNextEntry(this._archive)); - - ) { - const o = { - size: this._runCode.getEntrySize(n), - path: this._runCode.getEntryName(n), - type: e[this._runCode.getEntryType(n)], - ref: n, - } - if ('FILE' === o.type) { - let e = o.path.split('/') - o.fileName = e[e.length - 1] - } - if (r && t !== o.path) this._runCode.skipEntry(this._archive) - else { - const e = this._runCode.getFileData(this._archive, o.size) - if (e < 0) throw new Error(this._runCode.getError(this._archive)) - ;(o.fileData = this._wasmModule.HEAP8.slice(e, e + o.size)), - this._wasmModule._free(e) - } - yield o - } - } - _loadFile(e, r, t) { - try { - const n = new Uint8Array(e) - ;(this._fileLength = n.length), - (this._filePtr = this._runCode.malloc(this._fileLength)), - this._wasmModule.HEAP8.set(n, this._filePtr), - r() - } catch (e) { - t(e) - } - } - _promiseHandles() { - let e = null, - r = null - return { - promise: new Promise((t, n) => { - ;(e = t), (r = n) - }), - resolve: e, - reject: r, - } - } - } - var t, - n = - ((t = - 'undefined' != typeof document && document.currentScript - ? document.currentScript.src - : void 0), - function(e) { - var r, - n = void 0 !== (e = e || {}) ? e : {}, - o = {} - for (r in n) n.hasOwnProperty(r) && (o[r] = n[r]) - ;(n.arguments = []), - (n.thisProgram = './this.program'), - (n.quit = function(e, r) { - throw r - }), - (n.preRun = []), - (n.postRun = []) - var i, - a, - s = !1, - u = !1 - ;(s = 'object' == typeof window), - (u = 'function' == typeof importScripts), - (i = 'object' == typeof process && 'function' == typeof require && !s && !u), - (a = !s && !i && !u) - var c, - f, - l = '' - i - ? ((l = __dirname + '/'), - (n.read = function(e, r) { - var t - return ( - c || (c = require('fs')), - f || (f = require('path')), - (e = f.normalize(e)), - (t = c.readFileSync(e)), - r ? t : t.toString() - ) - }), - (n.readBinary = function(e) { - var r = n.read(e, !0) - return r.buffer || (r = new Uint8Array(r)), E(r.buffer), r - }), - process.argv.length > 1 && - (n.thisProgram = process.argv[1].replace(/\\/g, '/')), - (n.arguments = process.argv.slice(2)), - process.on('uncaughtException', function(e) { - if (!(e instanceof qe)) throw e - }), - process.on('unhandledRejection', Ze), - (n.quit = function(e) { - process.exit(e) - }), - (n.inspect = function() { - return '[Emscripten Module object]' - })) - : a - ? ('undefined' != typeof read && - (n.read = function(e) { - return read(e) - }), - (n.readBinary = function(e) { - var r - return 'function' == typeof readbuffer - ? new Uint8Array(readbuffer(e)) - : (E('object' == typeof (r = read(e, 'binary'))), r) - }), - 'undefined' != typeof scriptArgs - ? (n.arguments = scriptArgs) - : void 0 !== arguments && (n.arguments = arguments), - 'function' == typeof quit && - (n.quit = function(e) { - quit(e) - })) - : (s || u) && - (u - ? (l = self.location.href) - : document.currentScript && (l = document.currentScript.src), - t && (l = t), - (l = 0 !== l.indexOf('blob:') ? l.substr(0, l.lastIndexOf('/') + 1) : ''), - (n.read = function(e) { - var r = new XMLHttpRequest() - return r.open('GET', e, !1), r.send(null), r.responseText - }), - u && - (n.readBinary = function(e) { - var r = new XMLHttpRequest() - return ( - r.open('GET', e, !1), - (r.responseType = 'arraybuffer'), - r.send(null), - new Uint8Array(r.response) - ) - }), - (n.readAsync = function(e, r, t) { - var n = new XMLHttpRequest() - n.open('GET', e, !0), - (n.responseType = 'arraybuffer'), - (n.onload = function() { - 200 == n.status || (0 == n.status && n.response) ? r(n.response) : t() - }), - (n.onerror = t), - n.send(null) - }), - (n.setWindowTitle = function(e) { - document.title = e - })) - var d = - n.print || - ('undefined' != typeof console - ? console.log.bind(console) - : 'undefined' != typeof print - ? print - : null), - p = - n.printErr || - ('undefined' != typeof printErr - ? printErr - : ('undefined' != typeof console && console.warn.bind(console)) || d) - for (r in o) o.hasOwnProperty(r) && (n[r] = o[r]) - function m(e) { - var r = M[q >> 2], - t = (r + e + 15) & -16 - if (t <= Ae()) M[q >> 2] = t - else if (!Re(t)) return 0 - return r - } - function h(e) { - switch (e) { - case 'i1': - case 'i8': - return 1 - case 'i16': - return 2 - case 'i32': - return 4 - case 'i64': - return 8 - case 'float': - return 4 - case 'double': - return 8 - default: - if ('*' === e[e.length - 1]) return 4 - if ('i' === e[0]) { - var r = parseInt(e.substr(1)) - return ( - E(r % 8 == 0, 'getNativeTypeSize invalid bits ' + r + ', type ' + e), - r / 8 - ) - } - return 0 - } - } - o = void 0 - var v, - w = { - 'f64-rem': function(e, r) { - return e % r - }, - debugger: function() {}, - } - 'object' != typeof WebAssembly && p('no native wasm support detected') - var y = !1 - function E(e, r) { - e || Ze('Assertion failed: ' + r) - } - function g(e) { - var r = n['_' + e] - return ( - E(r, 'Cannot call unknown function ' + e + ', make sure it is exported'), r - ) - } - function _(e, r, t, n, o) { - var i = { - string: function(e) { - var r = 0 - if (null != e && 0 !== e) { - var t = 1 + (e.length << 2) - C(e, (r = je(t)), t) - } - return r - }, - array: function(e) { - var r, - t, - n = je(e.length) - return (r = e), (t = n), R.set(r, t), n - }, - }, - a = g(e), - s = [], - u = 0 - if (n) - for (var c = 0; c < n.length; c++) { - var f = i[t[c]] - f ? (0 === u && (u = We()), (s[c] = f(n[c]))) : (s[c] = n[c]) - } - var l = a.apply(null, s) - return ( - (l = (function(e) { - return 'string' === r ? I(e) : 'boolean' === r ? Boolean(e) : e - })(l)), - 0 !== u && He(u), - l - ) - } - function b(e, r, t, n) { - switch (('*' === (t = t || 'i8').charAt(t.length - 1) && (t = 'i32'), t)) { - case 'i1': - case 'i8': - R[e >> 0] = r - break - case 'i16': - P[e >> 1] = r - break - case 'i32': - M[e >> 2] = r - break - case 'i64': - ;(tempI64 = [ - r >>> 0, - ((tempDouble = r), - +J(tempDouble) >= 1 - ? tempDouble > 0 - ? (0 | re(+ee(tempDouble / 4294967296), 4294967295)) >>> 0 - : ~~+Q((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (M[e >> 2] = tempI64[0]), - (M[(e + 4) >> 2] = tempI64[1]) - break - case 'float': - B[e >> 2] = r - break - case 'double': - N[e >> 3] = r - break - default: - Ze('invalid type for setValue: ' + t) - } - } - var k = 0, - D = 3 - function S(e, r, t, n) { - var o, i - 'number' == typeof e ? ((o = !0), (i = e)) : ((o = !1), (i = e.length)) - var a, - s = 'string' == typeof r ? r : null - if (((a = t == D ? n : [Ue, je, m][t](Math.max(i, s ? 1 : r.length))), o)) { - var u - for (n = a, E(0 == (3 & a)), u = a + (-4 & i); n < u; n += 4) M[n >> 2] = 0 - for (u = a + i; n < u; ) R[n++ >> 0] = 0 - return a - } - if ('i8' === s) - return e.subarray || e.slice ? T.set(e, a) : T.set(new Uint8Array(e), a), a - for (var c, f, l, d = 0; d < i; ) { - var p = e[d] - 0 !== (c = s || r[d]) - ? ('i64' == c && (c = 'i32'), - b(a + d, p, c), - l !== c && ((f = h(c)), (l = c)), - (d += f)) - : d++ - } - return a - } - function F(e) { - return $ ? Ue(e) : m(e) - } - var A, - R, - T, - P, - M, - B, - N, - O = 'undefined' != typeof TextDecoder ? new TextDecoder('utf8') : void 0 - function x(e, r, t) { - for (var n = r + t, o = r; e[o] && !(o >= n); ) ++o - if (o - r > 16 && e.subarray && O) return O.decode(e.subarray(r, o)) - for (var i = ''; r < o; ) { - var a = e[r++] - if (128 & a) { - var s = 63 & e[r++] - if (192 != (224 & a)) { - var u = 63 & e[r++] - if ( - (a = - 224 == (240 & a) - ? ((15 & a) << 12) | (s << 6) | u - : ((7 & a) << 18) | (s << 12) | (u << 6) | (63 & e[r++])) < 65536 - ) - i += String.fromCharCode(a) - else { - var c = a - 65536 - i += String.fromCharCode(55296 | (c >> 10), 56320 | (1023 & c)) - } - } else i += String.fromCharCode(((31 & a) << 6) | s) - } else i += String.fromCharCode(a) - } - return i - } - function I(e, r) { - return e ? x(T, e, r) : '' - } - function z(e, r, t, n) { - if (!(n > 0)) return 0 - for (var o = t, i = t + n - 1, a = 0; a < e.length; ++a) { - var s = e.charCodeAt(a) - if ( - (s >= 55296 && - s <= 57343 && - (s = (65536 + ((1023 & s) << 10)) | (1023 & e.charCodeAt(++a))), - s <= 127) - ) { - if (t >= i) break - r[t++] = s - } else if (s <= 2047) { - if (t + 1 >= i) break - ;(r[t++] = 192 | (s >> 6)), (r[t++] = 128 | (63 & s)) - } else if (s <= 65535) { - if (t + 2 >= i) break - ;(r[t++] = 224 | (s >> 12)), - (r[t++] = 128 | ((s >> 6) & 63)), - (r[t++] = 128 | (63 & s)) - } else { - if (t + 3 >= i) break - ;(r[t++] = 240 | (s >> 18)), - (r[t++] = 128 | ((s >> 12) & 63)), - (r[t++] = 128 | ((s >> 6) & 63)), - (r[t++] = 128 | (63 & s)) - } - } - return (r[t] = 0), t - o - } - function C(e, r, t) { - return z(e, T, r, t) - } - function L(e) { - for (var r = 0, t = 0; t < e.length; ++t) { - var n = e.charCodeAt(t) - n >= 55296 && - n <= 57343 && - (n = (65536 + ((1023 & n) << 10)) | (1023 & e.charCodeAt(++t))), - n <= 127 ? ++r : (r += n <= 2047 ? 2 : n <= 65535 ? 3 : 4) - } - return r - } - function U(e, r, t) { - for (var n = 0; n < e.length; ++n) R[r++ >> 0] = e.charCodeAt(n) - t || (R[r >> 0] = 0) - } - function j() { - var e = (function() { - var e = new Error() - if (!e.stack) { - try { - throw new Error(0) - } catch (r) { - e = r - } - if (!e.stack) return '(no stack trace available)' - } - return e.stack.toString() - })() - return ( - n.extraStackTrace && (e += '\n' + n.extraStackTrace()), - e.replace(/__Z[\w\d_]+/g, function(e) { - var r = e - return e === r ? e : r + ' [' + e + ']' - }) - ) - } - function H(e, r) { - return e % r > 0 && (e += r - (e % r)), e - } - function W() { - ;(n.HEAP8 = R = new Int8Array(A)), - (n.HEAP16 = P = new Int16Array(A)), - (n.HEAP32 = M = new Int32Array(A)), - (n.HEAPU8 = T = new Uint8Array(A)), - (n.HEAPU16 = new Uint16Array(A)), - (n.HEAPU32 = new Uint32Array(A)), - (n.HEAPF32 = B = new Float32Array(A)), - (n.HEAPF64 = N = new Float64Array(A)) - } - 'undefined' != typeof TextDecoder && new TextDecoder('utf-16le') - var q = 277552, - K = n.TOTAL_MEMORY || 16777216 - function Z(e) { - for (; e.length > 0; ) { - var r = e.shift() - if ('function' != typeof r) { - var t = r.func - 'number' == typeof t - ? void 0 === r.arg - ? n.dynCall_v(t) - : n.dynCall_vi(t, r.arg) - : t(void 0 === r.arg ? null : r.arg) - } else r() - } - } - K < 5242880 && - p( - 'TOTAL_MEMORY should be larger than TOTAL_STACK, was ' + - K + - '! (TOTAL_STACK=5242880)' - ), - n.buffer - ? (A = n.buffer) - : 'object' == typeof WebAssembly && 'function' == typeof WebAssembly.Memory - ? ((v = new WebAssembly.Memory({ initial: K / 65536 })), (A = v.buffer)) - : (A = new ArrayBuffer(K)), - W(), - (M[q >> 2] = 5520464) - var V = [], - X = [], - Y = [], - G = [], - $ = !1, - J = Math.abs, - Q = Math.ceil, - ee = Math.floor, - re = Math.min, - te = 0, - ne = null, - oe = null - function ie(e) { - te++, n.monitorRunDependencies && n.monitorRunDependencies(te) - } - function ae(e) { - if ( - (te--, - n.monitorRunDependencies && n.monitorRunDependencies(te), - 0 == te && (null !== ne && (clearInterval(ne), (ne = null)), oe)) - ) { - var r = oe - ;(oe = null), r() - } - } - ;(n.preloadedImages = {}), (n.preloadedAudios = {}) - var se = 'data:application/octet-stream;base64,' - function ue(e) { - return String.prototype.startsWith ? e.startsWith(se) : 0 === e.indexOf(se) - } - var ce, - fe = 'libarchive.wasm' - function le() { - try { - if (n.wasmBinary) return new Uint8Array(n.wasmBinary) - if (n.readBinary) return n.readBinary(fe) - throw 'both async and sync fetching of the wasm failed' - } catch (e) { - Ze(e) - } - } - function de(e) { - var r = { - env: e, - global: { NaN: NaN, Infinity: 1 / 0 }, - 'global.Math': Math, - asm2wasm: w, - } - function t(e, r) { - var t = e.exports - ;(n.asm = t), ae() - } - if ((ie(), n.instantiateWasm)) - try { - return n.instantiateWasm(r, t) - } catch (e) { - return p('Module.instantiateWasm callback failed with error: ' + e), !1 - } - function o(e) { - t(e.instance) - } - function i(e) { - ;(n.wasmBinary || (!s && !u) || 'function' != typeof fetch - ? new Promise(function(e, r) { - e(le()) - }) - : fetch(fe, { credentials: 'same-origin' }) - .then(function(e) { - if (!e.ok) throw "failed to load wasm binary file at '" + fe + "'" - return e.arrayBuffer() - }) - .catch(function() { - return le() - }) - ) - .then(function(e) { - return WebAssembly.instantiate(e, r) - }) - .then(e, function(e) { - p('failed to asynchronously prepare wasm: ' + e), Ze(e) - }) - } - return ( - n.wasmBinary || - 'function' != typeof WebAssembly.instantiateStreaming || - ue(fe) || - 'function' != typeof fetch - ? i(o) - : WebAssembly.instantiateStreaming( - fetch(fe, { credentials: 'same-origin' }), - r - ).then(o, function(e) { - p('wasm streaming compile failed: ' + e), - p('falling back to ArrayBuffer instantiation'), - i(o) - }), - {} - ) - } - ue(fe) || ((ce = fe), (fe = n.locateFile ? n.locateFile(ce, l) : l + ce)), - (n.asm = function(e, r, t) { - return ( - (r.memory = v), - (r.table = new WebAssembly.Table({ - initial: 507, - maximum: 507, - element: 'anyfunc', - })), - (r.__memory_base = 1024), - (r.__table_base = 0), - de(r) - ) - }), - X.push({ - func: function() { - Ie() - }, - }) - var pe = {}, - me = { - splitPath: function(e) { - return /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/ - .exec(e) - .slice(1) - }, - normalizeArray: function(e, r) { - for (var t = 0, n = e.length - 1; n >= 0; n--) { - var o = e[n] - '.' === o - ? e.splice(n, 1) - : '..' === o - ? (e.splice(n, 1), t++) - : t && (e.splice(n, 1), t--) - } - if (r) for (; t; t--) e.unshift('..') - return e - }, - normalize: function(e) { - var r = '/' === e.charAt(0), - t = '/' === e.substr(-1) - return ( - (e = me - .normalizeArray( - e.split('/').filter(function(e) { - return !!e - }), - !r - ) - .join('/')) || - r || - (e = '.'), - e && t && (e += '/'), - (r ? '/' : '') + e - ) - }, - dirname: function(e) { - var r = me.splitPath(e), - t = r[0], - n = r[1] - return t || n ? (n && (n = n.substr(0, n.length - 1)), t + n) : '.' - }, - basename: function(e) { - if ('/' === e) return '/' - var r = e.lastIndexOf('/') - return -1 === r ? e : e.substr(r + 1) - }, - extname: function(e) { - return me.splitPath(e)[3] - }, - join: function() { - var e = Array.prototype.slice.call(arguments, 0) - return me.normalize(e.join('/')) - }, - join2: function(e, r) { - return me.normalize(e + '/' + r) - }, - } - function he(e) { - return n.___errno_location && (M[n.___errno_location() >> 2] = e), e - } - var ve = { - resolve: function() { - for (var e = '', r = !1, t = arguments.length - 1; t >= -1 && !r; t--) { - var n = t >= 0 ? arguments[t] : be.cwd() - if ('string' != typeof n) - throw new TypeError('Arguments to path.resolve must be strings') - if (!n) return '' - ;(e = n + '/' + e), (r = '/' === n.charAt(0)) - } - return ( - (r ? '/' : '') + - (e = me - .normalizeArray( - e.split('/').filter(function(e) { - return !!e - }), - !r - ) - .join('/')) || '.' - ) - }, - relative: function(e, r) { - function t(e) { - for (var r = 0; r < e.length && '' === e[r]; r++); - for (var t = e.length - 1; t >= 0 && '' === e[t]; t--); - return r > t ? [] : e.slice(r, t - r + 1) - } - ;(e = ve.resolve(e).substr(1)), (r = ve.resolve(r).substr(1)) - for ( - var n = t(e.split('/')), - o = t(r.split('/')), - i = Math.min(n.length, o.length), - a = i, - s = 0; - s < i; - s++ - ) - if (n[s] !== o[s]) { - a = s - break - } - var u = [] - for (s = a; s < n.length; s++) u.push('..') - return (u = u.concat(o.slice(a))).join('/') - }, - }, - we = { - ttys: [], - init: function() {}, - shutdown: function() {}, - register: function(e, r) { - ;(we.ttys[e] = { input: [], output: [], ops: r }), - be.registerDevice(e, we.stream_ops) - }, - stream_ops: { - open: function(e) { - var r = we.ttys[e.node.rdev] - if (!r) throw new be.ErrnoError(19) - ;(e.tty = r), (e.seekable = !1) - }, - close: function(e) { - e.tty.ops.flush(e.tty) - }, - flush: function(e) { - e.tty.ops.flush(e.tty) - }, - read: function(e, r, t, n, o) { - if (!e.tty || !e.tty.ops.get_char) throw new be.ErrnoError(6) - for (var i = 0, a = 0; a < n; a++) { - var s - try { - s = e.tty.ops.get_char(e.tty) - } catch (e) { - throw new be.ErrnoError(5) - } - if (void 0 === s && 0 === i) throw new be.ErrnoError(11) - if (null == s) break - i++, (r[t + a] = s) - } - return i && (e.node.timestamp = Date.now()), i - }, - write: function(e, r, t, n, o) { - if (!e.tty || !e.tty.ops.put_char) throw new be.ErrnoError(6) - try { - for (var i = 0; i < n; i++) e.tty.ops.put_char(e.tty, r[t + i]) - } catch (e) { - throw new be.ErrnoError(5) - } - return n && (e.node.timestamp = Date.now()), i - }, - }, - default_tty_ops: { - get_char: function(e) { - if (!e.input.length) { - var r = null - if (i) { - var t = new Buffer(256), - n = 0, - o = 'win32' != process.platform, - a = process.stdin.fd - if (o) { - var s = !1 - try { - ;(a = Me.openSync('/dev/stdin', 'r')), (s = !0) - } catch (e) {} - } - try { - n = Me.readSync(a, t, 0, 256, null) - } catch (e) { - if (-1 == e.toString().indexOf('EOF')) throw e - n = 0 - } - s && Me.closeSync(a), - (r = n > 0 ? t.slice(0, n).toString('utf-8') : null) - } else - 'undefined' != typeof window && 'function' == typeof window.prompt - ? null !== (r = window.prompt('Input: ')) && (r += '\n') - : 'function' == typeof readline && - null !== (r = readline()) && - (r += '\n') - if (!r) return null - e.input = Ne(r, !0) - } - return e.input.shift() - }, - put_char: function(e, r) { - null === r || 10 === r - ? (d(x(e.output, 0)), (e.output = [])) - : 0 != r && e.output.push(r) - }, - flush: function(e) { - e.output && e.output.length > 0 && (d(x(e.output, 0)), (e.output = [])) - }, - }, - default_tty1_ops: { - put_char: function(e, r) { - null === r || 10 === r - ? (p(x(e.output, 0)), (e.output = [])) - : 0 != r && e.output.push(r) - }, - flush: function(e) { - e.output && e.output.length > 0 && (p(x(e.output, 0)), (e.output = [])) - }, - }, - }, - ye = { - ops_table: null, - mount: function(e) { - return ye.createNode(null, '/', 16895, 0) - }, - createNode: function(e, r, t, n) { - if (be.isBlkdev(t) || be.isFIFO(t)) throw new be.ErrnoError(1) - ye.ops_table || - (ye.ops_table = { - dir: { - node: { - getattr: ye.node_ops.getattr, - setattr: ye.node_ops.setattr, - lookup: ye.node_ops.lookup, - mknod: ye.node_ops.mknod, - rename: ye.node_ops.rename, - unlink: ye.node_ops.unlink, - rmdir: ye.node_ops.rmdir, - readdir: ye.node_ops.readdir, - symlink: ye.node_ops.symlink, - }, - stream: { llseek: ye.stream_ops.llseek }, - }, - file: { - node: { getattr: ye.node_ops.getattr, setattr: ye.node_ops.setattr }, - stream: { - llseek: ye.stream_ops.llseek, - read: ye.stream_ops.read, - write: ye.stream_ops.write, - allocate: ye.stream_ops.allocate, - mmap: ye.stream_ops.mmap, - msync: ye.stream_ops.msync, - }, - }, - link: { - node: { - getattr: ye.node_ops.getattr, - setattr: ye.node_ops.setattr, - readlink: ye.node_ops.readlink, - }, - stream: {}, - }, - chrdev: { - node: { getattr: ye.node_ops.getattr, setattr: ye.node_ops.setattr }, - stream: be.chrdev_stream_ops, - }, - }) - var o = be.createNode(e, r, t, n) - return ( - be.isDir(o.mode) - ? ((o.node_ops = ye.ops_table.dir.node), - (o.stream_ops = ye.ops_table.dir.stream), - (o.contents = {})) - : be.isFile(o.mode) - ? ((o.node_ops = ye.ops_table.file.node), - (o.stream_ops = ye.ops_table.file.stream), - (o.usedBytes = 0), - (o.contents = null)) - : be.isLink(o.mode) - ? ((o.node_ops = ye.ops_table.link.node), - (o.stream_ops = ye.ops_table.link.stream)) - : be.isChrdev(o.mode) && - ((o.node_ops = ye.ops_table.chrdev.node), - (o.stream_ops = ye.ops_table.chrdev.stream)), - (o.timestamp = Date.now()), - e && (e.contents[r] = o), - o - ) - }, - getFileDataAsRegularArray: function(e) { - if (e.contents && e.contents.subarray) { - for (var r = [], t = 0; t < e.usedBytes; ++t) r.push(e.contents[t]) - return r - } - return e.contents - }, - getFileDataAsTypedArray: function(e) { - return e.contents - ? e.contents.subarray - ? e.contents.subarray(0, e.usedBytes) - : new Uint8Array(e.contents) - : new Uint8Array() - }, - expandFileStorage: function(e, r) { - var t = e.contents ? e.contents.length : 0 - if (!(t >= r)) { - ;(r = Math.max(r, (t * (t < 1048576 ? 2 : 1.125)) | 0)), - 0 != t && (r = Math.max(r, 256)) - var n = e.contents - ;(e.contents = new Uint8Array(r)), - e.usedBytes > 0 && e.contents.set(n.subarray(0, e.usedBytes), 0) - } - }, - resizeFileStorage: function(e, r) { - if (e.usedBytes != r) { - if (0 == r) return (e.contents = null), void (e.usedBytes = 0) - if (!e.contents || e.contents.subarray) { - var t = e.contents - return ( - (e.contents = new Uint8Array(new ArrayBuffer(r))), - t && e.contents.set(t.subarray(0, Math.min(r, e.usedBytes))), - void (e.usedBytes = r) - ) - } - if ((e.contents || (e.contents = []), e.contents.length > r)) - e.contents.length = r - else for (; e.contents.length < r; ) e.contents.push(0) - e.usedBytes = r - } - }, - node_ops: { - getattr: function(e) { - var r = {} - return ( - (r.dev = be.isChrdev(e.mode) ? e.id : 1), - (r.ino = e.id), - (r.mode = e.mode), - (r.nlink = 1), - (r.uid = 0), - (r.gid = 0), - (r.rdev = e.rdev), - be.isDir(e.mode) - ? (r.size = 4096) - : be.isFile(e.mode) - ? (r.size = e.usedBytes) - : be.isLink(e.mode) - ? (r.size = e.link.length) - : (r.size = 0), - (r.atime = new Date(e.timestamp)), - (r.mtime = new Date(e.timestamp)), - (r.ctime = new Date(e.timestamp)), - (r.blksize = 4096), - (r.blocks = Math.ceil(r.size / r.blksize)), - r - ) - }, - setattr: function(e, r) { - void 0 !== r.mode && (e.mode = r.mode), - void 0 !== r.timestamp && (e.timestamp = r.timestamp), - void 0 !== r.size && ye.resizeFileStorage(e, r.size) - }, - lookup: function(e, r) { - throw be.genericErrors[2] - }, - mknod: function(e, r, t, n) { - return ye.createNode(e, r, t, n) - }, - rename: function(e, r, t) { - if (be.isDir(e.mode)) { - var n - try { - n = be.lookupNode(r, t) - } catch (e) {} - if (n) for (var o in n.contents) throw new be.ErrnoError(39) - } - delete e.parent.contents[e.name], - (e.name = t), - (r.contents[t] = e), - (e.parent = r) - }, - unlink: function(e, r) { - delete e.contents[r] - }, - rmdir: function(e, r) { - var t = be.lookupNode(e, r) - for (var n in t.contents) throw new be.ErrnoError(39) - delete e.contents[r] - }, - readdir: function(e) { - var r = ['.', '..'] - for (var t in e.contents) e.contents.hasOwnProperty(t) && r.push(t) - return r - }, - symlink: function(e, r, t) { - var n = ye.createNode(e, r, 41471, 0) - return (n.link = t), n - }, - readlink: function(e) { - if (!be.isLink(e.mode)) throw new be.ErrnoError(22) - return e.link - }, - }, - stream_ops: { - read: function(e, r, t, n, o) { - var i = e.node.contents - if (o >= e.node.usedBytes) return 0 - var a = Math.min(e.node.usedBytes - o, n) - if (a > 8 && i.subarray) r.set(i.subarray(o, o + a), t) - else for (var s = 0; s < a; s++) r[t + s] = i[o + s] - return a - }, - write: function(e, r, t, n, o, i) { - if (!n) return 0 - var a = e.node - if ( - ((a.timestamp = Date.now()), - r.subarray && (!a.contents || a.contents.subarray)) - ) { - if (0 === a.usedBytes && 0 === o) - return ( - (a.contents = new Uint8Array(r.subarray(t, t + n))), - (a.usedBytes = n), - n - ) - if (o + n <= a.usedBytes) - return a.contents.set(r.subarray(t, t + n), o), n - } - if ((ye.expandFileStorage(a, o + n), a.contents.subarray && r.subarray)) - a.contents.set(r.subarray(t, t + n), o) - else for (var s = 0; s < n; s++) a.contents[o + s] = r[t + s] - return (a.usedBytes = Math.max(a.usedBytes, o + n)), n - }, - llseek: function(e, r, t) { - var n = r - if ( - (1 === t - ? (n += e.position) - : 2 === t && be.isFile(e.node.mode) && (n += e.node.usedBytes), - n < 0) - ) - throw new be.ErrnoError(22) - return n - }, - allocate: function(e, r, t) { - ye.expandFileStorage(e.node, r + t), - (e.node.usedBytes = Math.max(e.node.usedBytes, r + t)) - }, - mmap: function(e, r, t, n, o, i, a) { - if (!be.isFile(e.node.mode)) throw new be.ErrnoError(19) - var s, - u, - c = e.node.contents - if (2 & a || (c.buffer !== r && c.buffer !== r.buffer)) { - if ( - ((o > 0 || o + n < e.node.usedBytes) && - (c = c.subarray - ? c.subarray(o, o + n) - : Array.prototype.slice.call(c, o, o + n)), - (u = !0), - !(s = Ue(n))) - ) - throw new be.ErrnoError(12) - r.set(c, s) - } else (u = !1), (s = c.byteOffset) - return { ptr: s, allocated: u } - }, - msync: function(e, r, t, n, o) { - if (!be.isFile(e.node.mode)) throw new be.ErrnoError(19) - return 2 & o ? 0 : (ye.stream_ops.write(e, r, 0, n, t, !1), 0) - }, - }, - }, - Ee = { - dbs: {}, - indexedDB: function() { - if ('undefined' != typeof indexedDB) return indexedDB - var e = null - return ( - 'object' == typeof window && - (e = - window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB), - E(e, 'IDBFS used, but indexedDB not supported'), - e - ) - }, - DB_VERSION: 21, - DB_STORE_NAME: 'FILE_DATA', - mount: function(e) { - return ye.mount.apply(null, arguments) - }, - syncfs: function(e, r, t) { - Ee.getLocalSet(e, function(n, o) { - if (n) return t(n) - Ee.getRemoteSet(e, function(e, n) { - if (e) return t(e) - var i = r ? n : o, - a = r ? o : n - Ee.reconcile(i, a, t) - }) - }) - }, - getDB: function(e, r) { - var t, - n = Ee.dbs[e] - if (n) return r(null, n) - try { - t = Ee.indexedDB().open(e, Ee.DB_VERSION) - } catch (e) { - return r(e) - } - if (!t) return r('Unable to connect to IndexedDB') - ;(t.onupgradeneeded = function(e) { - var r, - t = e.target.result, - n = e.target.transaction - ;(r = t.objectStoreNames.contains(Ee.DB_STORE_NAME) - ? n.objectStore(Ee.DB_STORE_NAME) - : t.createObjectStore(Ee.DB_STORE_NAME)).indexNames.contains( - 'timestamp' - ) || r.createIndex('timestamp', 'timestamp', { unique: !1 }) - }), - (t.onsuccess = function() { - ;(n = t.result), (Ee.dbs[e] = n), r(null, n) - }), - (t.onerror = function(e) { - r(this.error), e.preventDefault() - }) - }, - getLocalSet: function(e, r) { - var t = {} - function n(e) { - return '.' !== e && '..' !== e - } - function o(e) { - return function(r) { - return me.join2(e, r) - } - } - for ( - var i = be - .readdir(e.mountpoint) - .filter(n) - .map(o(e.mountpoint)); - i.length; - - ) { - var a, - s = i.pop() - try { - a = be.stat(s) - } catch (e) { - return r(e) - } - be.isDir(a.mode) && - i.push.apply( - i, - be - .readdir(s) - .filter(n) - .map(o(s)) - ), - (t[s] = { timestamp: a.mtime }) - } - return r(null, { type: 'local', entries: t }) - }, - getRemoteSet: function(e, r) { - var t = {} - Ee.getDB(e.mountpoint, function(e, n) { - if (e) return r(e) - try { - var o = n.transaction([Ee.DB_STORE_NAME], 'readonly') - ;(o.onerror = function(e) { - r(this.error), e.preventDefault() - }), - (o - .objectStore(Ee.DB_STORE_NAME) - .index('timestamp') - .openKeyCursor().onsuccess = function(e) { - var o = e.target.result - if (!o) return r(null, { type: 'remote', db: n, entries: t }) - ;(t[o.primaryKey] = { timestamp: o.key }), o.continue() - }) - } catch (e) { - return r(e) - } - }) - }, - loadLocalEntry: function(e, r) { - var t, n - try { - ;(n = be.lookupPath(e).node), (t = be.stat(e)) - } catch (e) { - return r(e) - } - return be.isDir(t.mode) - ? r(null, { timestamp: t.mtime, mode: t.mode }) - : be.isFile(t.mode) - ? ((n.contents = ye.getFileDataAsTypedArray(n)), - r(null, { timestamp: t.mtime, mode: t.mode, contents: n.contents })) - : r(new Error('node type not supported')) - }, - storeLocalEntry: function(e, r, t) { - try { - if (be.isDir(r.mode)) be.mkdir(e, r.mode) - else { - if (!be.isFile(r.mode)) return t(new Error('node type not supported')) - be.writeFile(e, r.contents, { canOwn: !0 }) - } - be.chmod(e, r.mode), be.utime(e, r.timestamp, r.timestamp) - } catch (e) { - return t(e) - } - t(null) - }, - removeLocalEntry: function(e, r) { - try { - be.lookupPath(e) - var t = be.stat(e) - be.isDir(t.mode) ? be.rmdir(e) : be.isFile(t.mode) && be.unlink(e) - } catch (e) { - return r(e) - } - r(null) - }, - loadRemoteEntry: function(e, r, t) { - var n = e.get(r) - ;(n.onsuccess = function(e) { - t(null, e.target.result) - }), - (n.onerror = function(e) { - t(this.error), e.preventDefault() - }) - }, - storeRemoteEntry: function(e, r, t, n) { - var o = e.put(t, r) - ;(o.onsuccess = function() { - n(null) - }), - (o.onerror = function(e) { - n(this.error), e.preventDefault() - }) - }, - removeRemoteEntry: function(e, r, t) { - var n = e.delete(r) - ;(n.onsuccess = function() { - t(null) - }), - (n.onerror = function(e) { - t(this.error), e.preventDefault() - }) - }, - reconcile: function(e, r, t) { - var n = 0, - o = [] - Object.keys(e.entries).forEach(function(t) { - var i = e.entries[t], - a = r.entries[t] - ;(!a || i.timestamp > a.timestamp) && (o.push(t), n++) - }) - var i = [] - if ( - (Object.keys(r.entries).forEach(function(t) { - r.entries[t], e.entries[t] || (i.push(t), n++) - }), - !n) - ) - return t(null) - var a = 0, - s = ('remote' === e.type ? e.db : r.db).transaction( - [Ee.DB_STORE_NAME], - 'readwrite' - ), - u = s.objectStore(Ee.DB_STORE_NAME) - function c(e) { - return e - ? c.errored - ? void 0 - : ((c.errored = !0), t(e)) - : ++a >= n - ? t(null) - : void 0 - } - ;(s.onerror = function(e) { - c(this.error), e.preventDefault() - }), - o.sort().forEach(function(e) { - 'local' === r.type - ? Ee.loadRemoteEntry(u, e, function(r, t) { - if (r) return c(r) - Ee.storeLocalEntry(e, t, c) - }) - : Ee.loadLocalEntry(e, function(r, t) { - if (r) return c(r) - Ee.storeRemoteEntry(u, e, t, c) - }) - }), - i - .sort() - .reverse() - .forEach(function(e) { - 'local' === r.type - ? Ee.removeLocalEntry(e, c) - : Ee.removeRemoteEntry(u, e, c) - }) - }, - }, - ge = { - isWindows: !1, - staticInit: function() { - ge.isWindows = !!process.platform.match(/^win/) - var e = process.binding('constants') - e.fs && (e = e.fs), - (ge.flagsForNodeMap = { - 1024: e.O_APPEND, - 64: e.O_CREAT, - 128: e.O_EXCL, - 0: e.O_RDONLY, - 2: e.O_RDWR, - 4096: e.O_SYNC, - 512: e.O_TRUNC, - 1: e.O_WRONLY, - }) - }, - bufferFrom: function(e) { - return Buffer.alloc ? Buffer.from(e) : new Buffer(e) - }, - mount: function(e) { - return E(i), ge.createNode(null, '/', ge.getMode(e.opts.root), 0) - }, - createNode: function(e, r, t, n) { - if (!be.isDir(t) && !be.isFile(t) && !be.isLink(t)) - throw new be.ErrnoError(22) - var o = be.createNode(e, r, t) - return (o.node_ops = ge.node_ops), (o.stream_ops = ge.stream_ops), o - }, - getMode: function(e) { - var r - try { - ;(r = Me.lstatSync(e)), - ge.isWindows && (r.mode = r.mode | ((292 & r.mode) >> 2)) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - return r.mode - }, - realPath: function(e) { - for (var r = []; e.parent !== e; ) r.push(e.name), (e = e.parent) - return r.push(e.mount.opts.root), r.reverse(), me.join.apply(null, r) - }, - flagsForNode: function(e) { - ;(e &= -2097153), (e &= -2049), (e &= -32769), (e &= -524289) - var r = 0 - for (var t in ge.flagsForNodeMap) - e & t && ((r |= ge.flagsForNodeMap[t]), (e ^= t)) - if (e) throw new be.ErrnoError(22) - return r - }, - node_ops: { - getattr: function(e) { - var r, - t = ge.realPath(e) - try { - r = Me.lstatSync(t) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - return ( - ge.isWindows && !r.blksize && (r.blksize = 4096), - ge.isWindows && - !r.blocks && - (r.blocks = ((r.size + r.blksize - 1) / r.blksize) | 0), - { - dev: r.dev, - ino: r.ino, - mode: r.mode, - nlink: r.nlink, - uid: r.uid, - gid: r.gid, - rdev: r.rdev, - size: r.size, - atime: r.atime, - mtime: r.mtime, - ctime: r.ctime, - blksize: r.blksize, - blocks: r.blocks, - } - ) - }, - setattr: function(e, r) { - var t = ge.realPath(e) - try { - if ( - (void 0 !== r.mode && (Me.chmodSync(t, r.mode), (e.mode = r.mode)), - void 0 !== r.timestamp) - ) { - var n = new Date(r.timestamp) - Me.utimesSync(t, n, n) - } - void 0 !== r.size && Me.truncateSync(t, r.size) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - lookup: function(e, r) { - var t = me.join2(ge.realPath(e), r), - n = ge.getMode(t) - return ge.createNode(e, r, n) - }, - mknod: function(e, r, t, n) { - var o = ge.createNode(e, r, t, n), - i = ge.realPath(o) - try { - be.isDir(o.mode) - ? Me.mkdirSync(i, o.mode) - : Me.writeFileSync(i, '', { mode: o.mode }) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - return o - }, - rename: function(e, r, t) { - var n = ge.realPath(e), - o = me.join2(ge.realPath(r), t) - try { - Me.renameSync(n, o) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - unlink: function(e, r) { - var t = me.join2(ge.realPath(e), r) - try { - Me.unlinkSync(t) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - rmdir: function(e, r) { - var t = me.join2(ge.realPath(e), r) - try { - Me.rmdirSync(t) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - readdir: function(e) { - var r = ge.realPath(e) - try { - return Me.readdirSync(r) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - symlink: function(e, r, t) { - var n = me.join2(ge.realPath(e), r) - try { - Me.symlinkSync(t, n) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - readlink: function(e) { - var r = ge.realPath(e) - try { - return ( - (r = Me.readlinkSync(r)), - (r = Be.relative(Be.resolve(e.mount.opts.root), r)) - ) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - }, - stream_ops: { - open: function(e) { - var r = ge.realPath(e.node) - try { - be.isFile(e.node.mode) && - (e.nfd = Me.openSync(r, ge.flagsForNode(e.flags))) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - close: function(e) { - try { - be.isFile(e.node.mode) && e.nfd && Me.closeSync(e.nfd) - } catch (e) { - if (!e.code) throw e - throw new be.ErrnoError(-e.errno) - } - }, - read: function(e, r, t, n, o) { - if (0 === n) return 0 - try { - return Me.readSync(e.nfd, ge.bufferFrom(r.buffer), t, n, o) - } catch (e) { - throw new be.ErrnoError(-e.errno) - } - }, - write: function(e, r, t, n, o) { - try { - return Me.writeSync(e.nfd, ge.bufferFrom(r.buffer), t, n, o) - } catch (e) { - throw new be.ErrnoError(-e.errno) - } - }, - llseek: function(e, r, t) { - var n = r - if (1 === t) n += e.position - else if (2 === t && be.isFile(e.node.mode)) - try { - n += Me.fstatSync(e.nfd).size - } catch (e) { - throw new be.ErrnoError(-e.errno) - } - if (n < 0) throw new be.ErrnoError(22) - return n - }, - }, - }, - _e = { - DIR_MODE: 16895, - FILE_MODE: 33279, - reader: null, - mount: function(e) { - E(u), _e.reader || (_e.reader = new FileReaderSync()) - var r = _e.createNode(null, '/', _e.DIR_MODE, 0), - t = {} - function n(e) { - for (var n = e.split('/'), o = r, i = 0; i < n.length - 1; i++) { - var a = n.slice(0, i + 1).join('/') - t[a] || (t[a] = _e.createNode(o, n[i], _e.DIR_MODE, 0)), (o = t[a]) - } - return o - } - function o(e) { - var r = e.split('/') - return r[r.length - 1] - } - return ( - Array.prototype.forEach.call(e.opts.files || [], function(e) { - _e.createNode( - n(e.name), - o(e.name), - _e.FILE_MODE, - 0, - e, - e.lastModifiedDate - ) - }), - (e.opts.blobs || []).forEach(function(e) { - _e.createNode(n(e.name), o(e.name), _e.FILE_MODE, 0, e.data) - }), - (e.opts.packages || []).forEach(function(e) { - e.metadata.files.forEach(function(r) { - var t = r.filename.substr(1) - _e.createNode( - n(t), - o(t), - _e.FILE_MODE, - 0, - e.blob.slice(r.start, r.end) - ) - }) - }), - r - ) - }, - createNode: function(e, r, t, n, o, i) { - var a = be.createNode(e, r, t) - return ( - (a.mode = t), - (a.node_ops = _e.node_ops), - (a.stream_ops = _e.stream_ops), - (a.timestamp = (i || new Date()).getTime()), - E(_e.FILE_MODE !== _e.DIR_MODE), - t === _e.FILE_MODE - ? ((a.size = o.size), (a.contents = o)) - : ((a.size = 4096), (a.contents = {})), - e && (e.contents[r] = a), - a - ) - }, - node_ops: { - getattr: function(e) { - return { - dev: 1, - ino: void 0, - mode: e.mode, - nlink: 1, - uid: 0, - gid: 0, - rdev: void 0, - size: e.size, - atime: new Date(e.timestamp), - mtime: new Date(e.timestamp), - ctime: new Date(e.timestamp), - blksize: 4096, - blocks: Math.ceil(e.size / 4096), - } - }, - setattr: function(e, r) { - void 0 !== r.mode && (e.mode = r.mode), - void 0 !== r.timestamp && (e.timestamp = r.timestamp) - }, - lookup: function(e, r) { - throw new be.ErrnoError(2) - }, - mknod: function(e, r, t, n) { - throw new be.ErrnoError(1) - }, - rename: function(e, r, t) { - throw new be.ErrnoError(1) - }, - unlink: function(e, r) { - throw new be.ErrnoError(1) - }, - rmdir: function(e, r) { - throw new be.ErrnoError(1) - }, - readdir: function(e) { - var r = ['.', '..'] - for (var t in e.contents) e.contents.hasOwnProperty(t) && r.push(t) - return r - }, - symlink: function(e, r, t) { - throw new be.ErrnoError(1) - }, - readlink: function(e) { - throw new be.ErrnoError(1) - }, - }, - stream_ops: { - read: function(e, r, t, n, o) { - if (o >= e.node.size) return 0 - var i = e.node.contents.slice(o, o + n), - a = _e.reader.readAsArrayBuffer(i) - return r.set(new Uint8Array(a), t), i.size - }, - write: function(e, r, t, n, o) { - throw new be.ErrnoError(5) - }, - llseek: function(e, r, t) { - var n = r - if ( - (1 === t - ? (n += e.position) - : 2 === t && be.isFile(e.node.mode) && (n += e.node.size), - n < 0) - ) - throw new be.ErrnoError(22) - return n - }, - }, - }, - be = { - root: null, - mounts: [], - devices: {}, - streams: [], - nextInode: 1, - nameTable: null, - currentPath: '/', - initialized: !1, - ignorePermissions: !0, - trackingDelegate: {}, - tracking: { openFlags: { READ: 1, WRITE: 2 } }, - ErrnoError: null, - genericErrors: {}, - filesystems: null, - syncFSRequests: 0, - handleFSError: function(e) { - if (!(e instanceof be.ErrnoError)) throw e + ' : ' + j() - return he(e.errno) - }, - lookupPath: function(e, r) { - if (((r = r || {}), !(e = ve.resolve(be.cwd(), e)))) - return { path: '', node: null } - var t = { follow_mount: !0, recurse_count: 0 } - for (var n in t) void 0 === r[n] && (r[n] = t[n]) - if (r.recurse_count > 8) throw new be.ErrnoError(40) - for ( - var o = me.normalizeArray( - e.split('/').filter(function(e) { - return !!e - }), - !1 - ), - i = be.root, - a = '/', - s = 0; - s < o.length; - s++ - ) { - var u = s === o.length - 1 - if (u && r.parent) break - if ( - ((i = be.lookupNode(i, o[s])), - (a = me.join2(a, o[s])), - be.isMountpoint(i) && - (!u || (u && r.follow_mount)) && - (i = i.mounted.root), - !u || r.follow) - ) - for (var c = 0; be.isLink(i.mode); ) { - var f = be.readlink(a) - if ( - ((a = ve.resolve(me.dirname(a), f)), - (i = be.lookupPath(a, { recurse_count: r.recurse_count }).node), - c++ > 40) - ) - throw new be.ErrnoError(40) - } - } - return { path: a, node: i } - }, - getPath: function(e) { - for (var r; ; ) { - if (be.isRoot(e)) { - var t = e.mount.mountpoint - return r ? ('/' !== t[t.length - 1] ? t + '/' + r : t + r) : t - } - ;(r = r ? e.name + '/' + r : e.name), (e = e.parent) - } - }, - hashName: function(e, r) { - for (var t = 0, n = 0; n < r.length; n++) - t = ((t << 5) - t + r.charCodeAt(n)) | 0 - return ((e + t) >>> 0) % be.nameTable.length - }, - hashAddNode: function(e) { - var r = be.hashName(e.parent.id, e.name) - ;(e.name_next = be.nameTable[r]), (be.nameTable[r] = e) - }, - hashRemoveNode: function(e) { - var r = be.hashName(e.parent.id, e.name) - if (be.nameTable[r] === e) be.nameTable[r] = e.name_next - else - for (var t = be.nameTable[r]; t; ) { - if (t.name_next === e) { - t.name_next = e.name_next - break - } - t = t.name_next - } - }, - lookupNode: function(e, r) { - var t = be.mayLookup(e) - if (t) throw new be.ErrnoError(t, e) - for ( - var n = be.hashName(e.id, r), o = be.nameTable[n]; - o; - o = o.name_next - ) { - var i = o.name - if (o.parent.id === e.id && i === r) return o - } - return be.lookup(e, r) - }, - createNode: function(e, r, t, n) { - be.FSNode || - ((be.FSNode = function(e, r, t, n) { - e || (e = this), - (this.parent = e), - (this.mount = e.mount), - (this.mounted = null), - (this.id = be.nextInode++), - (this.name = r), - (this.mode = t), - (this.node_ops = {}), - (this.stream_ops = {}), - (this.rdev = n) - }), - (be.FSNode.prototype = {}), - Object.defineProperties(be.FSNode.prototype, { - read: { - get: function() { - return 365 == (365 & this.mode) - }, - set: function(e) { - e ? (this.mode |= 365) : (this.mode &= -366) - }, - }, - write: { - get: function() { - return 146 == (146 & this.mode) - }, - set: function(e) { - e ? (this.mode |= 146) : (this.mode &= -147) - }, - }, - isFolder: { - get: function() { - return be.isDir(this.mode) - }, - }, - isDevice: { - get: function() { - return be.isChrdev(this.mode) - }, - }, - })) - var o = new be.FSNode(e, r, t, n) - return be.hashAddNode(o), o - }, - destroyNode: function(e) { - be.hashRemoveNode(e) - }, - isRoot: function(e) { - return e === e.parent - }, - isMountpoint: function(e) { - return !!e.mounted - }, - isFile: function(e) { - return 32768 == (61440 & e) - }, - isDir: function(e) { - return 16384 == (61440 & e) - }, - isLink: function(e) { - return 40960 == (61440 & e) - }, - isChrdev: function(e) { - return 8192 == (61440 & e) - }, - isBlkdev: function(e) { - return 24576 == (61440 & e) - }, - isFIFO: function(e) { - return 4096 == (61440 & e) - }, - isSocket: function(e) { - return 49152 == (49152 & e) - }, - flagModes: { - r: 0, - rs: 1052672, - 'r+': 2, - w: 577, - wx: 705, - xw: 705, - 'w+': 578, - 'wx+': 706, - 'xw+': 706, - a: 1089, - ax: 1217, - xa: 1217, - 'a+': 1090, - 'ax+': 1218, - 'xa+': 1218, - }, - modeStringToFlags: function(e) { - var r = be.flagModes[e] - if (void 0 === r) throw new Error('Unknown file open mode: ' + e) - return r - }, - flagsToPermissionString: function(e) { - var r = ['r', 'w', 'rw'][3 & e] - return 512 & e && (r += 'w'), r - }, - nodePermissions: function(e, r) { - return be.ignorePermissions - ? 0 - : (-1 === r.indexOf('r') || 292 & e.mode) && - (-1 === r.indexOf('w') || 146 & e.mode) && - (-1 === r.indexOf('x') || 73 & e.mode) - ? 0 - : 13 - }, - mayLookup: function(e) { - var r = be.nodePermissions(e, 'x') - return r || (e.node_ops.lookup ? 0 : 13) - }, - mayCreate: function(e, r) { - try { - return be.lookupNode(e, r), 17 - } catch (e) {} - return be.nodePermissions(e, 'wx') - }, - mayDelete: function(e, r, t) { - var n - try { - n = be.lookupNode(e, r) - } catch (e) { - return e.errno - } - var o = be.nodePermissions(e, 'wx') - if (o) return o - if (t) { - if (!be.isDir(n.mode)) return 20 - if (be.isRoot(n) || be.getPath(n) === be.cwd()) return 16 - } else if (be.isDir(n.mode)) return 21 - return 0 - }, - mayOpen: function(e, r) { - return e - ? be.isLink(e.mode) - ? 40 - : be.isDir(e.mode) && ('r' !== be.flagsToPermissionString(r) || 512 & r) - ? 21 - : be.nodePermissions(e, be.flagsToPermissionString(r)) - : 2 - }, - MAX_OPEN_FDS: 4096, - nextfd: function(e, r) { - ;(e = e || 0), (r = r || be.MAX_OPEN_FDS) - for (var t = e; t <= r; t++) if (!be.streams[t]) return t - throw new be.ErrnoError(24) - }, - getStream: function(e) { - return be.streams[e] - }, - createStream: function(e, r, t) { - be.FSStream || - ((be.FSStream = function() {}), - (be.FSStream.prototype = {}), - Object.defineProperties(be.FSStream.prototype, { - object: { - get: function() { - return this.node - }, - set: function(e) { - this.node = e - }, - }, - isRead: { - get: function() { - return 1 != (2097155 & this.flags) - }, - }, - isWrite: { - get: function() { - return 0 != (2097155 & this.flags) - }, - }, - isAppend: { - get: function() { - return 1024 & this.flags - }, - }, - })) - var n = new be.FSStream() - for (var o in e) n[o] = e[o] - e = n - var i = be.nextfd(r, t) - return (e.fd = i), (be.streams[i] = e), e - }, - closeStream: function(e) { - be.streams[e] = null - }, - chrdev_stream_ops: { - open: function(e) { - var r = be.getDevice(e.node.rdev) - ;(e.stream_ops = r.stream_ops), e.stream_ops.open && e.stream_ops.open(e) - }, - llseek: function() { - throw new be.ErrnoError(29) - }, - }, - major: function(e) { - return e >> 8 - }, - minor: function(e) { - return 255 & e - }, - makedev: function(e, r) { - return (e << 8) | r - }, - registerDevice: function(e, r) { - be.devices[e] = { stream_ops: r } - }, - getDevice: function(e) { - return be.devices[e] - }, - getMounts: function(e) { - for (var r = [], t = [e]; t.length; ) { - var n = t.pop() - r.push(n), t.push.apply(t, n.mounts) - } - return r - }, - syncfs: function(e, r) { - 'function' == typeof e && ((r = e), (e = !1)), - be.syncFSRequests++, - be.syncFSRequests > 1 && - console.log( - 'warning: ' + - be.syncFSRequests + - ' FS.syncfs operations in flight at once, probably just doing extra work' - ) - var t = be.getMounts(be.root.mount), - n = 0 - function o(e) { - return be.syncFSRequests--, r(e) - } - function i(e) { - if (e) return i.errored ? void 0 : ((i.errored = !0), o(e)) - ++n >= t.length && o(null) - } - t.forEach(function(r) { - if (!r.type.syncfs) return i(null) - r.type.syncfs(r, e, i) - }) - }, - mount: function(e, r, t) { - var n, - o = '/' === t, - i = !t - if (o && be.root) throw new be.ErrnoError(16) - if (!o && !i) { - var a = be.lookupPath(t, { follow_mount: !1 }) - if (((t = a.path), (n = a.node), be.isMountpoint(n))) - throw new be.ErrnoError(16) - if (!be.isDir(n.mode)) throw new be.ErrnoError(20) - } - var s = { type: e, opts: r, mountpoint: t, mounts: [] }, - u = e.mount(s) - return ( - (u.mount = s), - (s.root = u), - o - ? (be.root = u) - : n && ((n.mounted = s), n.mount && n.mount.mounts.push(s)), - u - ) - }, - unmount: function(e) { - var r = be.lookupPath(e, { follow_mount: !1 }) - if (!be.isMountpoint(r.node)) throw new be.ErrnoError(22) - var t = r.node, - n = t.mounted, - o = be.getMounts(n) - Object.keys(be.nameTable).forEach(function(e) { - for (var r = be.nameTable[e]; r; ) { - var t = r.name_next - ;-1 !== o.indexOf(r.mount) && be.destroyNode(r), (r = t) - } - }), - (t.mounted = null) - var i = t.mount.mounts.indexOf(n) - t.mount.mounts.splice(i, 1) - }, - lookup: function(e, r) { - return e.node_ops.lookup(e, r) - }, - mknod: function(e, r, t) { - var n = be.lookupPath(e, { parent: !0 }).node, - o = me.basename(e) - if (!o || '.' === o || '..' === o) throw new be.ErrnoError(22) - var i = be.mayCreate(n, o) - if (i) throw new be.ErrnoError(i) - if (!n.node_ops.mknod) throw new be.ErrnoError(1) - return n.node_ops.mknod(n, o, r, t) - }, - create: function(e, r) { - return ( - (r = void 0 !== r ? r : 438), (r &= 4095), (r |= 32768), be.mknod(e, r, 0) - ) - }, - mkdir: function(e, r) { - return ( - (r = void 0 !== r ? r : 511), (r &= 1023), (r |= 16384), be.mknod(e, r, 0) - ) - }, - mkdirTree: function(e, r) { - for (var t = e.split('/'), n = '', o = 0; o < t.length; ++o) - if (t[o]) { - n += '/' + t[o] - try { - be.mkdir(n, r) - } catch (e) { - if (17 != e.errno) throw e - } - } - }, - mkdev: function(e, r, t) { - return void 0 === t && ((t = r), (r = 438)), (r |= 8192), be.mknod(e, r, t) - }, - symlink: function(e, r) { - if (!ve.resolve(e)) throw new be.ErrnoError(2) - var t = be.lookupPath(r, { parent: !0 }).node - if (!t) throw new be.ErrnoError(2) - var n = me.basename(r), - o = be.mayCreate(t, n) - if (o) throw new be.ErrnoError(o) - if (!t.node_ops.symlink) throw new be.ErrnoError(1) - return t.node_ops.symlink(t, n, e) - }, - rename: function(e, r) { - var t, - n, - o = me.dirname(e), - i = me.dirname(r), - a = me.basename(e), - s = me.basename(r) - try { - ;(t = be.lookupPath(e, { parent: !0 }).node), - (n = be.lookupPath(r, { parent: !0 }).node) - } catch (e) { - throw new be.ErrnoError(16) - } - if (!t || !n) throw new be.ErrnoError(2) - if (t.mount !== n.mount) throw new be.ErrnoError(18) - var u, - c = be.lookupNode(t, a), - f = ve.relative(e, i) - if ('.' !== f.charAt(0)) throw new be.ErrnoError(22) - if ('.' !== (f = ve.relative(r, o)).charAt(0)) throw new be.ErrnoError(39) - try { - u = be.lookupNode(n, s) - } catch (e) {} - if (c !== u) { - var l = be.isDir(c.mode), - d = be.mayDelete(t, a, l) - if (d) throw new be.ErrnoError(d) - if ((d = u ? be.mayDelete(n, s, l) : be.mayCreate(n, s))) - throw new be.ErrnoError(d) - if (!t.node_ops.rename) throw new be.ErrnoError(1) - if (be.isMountpoint(c) || (u && be.isMountpoint(u))) - throw new be.ErrnoError(16) - if (n !== t && (d = be.nodePermissions(t, 'w'))) - throw new be.ErrnoError(d) - be.hashRemoveNode(c) - try { - t.node_ops.rename(c, n, s) - } catch (e) { - throw e - } finally { - be.hashAddNode(c) - } - } - }, - rmdir: function(e) { - var r = be.lookupPath(e, { parent: !0 }).node, - t = me.basename(e), - n = be.lookupNode(r, t), - o = be.mayDelete(r, t, !0) - if (o) throw new be.ErrnoError(o) - if (!r.node_ops.rmdir) throw new be.ErrnoError(1) - if (be.isMountpoint(n)) throw new be.ErrnoError(16) - r.node_ops.rmdir(r, t), be.destroyNode(n) - }, - readdir: function(e) { - var r = be.lookupPath(e, { follow: !0 }).node - if (!r.node_ops.readdir) throw new be.ErrnoError(20) - return r.node_ops.readdir(r) - }, - unlink: function(e) { - var r = be.lookupPath(e, { parent: !0 }).node, - t = me.basename(e), - n = be.lookupNode(r, t), - o = be.mayDelete(r, t, !1) - if (o) throw new be.ErrnoError(o) - if (!r.node_ops.unlink) throw new be.ErrnoError(1) - if (be.isMountpoint(n)) throw new be.ErrnoError(16) - r.node_ops.unlink(r, t), be.destroyNode(n) - }, - readlink: function(e) { - var r = be.lookupPath(e).node - if (!r) throw new be.ErrnoError(2) - if (!r.node_ops.readlink) throw new be.ErrnoError(22) - return ve.resolve(be.getPath(r.parent), r.node_ops.readlink(r)) - }, - stat: function(e, r) { - var t = be.lookupPath(e, { follow: !r }).node - if (!t) throw new be.ErrnoError(2) - if (!t.node_ops.getattr) throw new be.ErrnoError(1) - return t.node_ops.getattr(t) - }, - lstat: function(e) { - return be.stat(e, !0) - }, - chmod: function(e, r, t) { - var n - if ( - !(n = 'string' == typeof e ? be.lookupPath(e, { follow: !t }).node : e) - .node_ops.setattr - ) - throw new be.ErrnoError(1) - n.node_ops.setattr(n, { - mode: (4095 & r) | (-4096 & n.mode), - timestamp: Date.now(), - }) - }, - lchmod: function(e, r) { - be.chmod(e, r, !0) - }, - fchmod: function(e, r) { - var t = be.getStream(e) - if (!t) throw new be.ErrnoError(9) - be.chmod(t.node, r) - }, - chown: function(e, r, t, n) { - var o - if ( - !(o = 'string' == typeof e ? be.lookupPath(e, { follow: !n }).node : e) - .node_ops.setattr - ) - throw new be.ErrnoError(1) - o.node_ops.setattr(o, { timestamp: Date.now() }) - }, - lchown: function(e, r, t) { - be.chown(e, r, t, !0) - }, - fchown: function(e, r, t) { - var n = be.getStream(e) - if (!n) throw new be.ErrnoError(9) - be.chown(n.node, r, t) - }, - truncate: function(e, r) { - if (r < 0) throw new be.ErrnoError(22) - var t - if ( - !(t = 'string' == typeof e ? be.lookupPath(e, { follow: !0 }).node : e) - .node_ops.setattr - ) - throw new be.ErrnoError(1) - if (be.isDir(t.mode)) throw new be.ErrnoError(21) - if (!be.isFile(t.mode)) throw new be.ErrnoError(22) - var n = be.nodePermissions(t, 'w') - if (n) throw new be.ErrnoError(n) - t.node_ops.setattr(t, { size: r, timestamp: Date.now() }) - }, - ftruncate: function(e, r) { - var t = be.getStream(e) - if (!t) throw new be.ErrnoError(9) - if (0 == (2097155 & t.flags)) throw new be.ErrnoError(22) - be.truncate(t.node, r) - }, - utime: function(e, r, t) { - var n = be.lookupPath(e, { follow: !0 }).node - n.node_ops.setattr(n, { timestamp: Math.max(r, t) }) - }, - open: function(e, r, t, o, i) { - if ('' === e) throw new be.ErrnoError(2) - var a - if ( - ((t = void 0 === t ? 438 : t), - (t = - 64 & (r = 'string' == typeof r ? be.modeStringToFlags(r) : r) - ? (4095 & t) | 32768 - : 0), - 'object' == typeof e) - ) - a = e - else { - e = me.normalize(e) - try { - a = be.lookupPath(e, { follow: !(131072 & r) }).node - } catch (e) {} - } - var s = !1 - if (64 & r) - if (a) { - if (128 & r) throw new be.ErrnoError(17) - } else (a = be.mknod(e, t, 0)), (s = !0) - if (!a) throw new be.ErrnoError(2) - if ((be.isChrdev(a.mode) && (r &= -513), 65536 & r && !be.isDir(a.mode))) - throw new be.ErrnoError(20) - if (!s) { - var u = be.mayOpen(a, r) - if (u) throw new be.ErrnoError(u) - } - 512 & r && be.truncate(a, 0), (r &= -641) - var c = be.createStream( - { - node: a, - path: be.getPath(a), - flags: r, - seekable: !0, - position: 0, - stream_ops: a.stream_ops, - ungotten: [], - error: !1, - }, - o, - i - ) - return ( - c.stream_ops.open && c.stream_ops.open(c), - !n.logReadFiles || - 1 & r || - (be.readFiles || (be.readFiles = {}), - e in be.readFiles || - ((be.readFiles[e] = 1), - console.log('FS.trackingDelegate error on read file: ' + e))), - c - ) - }, - close: function(e) { - if (be.isClosed(e)) throw new be.ErrnoError(9) - e.getdents && (e.getdents = null) - try { - e.stream_ops.close && e.stream_ops.close(e) - } catch (e) { - throw e - } finally { - be.closeStream(e.fd) - } - e.fd = null - }, - isClosed: function(e) { - return null === e.fd - }, - llseek: function(e, r, t) { - if (be.isClosed(e)) throw new be.ErrnoError(9) - if (!e.seekable || !e.stream_ops.llseek) throw new be.ErrnoError(29) - if (0 != t && 1 != t && 2 != t) throw new be.ErrnoError(22) - return ( - (e.position = e.stream_ops.llseek(e, r, t)), (e.ungotten = []), e.position - ) - }, - read: function(e, r, t, n, o) { - if (n < 0 || o < 0) throw new be.ErrnoError(22) - if (be.isClosed(e)) throw new be.ErrnoError(9) - if (1 == (2097155 & e.flags)) throw new be.ErrnoError(9) - if (be.isDir(e.node.mode)) throw new be.ErrnoError(21) - if (!e.stream_ops.read) throw new be.ErrnoError(22) - var i = void 0 !== o - if (i) { - if (!e.seekable) throw new be.ErrnoError(29) - } else o = e.position - var a = e.stream_ops.read(e, r, t, n, o) - return i || (e.position += a), a - }, - write: function(e, r, t, n, o, i) { - if (n < 0 || o < 0) throw new be.ErrnoError(22) - if (be.isClosed(e)) throw new be.ErrnoError(9) - if (0 == (2097155 & e.flags)) throw new be.ErrnoError(9) - if (be.isDir(e.node.mode)) throw new be.ErrnoError(21) - if (!e.stream_ops.write) throw new be.ErrnoError(22) - 1024 & e.flags && be.llseek(e, 0, 2) - var a = void 0 !== o - if (a) { - if (!e.seekable) throw new be.ErrnoError(29) - } else o = e.position - var s = e.stream_ops.write(e, r, t, n, o, i) - a || (e.position += s) - try { - e.path && - be.trackingDelegate.onWriteToFile && - be.trackingDelegate.onWriteToFile(e.path) - } catch (r) { - console.log( - "FS.trackingDelegate['onWriteToFile']('" + - e.path + - "') threw an exception: " + - r.message - ) - } - return s - }, - allocate: function(e, r, t) { - if (be.isClosed(e)) throw new be.ErrnoError(9) - if (r < 0 || t <= 0) throw new be.ErrnoError(22) - if (0 == (2097155 & e.flags)) throw new be.ErrnoError(9) - if (!be.isFile(e.node.mode) && !be.isDir(e.node.mode)) - throw new be.ErrnoError(19) - if (!e.stream_ops.allocate) throw new be.ErrnoError(95) - e.stream_ops.allocate(e, r, t) - }, - mmap: function(e, r, t, n, o, i, a) { - if (1 == (2097155 & e.flags)) throw new be.ErrnoError(13) - if (!e.stream_ops.mmap) throw new be.ErrnoError(19) - return e.stream_ops.mmap(e, r, t, n, o, i, a) - }, - msync: function(e, r, t, n, o) { - return e && e.stream_ops.msync ? e.stream_ops.msync(e, r, t, n, o) : 0 - }, - munmap: function(e) { - return 0 - }, - ioctl: function(e, r, t) { - if (!e.stream_ops.ioctl) throw new be.ErrnoError(25) - return e.stream_ops.ioctl(e, r, t) - }, - readFile: function(e, r) { - if ( - (((r = r || {}).flags = r.flags || 'r'), - (r.encoding = r.encoding || 'binary'), - 'utf8' !== r.encoding && 'binary' !== r.encoding) - ) - throw new Error('Invalid encoding type "' + r.encoding + '"') - var t, - n = be.open(e, r.flags), - o = be.stat(e).size, - i = new Uint8Array(o) - return ( - be.read(n, i, 0, o, 0), - 'utf8' === r.encoding - ? (t = x(i, 0)) - : 'binary' === r.encoding && (t = i), - be.close(n), - t - ) - }, - writeFile: function(e, r, t) { - ;(t = t || {}).flags = t.flags || 'w' - var n = be.open(e, t.flags, t.mode) - if ('string' == typeof r) { - var o = new Uint8Array(L(r) + 1), - i = z(r, o, 0, o.length) - be.write(n, o, 0, i, void 0, t.canOwn) - } else { - if (!ArrayBuffer.isView(r)) throw new Error('Unsupported data type') - be.write(n, r, 0, r.byteLength, void 0, t.canOwn) - } - be.close(n) - }, - cwd: function() { - return be.currentPath - }, - chdir: function(e) { - var r = be.lookupPath(e, { follow: !0 }) - if (null === r.node) throw new be.ErrnoError(2) - if (!be.isDir(r.node.mode)) throw new be.ErrnoError(20) - var t = be.nodePermissions(r.node, 'x') - if (t) throw new be.ErrnoError(t) - be.currentPath = r.path - }, - createDefaultDirectories: function() { - be.mkdir('/tmp'), be.mkdir('/home'), be.mkdir('/home/web_user') - }, - createDefaultDevices: function() { - var e - if ( - (be.mkdir('/dev'), - be.registerDevice(be.makedev(1, 3), { - read: function() { - return 0 - }, - write: function(e, r, t, n, o) { - return n - }, - }), - be.mkdev('/dev/null', be.makedev(1, 3)), - we.register(be.makedev(5, 0), we.default_tty_ops), - we.register(be.makedev(6, 0), we.default_tty1_ops), - be.mkdev('/dev/tty', be.makedev(5, 0)), - be.mkdev('/dev/tty1', be.makedev(6, 0)), - 'object' == typeof crypto && 'function' == typeof crypto.getRandomValues) - ) { - var r = new Uint8Array(1) - e = function() { - return crypto.getRandomValues(r), r[0] - } - } else if (i) - try { - var t = require('crypto') - e = function() { - return t.randomBytes(1)[0] - } - } catch (e) {} - e || - (e = function() { - Ze('random_device') - }), - be.createDevice('/dev', 'random', e), - be.createDevice('/dev', 'urandom', e), - be.mkdir('/dev/shm'), - be.mkdir('/dev/shm/tmp') - }, - createSpecialDirectories: function() { - be.mkdir('/proc'), - be.mkdir('/proc/self'), - be.mkdir('/proc/self/fd'), - be.mount( - { - mount: function() { - var e = be.createNode('/proc/self', 'fd', 16895, 73) - return ( - (e.node_ops = { - lookup: function(e, r) { - var t = +r, - n = be.getStream(t) - if (!n) throw new be.ErrnoError(9) - var o = { - parent: null, - mount: { mountpoint: 'fake' }, - node_ops: { - readlink: function() { - return n.path - }, - }, - } - return (o.parent = o), o - }, - }), - e - ) - }, - }, - {}, - '/proc/self/fd' - ) - }, - createStandardStreams: function() { - n.stdin - ? be.createDevice('/dev', 'stdin', n.stdin) - : be.symlink('/dev/tty', '/dev/stdin'), - n.stdout - ? be.createDevice('/dev', 'stdout', null, n.stdout) - : be.symlink('/dev/tty', '/dev/stdout'), - n.stderr - ? be.createDevice('/dev', 'stderr', null, n.stderr) - : be.symlink('/dev/tty1', '/dev/stderr'), - be.open('/dev/stdin', 'r'), - be.open('/dev/stdout', 'w'), - be.open('/dev/stderr', 'w') - }, - ensureErrnoError: function() { - be.ErrnoError || - ((be.ErrnoError = function(e, r) { - ;(this.node = r), - (this.setErrno = function(e) { - this.errno = e - }), - this.setErrno(e), - (this.message = 'FS error'), - this.stack && - Object.defineProperty(this, 'stack', { - value: new Error().stack, - writable: !0, - }) - }), - (be.ErrnoError.prototype = new Error()), - (be.ErrnoError.prototype.constructor = be.ErrnoError), - [2].forEach(function(e) { - ;(be.genericErrors[e] = new be.ErrnoError(e)), - (be.genericErrors[e].stack = '') - })) - }, - staticInit: function() { - be.ensureErrnoError(), - (be.nameTable = new Array(4096)), - be.mount(ye, {}, '/'), - be.createDefaultDirectories(), - be.createDefaultDevices(), - be.createSpecialDirectories(), - (be.filesystems = { MEMFS: ye, IDBFS: Ee, NODEFS: ge, WORKERFS: _e }) - }, - init: function(e, r, t) { - ;(be.init.initialized = !0), - be.ensureErrnoError(), - (n.stdin = e || n.stdin), - (n.stdout = r || n.stdout), - (n.stderr = t || n.stderr), - be.createStandardStreams() - }, - quit: function() { - be.init.initialized = !1 - var e = n._fflush - e && e(0) - for (var r = 0; r < be.streams.length; r++) { - var t = be.streams[r] - t && be.close(t) - } - }, - getMode: function(e, r) { - var t = 0 - return e && (t |= 365), r && (t |= 146), t - }, - joinPath: function(e, r) { - var t = me.join.apply(null, e) - return r && '/' == t[0] && (t = t.substr(1)), t - }, - absolutePath: function(e, r) { - return ve.resolve(r, e) - }, - standardizePath: function(e) { - return me.normalize(e) - }, - findObject: function(e, r) { - var t = be.analyzePath(e, r) - return t.exists ? t.object : (he(t.error), null) - }, - analyzePath: function(e, r) { - try { - e = (n = be.lookupPath(e, { follow: !r })).path - } catch (e) {} - var t = { - isRoot: !1, - exists: !1, - error: 0, - name: null, - path: null, - object: null, - parentExists: !1, - parentPath: null, - parentObject: null, - } - try { - var n = be.lookupPath(e, { parent: !0 }) - ;(t.parentExists = !0), - (t.parentPath = n.path), - (t.parentObject = n.node), - (t.name = me.basename(e)), - (n = be.lookupPath(e, { follow: !r })), - (t.exists = !0), - (t.path = n.path), - (t.object = n.node), - (t.name = n.node.name), - (t.isRoot = '/' === n.path) - } catch (e) { - t.error = e.errno - } - return t - }, - createFolder: function(e, r, t, n) { - var o = me.join2('string' == typeof e ? e : be.getPath(e), r), - i = be.getMode(t, n) - return be.mkdir(o, i) - }, - createPath: function(e, r, t, n) { - e = 'string' == typeof e ? e : be.getPath(e) - for (var o = r.split('/').reverse(); o.length; ) { - var i = o.pop() - if (i) { - var a = me.join2(e, i) - try { - be.mkdir(a) - } catch (e) {} - e = a - } - } - return a - }, - createFile: function(e, r, t, n, o) { - var i = me.join2('string' == typeof e ? e : be.getPath(e), r), - a = be.getMode(n, o) - return be.create(i, a) - }, - createDataFile: function(e, r, t, n, o, i) { - var a = r ? me.join2('string' == typeof e ? e : be.getPath(e), r) : e, - s = be.getMode(n, o), - u = be.create(a, s) - if (t) { - if ('string' == typeof t) { - for (var c = new Array(t.length), f = 0, l = t.length; f < l; ++f) - c[f] = t.charCodeAt(f) - t = c - } - be.chmod(u, 146 | s) - var d = be.open(u, 'w') - be.write(d, t, 0, t.length, 0, i), be.close(d), be.chmod(u, s) - } - return u - }, - createDevice: function(e, r, t, n) { - var o = me.join2('string' == typeof e ? e : be.getPath(e), r), - i = be.getMode(!!t, !!n) - be.createDevice.major || (be.createDevice.major = 64) - var a = be.makedev(be.createDevice.major++, 0) - return ( - be.registerDevice(a, { - open: function(e) { - e.seekable = !1 - }, - close: function(e) { - n && n.buffer && n.buffer.length && n(10) - }, - read: function(e, r, n, o, i) { - for (var a = 0, s = 0; s < o; s++) { - var u - try { - u = t() - } catch (e) { - throw new be.ErrnoError(5) - } - if (void 0 === u && 0 === a) throw new be.ErrnoError(11) - if (null == u) break - a++, (r[n + s] = u) - } - return a && (e.node.timestamp = Date.now()), a - }, - write: function(e, r, t, o, i) { - for (var a = 0; a < o; a++) - try { - n(r[t + a]) - } catch (e) { - throw new be.ErrnoError(5) - } - return o && (e.node.timestamp = Date.now()), a - }, - }), - be.mkdev(o, i, a) - ) - }, - createLink: function(e, r, t, n, o) { - var i = me.join2('string' == typeof e ? e : be.getPath(e), r) - return be.symlink(t, i) - }, - forceLoadFile: function(e) { - if (e.isDevice || e.isFolder || e.link || e.contents) return !0 - var r = !0 - if ('undefined' != typeof XMLHttpRequest) - throw new Error( - '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.' - ) - if (!n.read) - throw new Error('Cannot load without read() or XMLHttpRequest.') - try { - ;(e.contents = Ne(n.read(e.url), !0)), (e.usedBytes = e.contents.length) - } catch (e) { - r = !1 - } - return r || he(5), r - }, - createLazyFile: function(e, r, t, n, o) { - function i() { - ;(this.lengthKnown = !1), (this.chunks = []) - } - if ( - ((i.prototype.get = function(e) { - if (!(e > this.length - 1 || e < 0)) { - var r = e % this.chunkSize, - t = (e / this.chunkSize) | 0 - return this.getter(t)[r] - } - }), - (i.prototype.setDataGetter = function(e) { - this.getter = e - }), - (i.prototype.cacheLength = function() { - var e = new XMLHttpRequest() - if ( - (e.open('HEAD', t, !1), - e.send(null), - !((e.status >= 200 && e.status < 300) || 304 === e.status)) - ) - throw new Error("Couldn't load " + t + '. Status: ' + e.status) - var r, - n = Number(e.getResponseHeader('Content-length')), - o = (r = e.getResponseHeader('Accept-Ranges')) && 'bytes' === r, - i = (r = e.getResponseHeader('Content-Encoding')) && 'gzip' === r, - a = 1048576 - o || (a = n) - var s = this - s.setDataGetter(function(e) { - var r = e * a, - o = (e + 1) * a - 1 - if ( - ((o = Math.min(o, n - 1)), - void 0 === s.chunks[e] && - (s.chunks[e] = (function(e, r) { - if (e > r) - throw new Error( - 'invalid range (' + - e + - ', ' + - r + - ') or no bytes requested!' - ) - if (r > n - 1) - throw new Error( - 'only ' + n + ' bytes available! programmer error!' - ) - var o = new XMLHttpRequest() - if ( - (o.open('GET', t, !1), - n !== a && - o.setRequestHeader('Range', 'bytes=' + e + '-' + r), - 'undefined' != typeof Uint8Array && - (o.responseType = 'arraybuffer'), - o.overrideMimeType && - o.overrideMimeType('text/plain; charset=x-user-defined'), - o.send(null), - !((o.status >= 200 && o.status < 300) || 304 === o.status)) - ) - throw new Error( - "Couldn't load " + t + '. Status: ' + o.status - ) - return void 0 !== o.response - ? new Uint8Array(o.response || []) - : Ne(o.responseText || '', !0) - })(r, o)), - void 0 === s.chunks[e]) - ) - throw new Error('doXHR failed!') - return s.chunks[e] - }), - (!i && n) || - ((a = n = 1), - (n = this.getter(0).length), - (a = n), - console.log( - 'LazyFiles on gzip forces download of the whole file when length is accessed' - )), - (this._length = n), - (this._chunkSize = a), - (this.lengthKnown = !0) - }), - 'undefined' != typeof XMLHttpRequest) - ) { - if (!u) - throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc' - var a = new i() - Object.defineProperties(a, { - length: { - get: function() { - return this.lengthKnown || this.cacheLength(), this._length - }, - }, - chunkSize: { - get: function() { - return this.lengthKnown || this.cacheLength(), this._chunkSize - }, - }, - }) - var s = { isDevice: !1, contents: a } - } else s = { isDevice: !1, url: t } - var c = be.createFile(e, r, s, n, o) - s.contents - ? (c.contents = s.contents) - : s.url && ((c.contents = null), (c.url = s.url)), - Object.defineProperties(c, { - usedBytes: { - get: function() { - return this.contents.length - }, - }, - }) - var f = {} - return ( - Object.keys(c.stream_ops).forEach(function(e) { - var r = c.stream_ops[e] - f[e] = function() { - if (!be.forceLoadFile(c)) throw new be.ErrnoError(5) - return r.apply(null, arguments) - } - }), - (f.read = function(e, r, t, n, o) { - if (!be.forceLoadFile(c)) throw new be.ErrnoError(5) - var i = e.node.contents - if (o >= i.length) return 0 - var a = Math.min(i.length - o, n) - if (i.slice) for (var s = 0; s < a; s++) r[t + s] = i[o + s] - else for (s = 0; s < a; s++) r[t + s] = i.get(o + s) - return a - }), - (c.stream_ops = f), - c - ) - }, - createPreloadedFile: function(e, r, t, o, i, a, s, u, c, f) { - Browser.init() - var l = r ? ve.resolve(me.join2(e, r)) : e - function d(t) { - function d(t) { - f && f(), u || be.createDataFile(e, r, t, o, i, c), a && a(), ae() - } - var p = !1 - n.preloadPlugins.forEach(function(e) { - p || - (e.canHandle(l) && - (e.handle(t, l, d, function() { - s && s(), ae() - }), - (p = !0))) - }), - p || d(t) - } - ie(), - 'string' == typeof t - ? Browser.asyncLoad( - t, - function(e) { - d(e) - }, - s - ) - : d(t) - }, - indexedDB: function() { - return ( - window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB - ) - }, - DB_NAME: function() { - return 'EM_FS_' + window.location.pathname - }, - DB_VERSION: 20, - DB_STORE_NAME: 'FILE_DATA', - saveFilesToDB: function(e, r, t) { - ;(r = r || function() {}), (t = t || function() {}) - var n = be.indexedDB() - try { - var o = n.open(be.DB_NAME(), be.DB_VERSION) - } catch (e) { - return t(e) - } - ;(o.onupgradeneeded = function() { - console.log('creating db'), o.result.createObjectStore(be.DB_STORE_NAME) - }), - (o.onsuccess = function() { - var n = o.result.transaction([be.DB_STORE_NAME], 'readwrite'), - i = n.objectStore(be.DB_STORE_NAME), - a = 0, - s = 0, - u = e.length - function c() { - 0 == s ? r() : t() - } - e.forEach(function(e) { - var r = i.put(be.analyzePath(e).object.contents, e) - ;(r.onsuccess = function() { - ++a + s == u && c() - }), - (r.onerror = function() { - a + ++s == u && c() - }) - }), - (n.onerror = t) - }), - (o.onerror = t) - }, - loadFilesFromDB: function(e, r, t) { - ;(r = r || function() {}), (t = t || function() {}) - var n = be.indexedDB() - try { - var o = n.open(be.DB_NAME(), be.DB_VERSION) - } catch (e) { - return t(e) - } - ;(o.onupgradeneeded = t), - (o.onsuccess = function() { - var n = o.result - try { - var i = n.transaction([be.DB_STORE_NAME], 'readonly') - } catch (e) { - return void t(e) - } - var a = i.objectStore(be.DB_STORE_NAME), - s = 0, - u = 0, - c = e.length - function f() { - 0 == u ? r() : t() - } - e.forEach(function(e) { - var r = a.get(e) - ;(r.onsuccess = function() { - be.analyzePath(e).exists && be.unlink(e), - be.createDataFile( - me.dirname(e), - me.basename(e), - r.result, - !0, - !0, - !0 - ), - ++s + u == c && f() - }), - (r.onerror = function() { - s + ++u == c && f() - }) - }), - (i.onerror = t) - }), - (o.onerror = t) - }, - }, - ke = { - DEFAULT_POLLMASK: 5, - mappings: {}, - umask: 511, - calculateAt: function(e, r) { - if ('/' !== r[0]) { - var t - if (-100 === e) t = be.cwd() - else { - var n = be.getStream(e) - if (!n) throw new be.ErrnoError(9) - t = n.path - } - r = me.join2(t, r) - } - return r - }, - doStat: function(e, r, t) { - try { - var n = e(r) - } catch (e) { - if (e && e.node && me.normalize(r) !== me.normalize(be.getPath(e.node))) - return -20 - throw e - } - return ( - (M[t >> 2] = n.dev), - (M[(t + 4) >> 2] = 0), - (M[(t + 8) >> 2] = n.ino), - (M[(t + 12) >> 2] = n.mode), - (M[(t + 16) >> 2] = n.nlink), - (M[(t + 20) >> 2] = n.uid), - (M[(t + 24) >> 2] = n.gid), - (M[(t + 28) >> 2] = n.rdev), - (M[(t + 32) >> 2] = 0), - (tempI64 = [ - n.size >>> 0, - ((tempDouble = n.size), - +J(tempDouble) >= 1 - ? tempDouble > 0 - ? (0 | re(+ee(tempDouble / 4294967296), 4294967295)) >>> 0 - : ~~+Q((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (M[(t + 40) >> 2] = tempI64[0]), - (M[(t + 44) >> 2] = tempI64[1]), - (M[(t + 48) >> 2] = 4096), - (M[(t + 52) >> 2] = n.blocks), - (M[(t + 56) >> 2] = (n.atime.getTime() / 1e3) | 0), - (M[(t + 60) >> 2] = 0), - (M[(t + 64) >> 2] = (n.mtime.getTime() / 1e3) | 0), - (M[(t + 68) >> 2] = 0), - (M[(t + 72) >> 2] = (n.ctime.getTime() / 1e3) | 0), - (M[(t + 76) >> 2] = 0), - (tempI64 = [ - n.ino >>> 0, - ((tempDouble = n.ino), - +J(tempDouble) >= 1 - ? tempDouble > 0 - ? (0 | re(+ee(tempDouble / 4294967296), 4294967295)) >>> 0 - : ~~+Q((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (M[(t + 80) >> 2] = tempI64[0]), - (M[(t + 84) >> 2] = tempI64[1]), - 0 - ) - }, - doMsync: function(e, r, t, n) { - var o = new Uint8Array(T.subarray(e, e + t)) - be.msync(r, o, 0, t, n) - }, - doMkdir: function(e, r) { - return ( - '/' === (e = me.normalize(e))[e.length - 1] && - (e = e.substr(0, e.length - 1)), - be.mkdir(e, r, 0), - 0 - ) - }, - doMknod: function(e, r, t) { - switch (61440 & r) { - case 32768: - case 8192: - case 24576: - case 4096: - case 49152: - break - default: - return -22 - } - return be.mknod(e, r, t), 0 - }, - doReadlink: function(e, r, t) { - if (t <= 0) return -22 - var n = be.readlink(e), - o = Math.min(t, L(n)), - i = R[r + o] - return C(n, r, t + 1), (R[r + o] = i), o - }, - doAccess: function(e, r) { - if (-8 & r) return -22 - var t - t = be.lookupPath(e, { follow: !0 }).node - var n = '' - return ( - 4 & r && (n += 'r'), - 2 & r && (n += 'w'), - 1 & r && (n += 'x'), - n && be.nodePermissions(t, n) ? -13 : 0 - ) - }, - doDup: function(e, r, t) { - var n = be.getStream(t) - return n && be.close(n), be.open(e, r, 0, t, t).fd - }, - doReadv: function(e, r, t, n) { - for (var o = 0, i = 0; i < t; i++) { - var a = M[(r + 8 * i) >> 2], - s = M[(r + (8 * i + 4)) >> 2], - u = be.read(e, R, a, s, n) - if (u < 0) return -1 - if (((o += u), u < s)) break - } - return o - }, - doWritev: function(e, r, t, n) { - for (var o = 0, i = 0; i < t; i++) { - var a = M[(r + 8 * i) >> 2], - s = M[(r + (8 * i + 4)) >> 2], - u = be.write(e, R, a, s, n) - if (u < 0) return -1 - o += u - } - return o - }, - varargs: 0, - get: function(e) { - return (ke.varargs += 4), M[(ke.varargs - 4) >> 2] - }, - getStr: function() { - return I(ke.get()) - }, - getStreamFromFD: function() { - var e = be.getStream(ke.get()) - if (!e) throw new be.ErrnoError(9) - return e - }, - get64: function() { - var e = ke.get() - return ke.get(), e - }, - getZero: function() { - ke.get() - }, - }, - De = 11, - Se = 22, - Fe = { - BUCKET_BUFFER_SIZE: 8192, - mount: function(e) { - return be.createNode(null, '/', 16895, 0) - }, - createPipe: function() { - var e = { buckets: [] } - e.buckets.push({ - buffer: new Uint8Array(Fe.BUCKET_BUFFER_SIZE), - offset: 0, - roffset: 0, - }) - var r = Fe.nextname(), - t = Fe.nextname(), - n = be.createNode(Fe.root, r, 4096, 0), - o = be.createNode(Fe.root, t, 4096, 0) - ;(n.pipe = e), (o.pipe = e) - var i = be.createStream({ - path: r, - node: n, - flags: be.modeStringToFlags('r'), - seekable: !1, - stream_ops: Fe.stream_ops, - }) - n.stream = i - var a = be.createStream({ - path: t, - node: o, - flags: be.modeStringToFlags('w'), - seekable: !1, - stream_ops: Fe.stream_ops, - }) - return (o.stream = a), { readable_fd: i.fd, writable_fd: a.fd } - }, - stream_ops: { - poll: function(e) { - var r = e.node.pipe - if (1 == (2097155 & e.flags)) return 260 - if (r.buckets.length > 0) - for (var t = 0; t < r.buckets.length; t++) { - var n = r.buckets[t] - if (n.offset - n.roffset > 0) return 65 - } - return 0 - }, - ioctl: function(e, r, t) { - return Se - }, - read: function(e, r, t, n, o) { - for (var i = e.node.pipe, a = 0, s = 0; s < i.buckets.length; s++) { - var u = i.buckets[s] - a += u.offset - u.roffset - } - E(r instanceof ArrayBuffer || ArrayBuffer.isView(r)) - var c = r.subarray(t, t + n) - if (n <= 0) return 0 - if (0 == a) throw new be.ErrnoError(De) - var f = Math.min(a, n), - l = f, - d = 0 - for (s = 0; s < i.buckets.length; s++) { - var p = i.buckets[s], - m = p.offset - p.roffset - if (f <= m) { - var h = p.buffer.subarray(p.roffset, p.offset) - f < m ? ((h = h.subarray(0, f)), (p.roffset += f)) : d++, c.set(h) - break - } - ;(h = p.buffer.subarray(p.roffset, p.offset)), - c.set(h), - (c = c.subarray(h.byteLength)), - (f -= h.byteLength), - d++ - } - return ( - d && - d == i.buckets.length && - (d--, (i.buckets[d].offset = 0), (i.buckets[d].roffset = 0)), - i.buckets.splice(0, d), - l - ) - }, - write: function(e, r, t, n, o) { - var i = e.node.pipe - E(r instanceof ArrayBuffer || ArrayBuffer.isView(r)) - var a = r.subarray(t, t + n), - s = a.byteLength - if (s <= 0) return 0 - var u = null - 0 == i.buckets.length - ? ((u = { - buffer: new Uint8Array(Fe.BUCKET_BUFFER_SIZE), - offset: 0, - roffset: 0, - }), - i.buckets.push(u)) - : (u = i.buckets[i.buckets.length - 1]), - E(u.offset <= Fe.BUCKET_BUFFER_SIZE) - var c = Fe.BUCKET_BUFFER_SIZE - u.offset - if (c >= s) return u.buffer.set(a, u.offset), (u.offset += s), s - c > 0 && - (u.buffer.set(a.subarray(0, c), u.offset), - (u.offset += c), - (a = a.subarray(c, a.byteLength))) - for ( - var f = (a.byteLength / Fe.BUCKET_BUFFER_SIZE) | 0, - l = a.byteLength % Fe.BUCKET_BUFFER_SIZE, - d = 0; - d < f; - d++ - ) { - var p = { - buffer: new Uint8Array(Fe.BUCKET_BUFFER_SIZE), - offset: Fe.BUCKET_BUFFER_SIZE, - roffset: 0, - } - i.buckets.push(p), - p.buffer.set(a.subarray(0, Fe.BUCKET_BUFFER_SIZE)), - (a = a.subarray(Fe.BUCKET_BUFFER_SIZE, a.byteLength)) - } - return ( - l > 0 && - ((p = { - buffer: new Uint8Array(Fe.BUCKET_BUFFER_SIZE), - offset: a.byteLength, - roffset: 0, - }), - i.buckets.push(p), - p.buffer.set(a)), - s - ) - }, - close: function(e) { - e.node.pipe.buckets = null - }, - }, - nextname: function() { - return ( - Fe.nextname.current || (Fe.nextname.current = 0), - 'pipe[' + Fe.nextname.current++ + ']' - ) - }, - } - function Ae() { - return R.length - } - function Re(e) { - var r = Ae() - if (e > 2147418112) return !1 - for (var t = Math.max(r, 16777216); t < e; ) - t = - t <= 536870912 - ? H(2 * t, 65536) - : Math.min(H((3 * t + 2147483648) / 4, 65536), 2147418112) - return ( - !!(function(e) { - e = H(e, 65536) - var r = A.byteLength - try { - return -1 !== v.grow((e - r) / 65536) && ((A = v.buffer), !0) - } catch (e) { - return !1 - } - })(t) && (W(), !0) - ) - } - var Te = 277408 - function Pe() { - if (!Pe.called) { - ;(Pe.called = !0), (M[Ce() >> 2] = 60 * new Date().getTimezoneOffset()) - var e = new Date(2e3, 0, 1), - r = new Date(2e3, 6, 1) - M[ze() >> 2] = Number(e.getTimezoneOffset() != r.getTimezoneOffset()) - var t = a(e), - n = a(r), - o = S(Ne(t), 'i8', k), - i = S(Ne(n), 'i8', k) - r.getTimezoneOffset() < e.getTimezoneOffset() - ? ((M[Le() >> 2] = o), (M[(Le() + 4) >> 2] = i)) - : ((M[Le() >> 2] = i), (M[(Le() + 4) >> 2] = o)) - } - function a(e) { - var r = e.toTimeString().match(/\(([A-Za-z ]+)\)$/) - return r ? r[1] : 'GMT' - } - } - if ((C('GMT', 277456, 4), be.staticInit(), i)) { - var Me = require('fs'), - Be = require('path') - ge.staticInit() - } - function Ne(e, r, t) { - var n = t > 0 ? t : L(e) + 1, - o = new Array(n), - i = z(e, o, 0, o.length) - return r && (o.length = i), o - } - var Oe = { - b: Ze, - q: function(e) {}, - G: function e(r) { - var t, o - e.called - ? ((o = M[r >> 2]), (t = M[o >> 2])) - : ((e.called = !0), - (pe.USER = pe.LOGNAME = 'web_user'), - (pe.PATH = '/'), - (pe.PWD = '/'), - (pe.HOME = '/home/web_user'), - (pe.LANG = 'C.UTF-8'), - (pe._ = n.thisProgram), - (t = F(1024)), - (o = F(256)), - (M[o >> 2] = t), - (M[r >> 2] = o)) - var i = [], - a = 0 - for (var s in pe) - if ('string' == typeof pe[s]) { - var u = s + '=' + pe[s] - i.push(u), (a += u.length) - } - if (a > 1024) throw new Error('Environment size exceeded TOTAL_ENV_SIZE!') - for (var c = 0; c < i.length; c++) - U((u = i[c]), t), (M[(o + 4 * c) >> 2] = t), (t += u.length + 1) - M[(o + 4 * i.length) >> 2] = 0 - }, - l: he, - s: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD(), - n = ke.get(), - o = ke.get(), - i = ke.get(), - a = ke.get() - if (!((-1 == n && o < 0) || (0 == n && o >= 0))) return -75 - var s = o - return ( - be.llseek(t, s, a), - (tempI64 = [ - t.position >>> 0, - ((tempDouble = t.position), - +J(tempDouble) >= 1 - ? tempDouble > 0 - ? (0 | re(+ee(tempDouble / 4294967296), 4294967295)) >>> 0 - : ~~+Q((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (M[i >> 2] = tempI64[0]), - (M[(i + 4) >> 2] = tempI64[1]), - t.getdents && 0 === s && 0 === a && (t.getdents = null), - 0 - ) - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - i: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD(), - n = ke.get(), - o = ke.get() - return ke.doWritev(t, n, o) - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - p: function(e, r) { - ke.varargs = r - try { - for ( - var t = ke.get(), n = ke.get(), o = (ke.get(), 0), i = 0; - i < n; - i++ - ) { - var a = t + 8 * i, - s = M[a >> 2], - u = P[(a + 4) >> 1], - c = 32, - f = be.getStream(s) - f && - ((c = ke.DEFAULT_POLLMASK), - f.stream_ops.poll && (c = f.stream_ops.poll(f))), - (c &= 24 | u) && o++, - (P[(a + 6) >> 1] = c) - } - return o - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - o: function(e, r) { - ke.varargs = r - try { - var t = ke.getStr(), - n = ke.get() - return ke.doStat(be.stat, t, n) - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - n: function(e, r) { - ke.varargs = r - try { - var t = ke.getStr(), - n = ke.get() - return ke.doStat(be.lstat, t, n) - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - m: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD(), - n = ke.get() - return ke.doStat(be.stat, t.path, n) - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - c: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD() - switch (ke.get()) { - case 0: - return (n = ke.get()) < 0 ? -22 : be.open(t.path, t.flags, 0, n).fd - case 1: - case 2: - return 0 - case 3: - return t.flags - case 4: - var n = ke.get() - return (t.flags |= n), 0 - case 12: - return (n = ke.get()), (P[(n + 0) >> 1] = 2), 0 - case 13: - case 14: - return 0 - case 16: - case 8: - return -22 - case 9: - return he(22), -1 - default: - return -22 - } - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - F: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD(), - n = ke.get(), - o = ke.get() - return be.read(t, R, n, o) - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - E: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD(), - n = ke.get(), - o = ke.get() - return be.write(t, R, n, o) - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - D: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD() - return be.open(t.path, t.flags, 0).fd - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - C: function(e, r) { - ke.varargs = r - try { - var t = ke.get() - if (0 == t) throw new be.ErrnoError(14) - var n = Fe.createPipe() - return (M[t >> 2] = n.readable_fd), (M[(t + 4) >> 2] = n.writable_fd), 0 - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - B: function(e, r) { - ke.varargs = r - try { - var t = ke.getStr(), - n = ke.get(), - o = ke.get() - return be.open(t, n, o).fd - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - h: function(e, r) { - ke.varargs = r - try { - var t = ke.getStreamFromFD() - return be.close(t), 0 - } catch (e) { - return (void 0 !== be && e instanceof be.ErrnoError) || Ze(e), -e.errno - } - }, - g: function() { - n.abort() - }, - A: Ae, - z: function(e, r, t) { - T.set(T.subarray(r, r + t), e) - }, - y: Re, - f: function(e) { - !(function(e, r) { - ;(r && n.noExitRuntime && 0 === e) || - (n.noExitRuntime || ((y = !0), n.onExit && n.onExit(e)), - n.quit(e, new qe(e))) - })(e) - }, - x: function(e) { - return (function(e, r) { - Pe() - var t = new Date(1e3 * M[e >> 2]) - ;(M[r >> 2] = t.getSeconds()), - (M[(r + 4) >> 2] = t.getMinutes()), - (M[(r + 8) >> 2] = t.getHours()), - (M[(r + 12) >> 2] = t.getDate()), - (M[(r + 16) >> 2] = t.getMonth()), - (M[(r + 20) >> 2] = t.getFullYear() - 1900), - (M[(r + 24) >> 2] = t.getDay()) - var n = new Date(t.getFullYear(), 0, 1), - o = ((t.getTime() - n.getTime()) / 864e5) | 0 - ;(M[(r + 28) >> 2] = o), (M[(r + 36) >> 2] = -60 * t.getTimezoneOffset()) - var i = new Date(2e3, 6, 1).getTimezoneOffset(), - a = n.getTimezoneOffset(), - s = 0 | (i != a && t.getTimezoneOffset() == Math.min(a, i)) - M[(r + 32) >> 2] = s - var u = M[(Le() + (s ? 4 : 0)) >> 2] - return (M[(r + 40) >> 2] = u), r - })(e, Te) - }, - d: function(e) { - Pe() - var r = new Date( - M[(e + 20) >> 2] + 1900, - M[(e + 16) >> 2], - M[(e + 12) >> 2], - M[(e + 8) >> 2], - M[(e + 4) >> 2], - M[e >> 2], - 0 - ), - t = M[(e + 32) >> 2], - n = r.getTimezoneOffset(), - o = new Date(r.getFullYear(), 0, 1), - i = new Date(2e3, 6, 1).getTimezoneOffset(), - a = o.getTimezoneOffset(), - s = Math.min(a, i) - if (t < 0) M[(e + 32) >> 2] = Number(i != a && s == n) - else if (t > 0 != (s == n)) { - var u = Math.max(a, i), - c = t > 0 ? s : u - r.setTime(r.getTime() + 6e4 * (c - n)) - } - M[(e + 24) >> 2] = r.getDay() - var f = ((r.getTime() - o.getTime()) / 864e5) | 0 - return (M[(e + 28) >> 2] = f), (r.getTime() / 1e3) | 0 - }, - e: function() { - p('missing function: posix_spawn_file_actions_addclose'), Ze(-1) - }, - k: function() { - p('missing function: posix_spawn_file_actions_adddup2'), Ze(-1) - }, - j: function() { - p('missing function: posix_spawn_file_actions_destroy'), Ze(-1) - }, - w: function() { - p('missing function: posix_spawn_file_actions_init'), Ze(-1) - }, - v: function() { - return function() { - return he(11), -1 - }.apply(null, arguments) - }, - u: function(e) { - Pe() - var r = Date.UTC( - M[(e + 20) >> 2] + 1900, - M[(e + 16) >> 2], - M[(e + 12) >> 2], - M[(e + 8) >> 2], - M[(e + 4) >> 2], - M[e >> 2], - 0 - ), - t = new Date(r) - M[(e + 24) >> 2] = t.getUTCDay() - var n = Date.UTC(t.getUTCFullYear(), 0, 1, 0, 0, 0, 0), - o = ((t.getTime() - n) / 864e5) | 0 - return (M[(e + 28) >> 2] = o), (t.getTime() / 1e3) | 0 - }, - t: function() { - return function(e) { - return he(10), -1 - }.apply(null, arguments) - }, - r: function(e) { - Ze('OOM') - }, - a: q, - }, - xe = n.asm({}, Oe, A) - n.asm = xe - var Ie = (n.___emscripten_environ_constructor = function() { - return n.asm.H.apply(null, arguments) - }), - ze = - ((n.___errno_location = function() { - return n.asm.I.apply(null, arguments) - }), - (n.__get_daylight = function() { - return n.asm.J.apply(null, arguments) - })), - Ce = (n.__get_timezone = function() { - return n.asm.K.apply(null, arguments) - }), - Le = (n.__get_tzname = function() { - return n.asm.L.apply(null, arguments) - }), - Ue = - ((n._archive_close = function() { - return n.asm.M.apply(null, arguments) - }), - (n._archive_entry_filetype = function() { - return n.asm.N.apply(null, arguments) - }), - (n._archive_entry_is_encrypted = function() { - return n.asm.O.apply(null, arguments) - }), - (n._archive_entry_pathname = function() { - return n.asm.P.apply(null, arguments) - }), - (n._archive_entry_pathname_utf8 = function() { - return n.asm.Q.apply(null, arguments) - }), - (n._archive_entry_size = function() { - return n.asm.R.apply(null, arguments) - }), - (n._archive_error_string = function() { - return n.asm.S.apply(null, arguments) - }), - (n._archive_open = function() { - return n.asm.T.apply(null, arguments) - }), - (n._archive_read_add_passphrase = function() { - return n.asm.U.apply(null, arguments) - }), - (n._archive_read_data_skip = function() { - return n.asm.V.apply(null, arguments) - }), - (n._archive_read_has_encrypted_entries = function() { - return n.asm.W.apply(null, arguments) - }), - (n._free = function() { - return n.asm.X.apply(null, arguments) - }), - (n._get_filedata = function() { - return n.asm.Y.apply(null, arguments) - }), - (n._get_next_entry = function() { - return n.asm.Z.apply(null, arguments) - }), - (n._get_version = function() { - return n.asm._.apply(null, arguments) - }), - (n._malloc = function() { - return n.asm.$.apply(null, arguments) - })), - je = (n.stackAlloc = function() { - return n.asm.ca.apply(null, arguments) - }), - He = (n.stackRestore = function() { - return n.asm.da.apply(null, arguments) - }), - We = (n.stackSave = function() { - return n.asm.ea.apply(null, arguments) - }) - function qe(e) { - ;(this.name = 'ExitStatus'), - (this.message = 'Program terminated with exit(' + e + ')'), - (this.status = e) - } - function Ke(e) { - function r() { - n.calledRun || - ((n.calledRun = !0), - y || - ($ || - (($ = !0), - n.noFSInit || be.init.initialized || be.init(), - (Fe.root = be.mount(Fe, {}, null)), - Z(X)), - (be.ignorePermissions = !1), - Z(Y), - n.onRuntimeInitialized && n.onRuntimeInitialized(), - (function() { - if (n.postRun) - for ( - 'function' == typeof n.postRun && (n.postRun = [n.postRun]); - n.postRun.length; - - ) - (e = n.postRun.shift()), G.unshift(e) - var e - Z(G) - })())) - } - ;(e = e || n.arguments), - te > 0 || - ((function() { - if (n.preRun) - for ( - 'function' == typeof n.preRun && (n.preRun = [n.preRun]); - n.preRun.length; - - ) - (e = n.preRun.shift()), V.unshift(e) - var e - Z(V) - })(), - te > 0 || - n.calledRun || - (n.setStatus - ? (n.setStatus('Running...'), - setTimeout(function() { - setTimeout(function() { - n.setStatus('') - }, 1), - r() - }, 1)) - : r())) - } - function Ze(e) { - throw (n.onAbort && n.onAbort(e), - void 0 !== e ? (d(e), p(e), (e = JSON.stringify(e))) : (e = ''), - (y = !0), - 'abort(' + e + '). Build with -s ASSERTIONS=1 for more info.') - } - if ( - ((n.dynCall_v = function() { - return n.asm.aa.apply(null, arguments) - }), - (n.dynCall_vi = function() { - return n.asm.ba.apply(null, arguments) - }), - (n.asm = xe), - (n.intArrayFromString = Ne), - (n.cwrap = function(e, r, t, n) { - var o = (t = t || []).every(function(e) { - return 'number' === e - }) - return 'string' !== r && o && !n - ? g(e) - : function() { - return _(e, r, t, arguments) - } - }), - (n.allocate = S), - (n.then = function(e) { - if (n.calledRun) e(n) - else { - var r = n.onRuntimeInitialized - n.onRuntimeInitialized = function() { - r && r(), e(n) - } - } - return n - }), - (qe.prototype = new Error()), - (qe.prototype.constructor = qe), - (oe = function e() { - n.calledRun || Ke(), n.calledRun || (oe = e) - }), - (n.run = Ke), - (n.abort = Ze), - n.preInit) - ) - for ( - 'function' == typeof n.preInit && (n.preInit = [n.preInit]); - n.preInit.length > 0; - - ) - n.preInit.pop()() - return (n.noExitRuntime = !0), Ke(), e - }) - class o { - constructor() { - ;(this.preRun = []), (this.postRun = []), (this.totalDependencies = 0) - } - print(...e) { - console.log(e) - } - printErr(...e) { - console.error(e) - } - initFunctions() { - this.runCode = { - getVersion: this.cwrap('get_version', 'string', []), - openArchive: this.cwrap('archive_open', 'number', ['number', 'number', 'string']), - getNextEntry: this.cwrap('get_next_entry', 'number', ['number']), - getFileData: this.cwrap('get_filedata', 'number', ['number', 'number']), - skipEntry: this.cwrap('archive_read_data_skip', 'number', ['number']), - closeArchive: this.cwrap('archive_close', null, ['number']), - getEntrySize: this.cwrap('archive_entry_size', 'number', ['number']), - getEntryName: this.cwrap('archive_entry_pathname', 'string', ['number']), - getEntryType: this.cwrap('archive_entry_filetype', 'number', ['number']), - getError: this.cwrap('archive_error_string', 'string', ['number']), - entryIsEncrypted: this.cwrap('archive_entry_is_encrypted', 'number', ['number']), - hasEncryptedEntries: this.cwrap('archive_read_has_encrypted_entries', 'number', [ - 'number', - ]), - addPassphrase: this.cwrap('archive_read_add_passphrase', 'number', [ - 'number', - 'string', - ]), - string: e => this.allocate(this.intArrayFromString(e), 'i8', 0), - malloc: this.cwrap('malloc', 'number', ['number']), - free: this.cwrap('free', null, ['number']), - } - } - monitorRunDependencies() {} - locateFile(e) { - return `wasm-gen/${e}` - } - } - let i = null, - a = !1 - var s - ;(s = e => { - ;(i = new r(e)), (a = !1), self.postMessage({ type: 'READY' }) - }), - n(new o()).then(e => { - e.initFunctions(), s(e) - }), - (self.onmessage = async ({ data: e }) => { - if (a) return void self.postMessage({ type: 'BUSY' }) - let r = !1 - a = !0 - try { - switch (e.type) { - case 'HELLO': - break - case 'OPEN': - await i.open(e.file), self.postMessage({ type: 'OPENED' }) - break - case 'LIST_FILES': - r = !0 - case 'EXTRACT_FILES': - for (const e of i.entries(r)) self.postMessage({ type: 'ENTRY', entry: e }) - self.postMessage({ type: 'END' }) - break - case 'EXTRACT_SINGLE_FILE': - for (const r of i.entries(!0, e.target)) - r.fileData && self.postMessage({ type: 'FILE', entry: r }) - break - case 'CHECK_ENCRYPTION': - self.postMessage({ type: 'ENCRYPTION_STATUS', status: i.hasEncryptedData() }) - break - case 'SET_PASSPHRASE': - i.setPassphrase(e.passphrase), - self.postMessage({ type: 'PASSPHRASE_STATUS', status: !0 }) - break - default: - throw new Error('Invalid Command') - } - } catch (e) { - self.postMessage({ - type: 'ERROR', - error: { message: e.message, name: e.name, stack: e.stack }, - }) - } finally { - a = !1 - } - }) -})() diff --git a/packages/villain-react/dev-sandbox/theme.css b/packages/villain-react/dev-sandbox/theme.css deleted file mode 100644 index 03de5178..00000000 --- a/packages/villain-react/dev-sandbox/theme.css +++ /dev/null @@ -1,31 +0,0 @@ -html.color-theme-in-transition, -html.color-theme-in-transition *, -html.color-theme-in-transition *:before, -html.color-theme-in-transition *:after { - transition: all 750ms !important; - transition-delay: 0 !important; -} - -.villain-demo[data-theme='Light'] { - /* global colors */ - --primary-bg: #f2f2f2; - --card-bg: #fff; - --primary-text: #212121; - --input-bg: #fff; - --input-border: rgba(0, 0, 0, 0.2); -} - -.villain-demo[data-theme='Dark'] { - /* global colors */ - --primary-bg: #0b0b0b; - --card-bg: #282828; - --primary-text: #fff; - --input-bg: rgba(255, 255, 255, 0.1); - --input-border: rgba(255, 255, 255, 0.4); -} - -.villain-demo { - background: var(--primary-bg); - color: var(--primary-text); - font-weight: 400; -} diff --git a/packages/villain-react/dist/style.css b/packages/villain-react/dist/style.css deleted file mode 100644 index 7352d410..00000000 --- a/packages/villain-react/dist/style.css +++ /dev/null @@ -1 +0,0 @@ -.villain[data-theme=Dark]{--bg-color:#131313;--fg-color:#fff;--icon-color:var(--fg-color);--slider-bg:hsla(0,0%,100%,0.1);--slider-track-bg:#fff;--slider-buffer-bg:hsla(0,0%,100%,0.4);--input-border-focus:hsla(0,0%,100%,0.4);--input-bg:rgba(0,0,0,0.24);--input-border:rgba(0,0,0,0.24);--input-focus-bg:hsla(0,0%,88.2%,0.15);--button-bg:hsla(0,0%,100%,0.1);--button-active-bg:hsla(0,0%,100%,0.15);--button-hover-bg:var(--button-active-bg);--toolbar-bg:#282828;--toolbar-border:hsla(0,0%,100%,0.2);--toolbar-height:50px;--tooltip-bg:#575a67;--tooltip-fg:var(--fg-color);--toggler-bg:hsla(0,0%,100%,0.24)}.villain[data-theme=Light]{--bg-color:#f7f7f7;--fg-color:#757575;--icon-color:var(--fg-color);--slider-bg:rgba(0,0,0,0.1);--slider-buffer-bg:rgba(0,0,0,0.2);--slider-track-bg:var(--fg-color);--input-bg:#fff;--input-border:hsla(0,0%,70.6%,0.4);--input-border-focus:hsla(0,0%,58.8%,0.4);--input-focus-bg:hsla(0,0%,78.4%,0.24);--button-bg:rgba(0,0,0,0.1);--button-active-bg:rgba(0,0,0,0.15);--button-hover-bg:var(--button-active-bg);--toolbar-bg:#fff;--toolbar-border:rgba(0,0,0,0.2);--toolbar-height:50px;--tooltip-bg:var(--fg-color);--tooltip-fg:#fff;--toggler-bg:rgba(0,0,0,0.24)}.villain{--font-family:Helvetica. Arial,sans-serif;position:relative;background-color:var(--bg-color);color:var(--fg-color);overflow:hidden;border:1px solid rgba(0,0,0,.1);font-size:14px;font-family:var(--font-family);min-height:359px;min-width:640px}.villain--fullscreen{position:fixed;top:0;left:0;width:100%!important;height:100%!important;margin:0;z-index:99}.villain--static .villain-toolbar{margin:0;border-radius:0}.villain--static .villain-canvas{bottom:var(--toolbar-height)}.villain-icon{fill:var(--icon-color)}.villain-menu{--menu-width:240px;--menu-item-height:38px;outline:none;min-width:var(--menu-width);border-radius:8px;transform-origin:bottom}.villain-menu__item .villain-icon{margin-right:12px;width:24px;height:24px}.villain-menu__radio .villain-icon{margin-right:14px}.villain-menu__item:first-child{margin-top:0}.villain-menu__item:last-child{margin-bottom:0}.villain-menu__item{padding:0 14px;border:0;background:transparent;font-size:14px;color:var(--fg-color);width:100%;text-align:left;display:flex;justify-content:flex-start;align-items:center;outline:none;cursor:pointer;height:var(--menu-item-height)}.villain-menu .villain-menu__item:focus{box-shadow:none}.villain-menu__item__content{display:flex;justify-content:space-between;align-self:center;align-items:center;flex:1 0 0}.villain-menu__item .villain-menu__item__icon{margin:0}.villain-menu__item__toggler{height:16px;width:30px;border-radius:16px;position:relative;margin-left:24px;background-color:var(--toggler-bg)}.villain-menu__item__toggler:after{content:"";display:block;background-color:var(--toolbar-bg);height:10px;width:10px;position:absolute;top:50%;left:0;margin:auto 4px;transform:translateY(-50%);border-radius:12px;transition-duration:.2s;transition-timing-function:ease;transition-property:transform}.villain-menu__checkbox[aria-checked=true] .villain-menu__item__toggler:after{transform:translate(125%,-50%)}.villain-menu__checkbox[aria-checked=true] .villain-menu__item__toggler{background-color:var(--fg-color)}.villain-menu__item:focus{background:var(--button-bg);outline:none}.villain-menu__separator{border:0;margin:0;border-top:1px solid var(--fg-color);opacity:.2}.villain-menu__panel{margin:0;padding:0;width:100%;display:block;background:var(--toolbar-bg)}.villain-menu__animated-content{margin:0;width:var(--menu-width);background:var(--toolbar-bg);box-shadow:0 0 4px 0 rgba(0,0,0,.1),0 0 0 1px rgba(0,0,0,.1);border-radius:8px;position:absolute;left:0;bottom:0;overflow-y:auto;overflow-x:hidden;transform:translateZ(0) scaleX(1);will-change:transform,height,opacity}.villain-menu__animated-content[data-animation=true]{pointer-events:none;overflow:hidden}.villain-menu__header .villain-menu__item{margin:0}.villain-menu__title{padding:8px;margin:4px 0;display:block;border-bottom:1px solid rgba(0,0,0,.5)}.villain-toolbar .villain-input{-moz-appearance:textfield;text-align:right;color:var(--fg-color);height:1rem;max-width:38px;font-size:14px;font-family:var(--font-family);font-weight:700;background:var(--input-bg);border:0}.villain-toolbar .villain-input:focus{background:transparent;border-color:transparent;outline:0}.villain-toolbar input[type=number]::-webkit-inner-spin-button,.villain-toolbar input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.villain-label{margin:0 6px;opacity:.8;font-size:14px;padding:0 2px;font-weight:700}.villain-wrapper-input{display:flex;justify-content:space-around;align-items:baseline;align-self:center;flex-grow:0;min-width:52px;background:var(--input-bg);border:2px solid var(--input-border);padding:2px 6px;color:var(--fg-color);margin:0 8px;border-radius:16px;cursor:pointer}.villain-wrapper-input .villain-input{border:0;margin:0;background:transparent;padding:0;border-radius:0;display:inline-block;min-width:0;text-align:right;flex:1 1 0}.villain-wrapper-input .villain-input:focus{box-shadow:none}.villain-wrapper-input .villain-label{border:0;margin:0;padding:0;background:transparent;display:inline-block;min-width:0;width:25%;text-align:left;flex:1 1 0}.villain-wrapper-input[data-focus=true]{background:var(--input-focus-bg);border-color:var(--input-border-focus)}.villain-wrapper-input .villain-label--center{text-align:center;flex:0.5}.villain-button{background:var(--button-bg);border:0;border-radius:4px;color:var(--fg-color);margin:0 4px;padding:2px;display:flex;align-items:center;justify-content:center;cursor:pointer}.villain-button--icon{padding:.3em;border-radius:4px;background:transparent;width:32px;height:32px;margin:0 6px}.villain-button__label{padding:2px 4px}.villain-button--icon:focus:not([aria-disabled=true]):not(.villain-button--active),.villain-button--icon:hover:not([aria-disabled=true]):not(.villain-button--active){background:var(--button-hover-bg)}.villain-button--active:not([aria-disabled=true]),.villain-button--icon:active:not([aria-disabled=true]){background:var(--button-active-bg)}.villain-button[aria-disabled=true]{opacity:.4;cursor:default}.villain-canvas{width:100%;position:absolute!important;top:0;left:0;right:0;bottom:0;margin:0;z-index:0}.villain-overlay{position:absolute;width:100%;height:100%;top:0;left:0;margin:0;background:var(--bg-color);text-align:center;display:flex;align-items:center;justify-content:center;flex-direction:column}.villain-overlay--message{margin:1em}.villain-loader-indicator,.villain-loader-indicator:after{border-radius:50%;width:10em;height:10em}.villain-loader-indicator{margin:60px auto;font-size:4px;position:relative;text-indent:-9999em;border:1.6em solid var(--toolbar-border);border-left-color:var(--fg-color);-webkit-transform:translateZ(0);-ms-transform:translateZ(0);transform:translateZ(0);-webkit-animation:villain-animation-load 1.1s linear infinite;animation:villain-animation-load 1.1s linear infinite}.openseadragon-message{display:none!important}.villain-slider{position:relative;margin:0 8px;flex-grow:1;width:100%;min-width:50px}.villain-slider__buffer{z-index:0;margin:0;height:100%;border-radius:4px;background-color:var(--slider-buffer-bg);position:absolute;transition:width .3s ease;will-change:width}.villain-slider__track{position:absolute;top:0;left:0;bottom:0;margin:0;z-index:1;border-radius:4px;background-color:var(--slider-track-bg);cursor:pointer}.villain-toolbar.villain-toolbar--hide{opacity:0;transform:translate3d(0,50px,0);transition-delay:.8s}.villain-toolbar{background:var(--toolbar-bg);padding:0 4px;display:flex;align-self:center;align-items:center;justify-content:space-between;height:var(--toolbar-height);margin:8px;position:absolute;bottom:0;left:0;right:0;opacity:1;z-index:1;border:0;border-radius:8px;box-sizing:border-box;box-shadow:0 0 4px 0 rgba(0,0,0,.1),0 0 0 1px rgba(0,0,0,.1);transform:translateZ(0);transition-property:opacity,transform;transition-duration:.3s;transition-timing-function:ease;transition-delay:.2s}.villain-toolbar__divider{height:1em;width:2px;margin:0 12px;border:0;background:var(--toolbar-border)}.villain-toolbar__group{display:flex;align-items:center;justify-content:center;margin:0 4px}.villain-toolbar__group[disabled]{opacity:.4;user-select:none;pointer-events:none}.villain-toolbar__group--expand{flex-grow:1}.villain-tooltip{color:var(--tooltip-fg,#fff);background-color:var(--tooltip-bg,#575a67);width:max-content;z-index:99;padding:4px 8px;border-radius:4px;margin-bottom:8px}.villain-tooltip--slider{left:50%;bottom:28px;padding:0;width:28px;height:28px;margin-left:-14px;border:none;background:var(--tooltip-bg);color:#fff;font-size:12px;font-weight:600;line-height:28px;border-radius:50%;position:absolute;text-align:center}.villain-tooltip--slider:before{content:"";top:9px;width:20px;height:20px;position:absolute;left:50%;background:var(--tooltip-bg);margin-left:-10px;z-index:-1;-ms-transform:rotate(45deg);-webkit-transform:rotate(45deg);transform:rotate(45deg);border-radius:10px 10px 0 10px}@keyframes villain-animation-load{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}} \ No newline at end of file diff --git a/packages/villain-react/dist/villain.js b/packages/villain-react/dist/villain.js deleted file mode 100644 index 5afa9b9d..00000000 --- a/packages/villain-react/dist/villain.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react"),require("reakit")):"function"==typeof define&&define.amd?define(["react","reakit"],t):(e=e||self).villain=t(e.React,e.reakit)}(this,(function(React,reakit){"use strict";var React__default="default"in React?React.default:React;function toVal(e){var t,i,n="";if(e)if("object"==typeof e)if(e.push)for(t=0;t1?t-1:0),n=1;n2?i-2:0),r=2;r1?printWarning$1("Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."):printWarning$1("Invalid argument supplied to oneOf, expected an array."),emptyFunctionThatReturnsNull;return l((function(t,i,n,r,o){for(var l=t[i],c=0;c{this.setState(e,t)},this.clear=()=>{this.setState({...defaultState})},this.toggleSetting=e=>{this.setState(t=>({[e]:!t[e]}))},this.createPage=e=>{const t=this.state.pages.concat(e);0===e.index?this.setState({ready:!0,error:null,currentPage:0,pages:t}):this.setState({pages:t})},this.trigger=(e,t)=>{"error"===e&&t&&(console.error(t),this.setState({ready:!1,error:t}))},this.togglePin=()=>{this.setState(e=>({autoHideControls:!e.autoHideControls}))},this.navigateToPage=e=>{this.setState(t=>{const{totalPages:i}=t,n=i-1;return e<0||e>n?{}:{isLastPage:e===n,isFirstPage:0===e,currentPage:e}})},this.navigateForward=()=>{const{isLastPage:e,currentPage:t}=this.state;e||this.navigateToPage(t+1)},this.navigateBackward=()=>{const{isFirstPage:e,currentPage:t}=this.state;e||this.navigateToPage(t-1)},this.getPage=e=>{const{pages:t,bookMode:i}=this.state,n=t&&t.length&&t[e];if(n){const r=e+1,o=r0){return[n,t[r]]}return n}return null},this.state={clear:this.clear,trigger:this.trigger,getPage:this.getPage,updateState:this.updateState,createPage:this.createPage,toggleSetting:this.toggleSetting,togglePin:this.togglePin,navigateToPage:this.navigateToPage,navigateForward:this.navigateForward,navigateBackward:this.navigateBackward,...defaultContext,...this.props.externalOptions}}render(){return React__default.createElement(ReaderContext.Provider,{value:this.state},this.props.children)}}var utils=createCommonjsModule((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.getInterfaceLanguage=function(){if("undefined"==typeof navigator)return"en-US";var e=navigator;if(e){if(e.language)return e.language;if(e.languages&&e.languages[0])return e.languages[0];if(e.userLanguage)return e.userLanguage;if(e.browserLanguage)return e.browserLanguage}return"en-US"},t.getBestMatchingLanguage=function(e,t){if(t[e])return e;var i=e.indexOf("-"),n=i>=0?e.substring(0,i):e;return t[n]?n:Object.keys(t)[0]},t.validateTranslationKeys=function(e){var t=["_interfaceLanguage","_language","_defaultLanguage","_defaultLanguageFirstLevelKeys","_props"];e.forEach((function(e){if(-1!==t.indexOf(e))throw new Error(e+" cannot be used as a key. It is a reserved word.")}))},t.randomPseudo=function(e){for(var t="",i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=0;n1?i-1:0),r=1;r2&&void 0!==arguments[2]&&arguments[2];try{for(var n=this._props[t||this._language],r=e.split("."),o=0;o1?t-1:0),o=1;o{const{theme:o,language:a,fullscreen:s,autoHideControls:l}=n;return localize.setLanguage(a),React__default.createElement("div",{ref:r,style:e,className:clsx("villain",s&&"villain--fullscreen",!l&&"villain--static",i),"data-theme":o},t)}),PureWrapper=React__default.memo(Wrapper),WrapperConsumer=({children:e,...t})=>{const i=React.useRef(null);return React__default.createElement(ReaderContext.Consumer,null,({theme:n,fullScreen:r,language:o,autoHideControls:a})=>React__default.createElement(PureWrapper,_extends({},t,{ref:i,theme:n,fullScreen:r,autoHideControls:a,language:o}),e(i?i.current:null)))};var Wrapp=React__default.memo(WrapperConsumer);const OptionsConsumer=React__default.memo(({options:e})=>{const t=React__default.useContext(ReaderContext);return React__default.useEffect(()=>{Object.entries(e).map(([e,i])=>{t[e]!==i&&t.updateState({[e]:i})})},[e]),null}),useFocus=()=>{const e=React.useRef(null);return[e,()=>{e.current&&(e.current.focus(),e.current.select())}]},getNestedFocus=e=>{const t=document.activeElement;return e.contains(t)},getInteractionFocus=()=>{const e=document.activeElement;if(e){return["BUTTON","INPUT","TEXTAREA"].includes(e.tagName)}},prefixes={exitFullscreen:["exitFullscreen","msExitFullscreen","mozCancelFullScreen","webkitExitFullscreen"],fullscreenChange:["fullscreenchange","MSFullscreenChange","mozfullscreenchange","webkitfullscreenchange"],fullscreenEnabled:["fullscreenEnabled","msFullscreenEnabled","mozFullScreenEnabled","webkitFullscreenEnabled"],fullscreenElement:["fullscreenElement","msFullscreenElement","mozFullScreenElement","webkitFullscreenElement"],requestFullscreen:["requestFullscreen","msRequestFullscreen","mozRequestFullScreen","webkitRequestFullscreen"]},getPrefix=()=>{let e=0;return prefixes.fullscreenEnabled.some((t,i)=>{if(document[t]||!1===document[t])return e=i,!0}),e},fullscreenElement=()=>{const e=getPrefix(),t=prefixes.fullscreenElement[e];return document[t]},requestFullscreen=e=>{const t=getPrefix(),i=prefixes.requestFullscreen[t];e[i]&&e[i]()},exitFullscreen=()=>{const e=getPrefix(),t=prefixes.exitFullscreen[e];document[t]&&document[t]()},toggleFullscreen=e=>{fullscreenElement()?exitFullscreen():requestFullscreen(e)},onFullscreenChange=(e,t,i)=>{const n=getPrefix(),r=prefixes.fullscreenChange[n];e[`${t}EventListener`](r,i,!1)},KeyboardConsumer=React__default.memo(({container:e})=>{const t=React__default.useContext(ReaderContext),{error:i,mangaMode:n,navigateBackward:r,navigateForward:o,allowGlobalShortcuts:a,allowFullScreen:s}=t,l=React__default.useCallback(t=>{if(i||getInteractionFocus())return;if(!a&&!getNestedFocus(e))return;const s=n?r:o,l=n?o:r;switch(t.key){case"f":t.preventDefault(),toggleFullscreen(e);break;case"ArrowRight":s();break;case"ArrowLeft":l()}},[s,a,n,r,o,e]);return React__default.useEffect(()=>(document.addEventListener("keydown",l),()=>{document.removeEventListener("keydown",l)}),[l]),null});class CompressedFile{constructor(e,t,i,n){this._name=e,this._size=t,this._path=i,this._archiveRef=n}get name(){return this._name}get size(){return this._size}extract(){return this._archiveRef.extractSingleFile(this._path)}}class Archive{static init(e={}){return Archive._options={workerUrl:"../dist/worker-bundle.js",...e},Archive._options}static open(e,t=null){return t=t||Archive._options||Archive.init()&&console.warn("Automatically initializing using options: ",Archive._options),new Archive(e,t).open()}constructor(e,t){this._worker=new Worker(t.workerUrl),this._worker.addEventListener("message",this._workerMsg.bind(this)),this._callbacks=[],this._content={},this._processed=0,this._file=e}async open(){return await this._postMessage({type:"HELLO"},(e,t,i)=>{"READY"===i.type&&e()}),await this._postMessage({type:"OPEN",file:this._file},(e,t,i)=>{"OPENED"===i.type&&e(this)})}hasEncryptedData(){return this._postMessage({type:"CHECK_ENCRYPTION"},(e,t,i)=>{"ENCRYPTION_STATUS"===i.type&&e(i.status)})}usePassword(e){return this._postMessage({type:"SET_PASSPHRASE",passphrase:e},(e,t,i)=>{"PASSPHRASE_STATUS"===i.type&&e(i.status)})}getFilesObject(){return this._processed>0?Promise.resolve().then(()=>this._content):this._postMessage({type:"LIST_FILES"},(e,t,i)=>{if("ENTRY"===i.type){const e=i.entry,[t,n]=this._getProp(this._content,e.path);return"FILE"===e.type&&(t[n]=new CompressedFile(e.fileName,e.size,e.path,this)),!0}"END"===i.type&&(this._processed=1,e(this._cloneContent(this._content)))})}getFilesArray(){return this.getFilesObject().then(e=>this._objectToArray(e))}extractSingleFile(e){return this._postMessage({type:"EXTRACT_SINGLE_FILE",target:e},(e,t,i)=>{if("FILE"===i.type){e(new File([i.entry.fileData],i.entry.fileName,{type:"application/octet-stream"}))}})}extractFiles(e){return this._processed>1?Promise.resolve().then(()=>this._content):this._postMessage({type:"EXTRACT_FILES"},(t,i,n)=>{if("ENTRY"===n.type){const[t,i]=this._getProp(this._content,n.entry.path);return"FILE"===n.entry.type&&(t[i]=new File([n.entry.fileData],n.entry.fileName,{type:"application/octet-stream"}),void 0!==e&&setTimeout(e.bind(null,{file:t[i],path:n.entry.path}))),!0}"END"===n.type&&(this._processed=2,this._worker.terminate(),t(this._cloneContent(this._content)))})}_cloneContent(e){if(e instanceof File||e instanceof CompressedFile||null===e)return e;const t={};for(const i of Object.keys(e))t[i]=this._cloneContent(e[i]);return t}_objectToArray(e,t=""){const i=[];for(const n of Object.keys(e))e[n]instanceof File||e[n]instanceof CompressedFile||null===e[n]?i.push({file:e[n]||n,path:t}):i.push(...this._objectToArray(e[n],`${t}${n}/`));return i}_getProp(e,t){const i=t.split("/");""===i[i.length-1]&&i.pop();let n=e,r=null;for(const e of i)n[e]=n[e]||{},r=n,n=n[e];return[r,i[i.length-1]]}_postMessage(e,t){return this._worker.postMessage(e),new Promise((e,i)=>{this._callbacks.push(this._msgHandler.bind(this,t,e,i))})}_msgHandler(e,t,i,n){if("BUSY"===n.type)i("worker is busy");else{if("ERROR"!==n.type)return e(t,i,n);i(n.error)}}_workerMsg({data:e}){(0,this._callbacks[this._callbacks.length-1])(e)||this._callbacks.pop()}}const regexImage=new RegExp(/(^[A-Za-zªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛱ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢄᢇ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々〆〱-〵〻〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿯ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛥꜗ-ꜟꜢ-ꞈꞋ-ꞹꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ0-9²³¹¼-¾٠-٩۰-۹߀-߉०-९০-৯৴-৹੦-੯૦-૯୦-୯୲-୷௦-௲౦-౯౸-౾೦-೯൘-൞൦-൸෦-෯๐-๙໐-໙༠-༳၀-၉႐-႙፩-፼ᛮ-ᛰ០-៩៰-៹᠐-᠙᥆-᥏᧐-᧚᪀-᪉᪐-᪙᭐-᭙᮰-᮹᱀-᱉᱐-᱙⁰⁴-⁹₀-₉⅐-ↂↅ-↉①-⒛⓪-⓿❶-➓⳽〇〡-〩〸-〺㆒-㆕㈠-㈩㉈-㉏㉑-㉟㊀-㊉㊱-㊿꘠-꘩ꛦ-ꛯ꠰-꠵꣐-꣙꤀-꤉꧐-꧙꧰-꧹꩐-꩙꯰-꯹0-9*@()_-]([A-Za-zªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛱ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢄᢇ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々〆〱-〵〻〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿯ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛥꜗ-ꜟꜢ-ꞈꞋ-ꞹꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ0-9²³¹¼-¾٠-٩۰-۹߀-߉०-९০-৯৴-৹੦-੯૦-૯୦-୯୲-୷௦-௲౦-౯౸-౾೦-೯൘-൞൦-൸෦-෯๐-๙໐-໙༠-༳၀-၉႐-႙፩-፼ᛮ-ᛰ០-៩៰-៹᠐-᠙᥆-᥏᧐-᧚᪀-᪉᪐-᪙᭐-᭙᮰-᮹᱀-᱉᱐-᱙⁰⁴-⁹₀-₉⅐-ↂↅ-↉①-⒛⓪-⓿❶-➓⳽〇〡-〩〸-〺㆒-㆕㈠-㈩㉈-㉏㉑-㉟㊀-㊉㊱-㊿꘠-꘩ꛦ-ꛯ꠰-꠵꣐-꣙꤀-꤉꧐-꧙꧰-꧹꩐-꩙꯰-꯹0-9\s.*@()_-]+)?)+.(jpeg|jpg|png|bpm|webp)$/),status=e=>e.status>=200&&e.status<300?Promise.resolve(e):Promise.reject(new Error(e.statusText)),isValidImageType=e=>regexImage.test(e),fetchArchive=(e,t,i)=>{fetch(e,{mode:"cors"}).then(status).then(e=>{e.headers.get("Content-Type");return e.blob()}).then(t).catch(e=>{i&&i("Cant open archive"),console.error("Request failed",e)})},asyncForEach=async(e,t)=>{for(let i=0;iObject.keys(e).find(i=>e[i]===t),debounce=(e,t,i)=>{let n;return function(){const r=this,o=arguments,a=()=>{n=null,i||e.apply(r,o)},s=i&&!n;clearTimeout(n),n=setTimeout(a,t),s&&e.apply(r,o)}};var Icon=createCommonjsModule((function(e){e.exports=function(e){var t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(n,r,function(t){return e[t]}.bind(null,r));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=2)}([function(e,t){e.exports=propTypes},function(e,t){e.exports=React__default},function(e,t,i){i.r(t);var n=i(1),r=i(0),o=function(){return(o=Object.assign||function(e){for(var t,i=1,n=arguments.length;i0&&(x.transform=C.join(" "),x.transformOrigin="center",E&&(O=n.createElement("g",{style:x},k,n.createElement("rect",{width:"24",height:"24",fill:"transparent"}))));var I,M=O,L=!0===T||"number"!=typeof T?2:T,A=!E&&(m||v);if(L<0&&(A=!A),T&&(M=n.createElement("g",{style:{animation:"spin"+(A?"-inverse":"")+" linear "+Math.abs(L)+"s infinite",transformOrigin:"center"}},O,!(m||v||0!==w)&&n.createElement("rect",{width:"24",height:"24",fill:"transparent"}))),E)return M;var D,H="icon_labelledby_"+u,z="icon_describedby_"+u;if(o)I=s?H+" "+z:H;else if(D="presentation",s)throw new Error("title attribute required when description is set");return n.createElement("svg",c({ref:t,viewBox:"0 0 24 24",style:x,role:D,"aria-labelledby":I},P),o&&n.createElement("title",{id:H},o),s&&n.createElement("desc",{id:z},s),!E&&T&&(A?n.createElement("style",null,"@keyframes spin-inverse { to { transform: rotate(-360deg) } }"):n.createElement("style",null,"@keyframes spin { to { transform: rotate(360deg) } }")),M)}));h.displayName="Icon",h.propTypes={path:r.string.isRequired,size:r.oneOfType([r.number,r.string]),color:r.string,horizontal:r.bool,vertical:r.bool,rotate:r.number,spin:r.oneOfType([r.bool,r.number]),style:r.object,inStack:r.bool,className:r.string},h.defaultProps={size:null,color:null,horizontal:!1,vertical:!1,rotate:0,spin:!1},t.default=h}])})),Icon$1=unwrapExports(Icon);const Localized=React__default.memo(({value:e,language:t})=>localize[e]),LocalizedConsumer=React__default.memo(({value:e})=>{const{language:t}=React__default.useContext(ReaderContext);return React__default.createElement(Localized,{value:e,language:t})}),Error$1=React__default.memo(e=>{const{icon:t,message:i}=e;return React__default.createElement("div",{className:"villain-overlay villain-overlay--canvas"},React__default.createElement(Icon$1,{className:"villain-icon",path:t,size:3}),React__default.createElement("div",{className:"villain-overlay--message"},React__default.createElement("h3",null,React__default.createElement(LocalizedConsumer,{value:i}))))}),Loader=React__default.memo(({id:e})=>React__default.createElement("div",{className:"villain-overlay",id:e},React__default.createElement("div",{className:"villain-loader-indicator"})));var mdiBookOpen="M13,12H20V13.5H13M13,9.5H20V11H13M13,14.5H20V16H13M21,4H3A2,2 0 0,0 1,6V19A2,2 0 0,0 3,21H21A2,2 0 0,0 23,19V6A2,2 0 0,0 21,4M21,19H12V6H21",mdiBookOpenOutline="M21,4H3A2,2 0 0,0 1,6V19A2,2 0 0,0 3,21H21A2,2 0 0,0 23,19V6A2,2 0 0,0 21,4M3,19V6H11V19H3M21,19H13V6H21V19M14,9.5H20V11H14V9.5M14,12H20V13.5H14V12M14,14.5H20V16H14V14.5Z",mdiBrightness4="M12,18C11.11,18 10.26,17.8 9.5,17.45C11.56,16.5 13,14.42 13,12C13,9.58 11.56,7.5 9.5,6.55C10.26,6.2 11.11,6 12,6A6,6 0 0,1 18,12A6,6 0 0,1 12,18M20,8.69V4H15.31L12,0.69L8.69,4H4V8.69L0.69,12L4,15.31V20H8.69L12,23.31L15.31,20H20V15.31L23.31,12L20,8.69Z",mdiChevronLeft="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z",mdiChevronRight="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z",mdiFileAlert="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M10,18H8V16H10V18M10,14H8V9H10V14M13,9V3.5L18.5,9H13Z",mdiFullscreen="M5,5H10V7H7V10H5V5M14,5H19V10H17V7H14V5M17,14H19V19H14V17H17V14M10,17V19H5V14H7V17H10Z",mdiFullscreenExit="M14,14H19V16H16V19H14V14M5,14H10V19H8V16H5V14M8,5H10V10H5V8H8V5M19,8V10H14V5H16V8H19Z",mdiImageBrokenVariant="M21,5V11.59L18,8.58L14,12.59L10,8.59L6,12.59L3,9.58V5A2,2 0 0,1 5,3H19A2,2 0 0,1 21,5M18,11.42L21,14.43V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V12.42L6,15.41L10,11.41L14,15.41",mdiMinus="M19,13H5V11H19V13Z",mdiPagePrevious="M4,21H19A2,2 0 0,0 21,19V13H17V15L13,12L17,9V11H21V5A2,2 0 0,0 19,3H4A2,2 0 0,0 2,5V19A2,2 0 0,0 4,21M4,15H8V17H4V15M4,11H11V13H4V11M4,7H11V9H4V7M21,11H24V13H21V11Z",mdiPin="M16,12V4H17V2H7V4H8V12L6,14V16H11.2V22H12.8V16H18V14L16,12Z",mdiPinOff="M2,5.27L3.28,4L20,20.72L18.73,22L12.8,16.07V22H11.2V16H6V14L8,12V11.27L2,5.27M16,12L18,14V16H17.82L8,6.18V4H7V2H17V4H16V12Z",mdiPlus="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z",mdiRadioboxBlank="M12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z",mdiRadioboxMarked="M12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7Z",mdiSettings="M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z",mdiTranslate="M12.87,15.07L10.33,12.56L10.36,12.53C12.1,10.59 13.34,8.36 14.07,6H17V4H10V2H8V4H1V6H12.17C11.5,7.92 10.44,9.75 9,11.35C8.07,10.32 7.3,9.19 6.69,8H4.69C5.42,9.63 6.42,11.17 7.67,12.56L2.58,17.58L4,19L9,14L12.11,17.11L12.87,15.07M18.5,10H16.5L12,22H14L15.12,19H19.87L21,22H23L18.5,10M15.88,17L17.5,12.67L19.12,17H15.88Z";const Uncompress=React__default.memo(({source:e=null,workerUrl:t=null,children:i,...n})=>{const r=React.useRef(null),{ready:o,error:a,maxPages:s,pages:l,load:c,forceSort:u}=n,h=e=>{console.error(e),n.trigger("error",e.message||e)},d=async e=>{try{const t=await g(e);if(t&&t.length>0){const e=s&&s{const n=await t.file.extract();p(n,i),i===e.length-1&&r.current._worker.terminate()})}else n.trigger("error","Cant open archive"),r.current._worker.terminate()}catch(e){console.error(e),h(e),r.current._worker.terminate()}},p=(e,t)=>{const{size:i,name:r}=e,o={index:t,url:URL.createObjectURL(e),name:r,size:i,type:"image",buildPyramid:!0};n.createPage(o)},g=async e=>{r.current=await Archive.open(e);const t=(await r.current.getFilesArray()).filter(e=>isValidImageType(e.file.name));t.length>1&&u&&t.sort((e,t)=>e.file.name>t.file.name?1:e.file.name0?t:null};return React.useEffect(()=>(Archive.init({workerUrl:t}),()=>{l&&l.length>0&&l.forEach(e=>{URL.revokeObjectURL(e.src)}),r.current&&(r.current._worker.terminate(),r.current=null)}),[]),React.useEffect(()=>{n.clear(),e&&("string"==typeof e&&(e=>{fetchArchive(e,d,h)})(e),e instanceof Blob&&(e=>{d(e)})(e))},[e]),React__default.createElement(React__default.Fragment,null,a&&React__default.createElement(Error$1,{message:a.message||a,icon:mdiFileAlert})||(o?i:React__default.createElement(Loader,null)))}),UncompressConsumer=React__default.memo(e=>React__default.createElement(ReaderContext.Consumer,null,({load:t,error:i,ready:n,pages:r,maxPages:o,forceSort:a,clear:s,trigger:l,createPage:c,updateState:u})=>React__default.createElement(Uncompress,_extends({},e,{load:t,error:i,ready:n,pages:r,clear:s,trigger:l,maxPages:o,forceSort:a,createPage:c,updateCotextState:u}))));Uncompress.propTypes={source:propTypes.oneOfType([propTypes.string,propTypes.instanceOf(Blob)]),workerUrl:propTypes.string};var openseadragon=createCommonjsModule((function(module){function OpenSeadragon(e){return new OpenSeadragon.Viewer(e)}var root,factory,$,fullScreenApi;!function(e){e.version={versionStr:"2.4.1",major:parseInt("2",10),minor:parseInt("4",10),revision:parseInt("1",10)};var t,i={"[object Boolean]":"boolean","[object Number]":"number","[object String]":"string","[object Function]":"function","[object Array]":"array","[object Date]":"date","[object RegExp]":"regexp","[object Object]":"object"},n=Object.prototype.toString,r=Object.prototype.hasOwnProperty;e.isFunction=function(t){return"function"===e.type(t)},e.isArray=Array.isArray||function(t){return"array"===e.type(t)},e.isWindow=function(e){return e&&"object"==typeof e&&"setInterval"in e},e.type=function(e){return null==e?String(e):i[n.call(e)]||"object"},e.isPlainObject=function(t){if(!t||"object"!==OpenSeadragon.type(t)||t.nodeType||e.isWindow(t))return!1;if(t.constructor&&!r.call(t,"constructor")&&!r.call(t.constructor.prototype,"isPrototypeOf"))return!1;var i;for(var n in t)i=n;return void 0===i||r.call(t,i)},e.isEmptyObject=function(e){for(var t in e)return!1;return!0},e.freezeObject=function(t){return Object.freeze?e.freezeObject=Object.freeze:e.freezeObject=function(e){return e},e.freezeObject(t)},e.supportsCanvas=(t=document.createElement("canvas"),!(!e.isFunction(t.getContext)||!t.getContext("2d"))),e.isCanvasTainted=function(e){var t=!1;try{e.getContext("2d").getImageData(0,0,1,1)}catch(e){t=!0}return t},e.pixelDensityRatio=function(){if(e.supportsCanvas){var t=document.createElement("canvas").getContext("2d"),i=window.devicePixelRatio||1,n=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1;return Math.max(i,1)/n}return 1}()}(OpenSeadragon),function($){$.extend=function(){var e,t,i,n,r,o,a=arguments[0]||{},s=arguments.length,l=!1,c=1;for("boolean"==typeof a&&(l=a,a=arguments[1]||{},c=2),"object"==typeof a||OpenSeadragon.isFunction(a)||(a={}),s===c&&(a=this,--c);c=i.x&&t.x=i.y},getEvent:function(e){return $.getEvent=e?function(e){return e}:function(){return window.event},$.getEvent(e)},getMousePosition:function(e){if("number"==typeof e.pageX)$.getMousePosition=function(e){var t=new $.Point;return e=$.getEvent(e),t.x=e.pageX,t.y=e.pageY,t};else{if("number"!=typeof e.clientX)throw new Error("Unknown event mouse position, no known technique.");$.getMousePosition=function(e){var t=new $.Point;return e=$.getEvent(e),t.x=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,t.y=e.clientY+document.body.scrollTop+document.documentElement.scrollTop,t}}return $.getMousePosition(e)},getPageScroll:function(){var e=document.documentElement||{},t=document.body||{};if("number"==typeof window.pageXOffset)$.getPageScroll=function(){return new $.Point(window.pageXOffset,window.pageYOffset)};else if(t.scrollLeft||t.scrollTop)$.getPageScroll=function(){return new $.Point(document.body.scrollLeft,document.body.scrollTop)};else{if(!e.scrollLeft&&!e.scrollTop)return new $.Point(0,0);$.getPageScroll=function(){return new $.Point(document.documentElement.scrollLeft,document.documentElement.scrollTop)}}return $.getPageScroll()},setPageScroll:function(e){if(void 0!==window.scrollTo)$.setPageScroll=function(e){window.scrollTo(e.x,e.y)};else{var t=$.getPageScroll();if(t.x===e.x&&t.y===e.y)return;document.body.scrollLeft=e.x,document.body.scrollTop=e.y;var i=$.getPageScroll();if(i.x!==t.x&&i.y!==t.y)return void($.setPageScroll=function(e){document.body.scrollLeft=e.x,document.body.scrollTop=e.y});if(document.documentElement.scrollLeft=e.x,document.documentElement.scrollTop=e.y,(i=$.getPageScroll()).x!==t.x&&i.y!==t.y)return void($.setPageScroll=function(e){document.documentElement.scrollLeft=e.x,document.documentElement.scrollTop=e.y});$.setPageScroll=function(e){}}return $.setPageScroll(e)},getWindowSize:function(){var e=document.documentElement||{},t=document.body||{};if("number"==typeof window.innerWidth)$.getWindowSize=function(){return new $.Point(window.innerWidth,window.innerHeight)};else if(e.clientWidth||e.clientHeight)$.getWindowSize=function(){return new $.Point(document.documentElement.clientWidth,document.documentElement.clientHeight)};else{if(!t.clientWidth&&!t.clientHeight)throw new Error("Unknown window size, no known technique.");$.getWindowSize=function(){return new $.Point(document.body.clientWidth,document.body.clientHeight)}}return $.getWindowSize()},makeCenteredNode:function(e){e=$.getElement(e);var t=[$.makeNeutralElement("div"),$.makeNeutralElement("div"),$.makeNeutralElement("div")];return $.extend(t[0].style,{display:"table",height:"100%",width:"100%"}),$.extend(t[1].style,{display:"table-row"}),$.extend(t[2].style,{display:"table-cell",verticalAlign:"middle",textAlign:"center"}),t[0].appendChild(t[1]),t[1].appendChild(t[2]),t[2].appendChild(e),t[0]},makeNeutralElement:function(e){var t=document.createElement(e),i=t.style;return i.background="transparent none",i.border="none",i.margin="0px",i.padding="0px",i.position="static",t},now:function(){return Date.now?$.now=Date.now:$.now=function(){return(new Date).getTime()},$.now()},makeTransparentImage:function(e){return $.makeTransparentImage=function(e){var t=$.makeNeutralElement("img");return t.src=e,t},$.Browser.vendor==$.BROWSERS.IE&&$.Browser.version<7&&($.makeTransparentImage=function(e){var t=$.makeNeutralElement("img"),i=null;return(i=$.makeNeutralElement("span")).style.display="inline-block",t.onload=function(){i.style.width=i.style.width||t.width+"px",i.style.height=i.style.height||t.height+"px",t.onload=null,t=null},t.src=e,i.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+e+"', sizingMethod='scale')",i}),$.makeTransparentImage(e)},setElementOpacity:function(e,t,i){var n;e=$.getElement(e),i&&!$.Browser.alpha&&(t=Math.round(t)),$.Browser.opacity?e.style.opacity=t<1?t:"":t<1?(n="alpha(opacity="+Math.round(100*t)+")",e.style.filter=n):e.style.filter=""},setElementTouchActionNone:function(e){void 0!==(e=$.getElement(e)).style.touchAction?e.style.touchAction="none":void 0!==e.style.msTouchAction&&(e.style.msTouchAction="none")},addClass:function(e,t){(e=$.getElement(e)).className?-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=" "+t):e.className=t},indexOf:function(e,t,i){return Array.prototype.indexOf?this.indexOf=function(e,t,i){return e.indexOf(t,i)}:this.indexOf=function(e,t,i){var n,r,o=i||0;if(!e)throw new TypeError;if(0===(r=e.length)||o>=r)return-1;for(o<0&&(o=r-Math.abs(o)),n=o;n=200&&s.status<300||0===s.status&&"http:"!==a&&"https:"!==a?t(s):($.console.log("AJAX request returned %d: %s",s.status,e),$.isFunction(i)&&i(s)))};try{if(s.open("GET",e,!0),o&&(s.responseType=o),r)for(var l in r)r.hasOwnProperty(l)&&r[l]&&s.setRequestHeader(l,r[l]);n&&(s.withCredentials=!0),s.send(null)}catch(n){var c=n.message;if($.Browser.vendor==$.BROWSERS.IE&&$.Browser.version<10&&void 0!==n.number&&-2147024891==n.number&&(c+="\nSee http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx#xdomain"),$.console.log("%s while making AJAX request: %s",n.name,c),s.onreadystatechange=function(){},window.XDomainRequest){var u=new XDomainRequest;if(u){u.onload=function(e){$.isFunction(t)&&t({responseText:u.responseText,status:200,statusText:"OK"})},u.onerror=function(e){$.isFunction(i)&&i({responseText:u.responseText,status:444,statusText:"An error happened. Due to an XDomainRequest deficiency we can not extract any information about this error. Upgrade your browser."})};try{u.open("GET",e),u.send()}catch(e){$.isFunction(i)&&i(s,n)}}}else $.isFunction(i)&&i(s,n)}return s},jsonp:function(e){var t,i=e.url,n=document.head||document.getElementsByTagName("head")[0]||document.documentElement,r=e.callbackName||"openseadragon"+$.now(),o=window[r],a="$1"+r+"$2",s=e.param||"callback",l=e.callback;i=i.replace(/(\=)\?(&|$)|\?\?/i,a),i+=(/\?/.test(i)?"&":"?")+s+"="+r,window[r]=function(e){if(o)window[r]=o;else try{delete window[r]}catch(e){}l&&$.isFunction(l)&&l(e)},t=document.createElement("script"),void 0===e.async&&!1===e.async||(t.async="async"),e.scriptCharset&&(t.charset=e.scriptCharset),t.src=i,t.onload=t.onreadystatechange=function(e,i){(i||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,n&&t.parentNode&&n.removeChild(t),t=void 0)},n.insertBefore(t,n.firstChild)},createFromDZI:function(){throw"OpenSeadragon.createFromDZI is deprecated, use Viewer.open."},parseXml:function(e){if(window.DOMParser)$.parseXml=function(e){return(new DOMParser).parseFromString(e,"text/xml")};else{if(!window.ActiveXObject)throw new Error("Browser doesn't support XML DOM.");$.parseXml=function(e){var t=null;return(t=new ActiveXObject("Microsoft.XMLDOM")).async=!1,t.loadXML(e),t}}return $.parseXml(e)},parseJSON:function(string){return window.JSON&&window.JSON.parse?$.parseJSON=window.JSON.parse:$.parseJSON=function(string){return eval("("+string+")")},$.parseJSON(string)},imageFormatSupported:function(e){return!!FILEFORMATS[(e=e||"").toLowerCase()]}}),$.Browser={vendor:$.BROWSERS.UNKNOWN,version:0,alpha:!0};var FILEFORMATS={bmp:!1,jpeg:!0,jpg:!0,png:!0,tif:!1,wdp:!1},URLPARAMS={};!function(){var e=navigator.appVersion,t=navigator.userAgent;switch(navigator.appName){case"Microsoft Internet Explorer":window.attachEvent&&window.ActiveXObject&&($.Browser.vendor=$.BROWSERS.IE,$.Browser.version=parseFloat(t.substring(t.indexOf("MSIE")+5,t.indexOf(";",t.indexOf("MSIE")))));break;case"Netscape":window.addEventListener&&(t.indexOf("Firefox")>=0?($.Browser.vendor=$.BROWSERS.FIREFOX,$.Browser.version=parseFloat(t.substring(t.indexOf("Firefox")+8))):t.indexOf("Safari")>=0?($.Browser.vendor=t.indexOf("Chrome")>=0?$.BROWSERS.CHROME:$.BROWSERS.SAFARI,$.Browser.version=parseFloat(t.substring(t.substring(0,t.indexOf("Safari")).lastIndexOf("/")+1,t.indexOf("Safari")))):null!==new RegExp("Trident/.*rv:([0-9]{1,}[.0-9]{0,})").exec(t)&&($.Browser.vendor=$.BROWSERS.IE,$.Browser.version=parseFloat(RegExp.$1)));break;case"Opera":$.Browser.vendor=$.BROWSERS.OPERA,$.Browser.version=parseFloat(e)}var i,n,r,o=window.location.search.substring(1).split("&");for(r=0;r0&&(URLPARAMS[i.substring(0,n)]=decodeURIComponent(i.substring(n+1)));$.Browser.alpha=!($.Browser.vendor==$.BROWSERS.IE&&$.Browser.version<9||$.Browser.vendor==$.BROWSERS.CHROME&&$.Browser.version<2),$.Browser.opacity=!($.Browser.vendor==$.BROWSERS.IE&&$.Browser.version<9)}();var nullfunction=function(e){};function getOffsetParent(e,t){return t&&e!=document.body?document.body:e.offsetParent}$.console=window.console||{log:nullfunction,debug:nullfunction,info:nullfunction,warn:nullfunction,error:nullfunction,assert:nullfunction},function(e){var t=e.requestAnimationFrame||e.mozRequestAnimationFrame||e.webkitRequestAnimationFrame||e.msRequestAnimationFrame,i=e.cancelAnimationFrame||e.mozCancelAnimationFrame||e.webkitCancelAnimationFrame||e.msCancelAnimationFrame;if(t&&i)$.requestAnimationFrame=function(){return t.apply(e,arguments)},$.cancelAnimationFrame=function(){return i.apply(e,arguments)};else{var n,r=[],o=[],a=0;$.requestAnimationFrame=function(e){return r.push([++a,e]),n||(n=setInterval((function(){if(r.length){var e=$.now(),t=o;for(o=r,r=t;o.length;)o.shift()[1](e)}else clearInterval(n),n=void 0}),20)),a},$.cancelAnimationFrame=function(e){var t,i;for(t=0,i=r.length;t0&&(e.removeEvent(e.MouseTracker.captureElement,"mousemove",n.mousemovecaptured,!0),e.removeEvent(e.MouseTracker.captureElement,"mouseup",n.mouseupcaptured,!0),e.removeEvent(e.MouseTracker.captureElement,e.MouseTracker.unprefixedPointerEvents?"pointermove":"MSPointerMove",n.pointermovecaptured,!0),e.removeEvent(e.MouseTracker.captureElement,e.MouseTracker.unprefixedPointerEvents?"pointerup":"MSPointerUp",n.pointerupcaptured,!0),e.removeEvent(e.MouseTracker.captureElement,"touchmove",n.touchmovecaptured,!0),e.removeEvent(e.MouseTracker.captureElement,"touchend",n.touchendcaptured,!0),n.activePointersLists[i].captureCount=0);for(i=0;i0){for(n=0;n0&&(fe(e,t,o,0),i.captureCount=1,p(e,i.type),ge(e,t,o))}}function W(t,i){var n,r,o,a,l=i.changedTouches.length,c=[],u=t.getActivePointersListByType("touch");for(n=e.now(),u.getLength()>i.touches.length-l&&(e.console.warn("Tracked touch contact count doesn't match event.touches.length. Removing all tracked touch pointers."),U(t,i,u)),r=0;r8||"onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll",e.MouseTracker.supportsMouseCapture=(a=document.createElement("div"),e.isFunction(a.setCapture)&&e.isFunction(a.releaseCapture)),e.MouseTracker.subscribeEvents=["click","dblclick","keydown","keyup","keypress","focus","blur",e.MouseTracker.wheelEventName],"DOMMouseScroll"==e.MouseTracker.wheelEventName&&e.MouseTracker.subscribeEvents.push("MozMousePixelScroll"),window.PointerEvent&&(window.navigator.pointerEnabled||e.Browser.vendor!==e.BROWSERS.IE)?(e.MouseTracker.havePointerEvents=!0,e.MouseTracker.subscribeEvents.push("pointerover","pointerout","pointerdown","pointerup","pointermove","pointercancel"),e.MouseTracker.unprefixedPointerEvents=!0,navigator.maxTouchPoints?e.MouseTracker.maxTouchPoints=navigator.maxTouchPoints:e.MouseTracker.maxTouchPoints=0,e.MouseTracker.haveMouseEnter=!1):window.MSPointerEvent&&window.navigator.msPointerEnabled?(e.MouseTracker.havePointerEvents=!0,e.MouseTracker.subscribeEvents.push("MSPointerOver","MSPointerOut","MSPointerDown","MSPointerUp","MSPointerMove","MSPointerCancel"),e.MouseTracker.unprefixedPointerEvents=!1,navigator.msMaxTouchPoints?e.MouseTracker.maxTouchPoints=navigator.msMaxTouchPoints:e.MouseTracker.maxTouchPoints=0,e.MouseTracker.haveMouseEnter=!1):(e.MouseTracker.havePointerEvents=!1,e.Browser.vendor===e.BROWSERS.IE&&e.Browser.version<9?(e.MouseTracker.subscribeEvents.push("mouseenter","mouseleave"),e.MouseTracker.haveMouseEnter=!0):(e.MouseTracker.subscribeEvents.push("mouseover","mouseout"),e.MouseTracker.haveMouseEnter=!1),e.MouseTracker.subscribeEvents.push("mousedown","mouseup","mousemove"),"ontouchstart"in window&&e.MouseTracker.subscribeEvents.push("touchstart","touchend","touchmove","touchcancel"),"ongesturestart"in window&&e.MouseTracker.subscribeEvents.push("gesturestart","gesturechange"),e.MouseTracker.mousePointerId="legacy-mouse",e.MouseTracker.maxTouchPoints=10),e.MouseTracker.GesturePointList=function(e){this._gPoints=[],this.type=e,this.buttons=0,this.contacts=0,this.clicks=0,this.captureCount=0},e.MouseTracker.GesturePointList.prototype={getLength:function(){return this._gPoints.length},asArray:function(){return this._gPoints},add:function(e){return this._gPoints.push(e)},removeById:function(e){var t,i=this._gPoints.length;for(t=0;t1&&("mouse"===this.type||"pen"===this.type)&&(this.contacts=1)},removeContact:function(){--this.contacts,this.contacts<0&&(this.contacts=0)}};var ye=function(){try{return window.self!==window.top}catch(e){return!0}}();function we(e){try{return e.addEventListener&&e.removeEventListener}catch(e){return!1}}}(OpenSeadragon),function(e){e.ControlAnchor={NONE:0,TOP_LEFT:1,TOP_RIGHT:2,BOTTOM_RIGHT:3,BOTTOM_LEFT:4,ABSOLUTE:5},e.Control=function(t,i,n){var r=t.parentNode;"number"==typeof i&&(e.console.error("Passing an anchor directly into the OpenSeadragon.Control constructor is deprecated; please use an options object instead. Support for this deprecated variant is scheduled for removal in December 2013"),i={anchor:i}),i.attachToViewer=void 0===i.attachToViewer||i.attachToViewer,this.autoFade=void 0===i.autoFade||i.autoFade,this.element=t,this.anchor=i.anchor,this.container=n,this.anchor==e.ControlAnchor.ABSOLUTE?(this.wrapper=e.makeNeutralElement("div"),this.wrapper.style.position="absolute",this.wrapper.style.top="number"==typeof i.top?i.top+"px":i.top,this.wrapper.style.left="number"==typeof i.left?i.left+"px":i.left,this.wrapper.style.height="number"==typeof i.height?i.height+"px":i.height,this.wrapper.style.width="number"==typeof i.width?i.width+"px":i.width,this.wrapper.style.margin="0px",this.wrapper.style.padding="0px",this.element.style.position="relative",this.element.style.top="0px",this.element.style.left="0px",this.element.style.height="100%",this.element.style.width="100%"):(this.wrapper=e.makeNeutralElement("div"),this.wrapper.style.display="inline-block",this.anchor==e.ControlAnchor.NONE&&(this.wrapper.style.width=this.wrapper.style.height="100%")),this.wrapper.appendChild(this.element),i.attachToViewer?this.anchor==e.ControlAnchor.TOP_RIGHT||this.anchor==e.ControlAnchor.BOTTOM_RIGHT?this.container.insertBefore(this.wrapper,this.container.firstChild):this.container.appendChild(this.wrapper):r.appendChild(this.wrapper)},e.Control.prototype={destroy:function(){this.wrapper.removeChild(this.element),this.container.removeChild(this.wrapper)},isVisible:function(){return"none"!=this.wrapper.style.display},setVisible:function(t){this.wrapper.style.display=t?this.anchor==e.ControlAnchor.ABSOLUTE?"block":"inline-block":"none"},setOpacity:function(t){this.element[e.SIGNAL]&&e.Browser.vendor==e.BROWSERS.IE?e.setElementOpacity(this.element,t,!0):e.setElementOpacity(this.wrapper,t,!0)}}}(OpenSeadragon),function(e){function t(e,t){var i,n=e.controls;for(i=n.length-1;i>=0;i--)if(n[i].element==t)return i;return-1}e.ControlDock=function(t){var i,n,r=["topleft","topright","bottomright","bottomleft"];for(e.extend(!0,this,{id:"controldock-"+e.now()+"-"+Math.floor(1e6*Math.random()),container:e.makeNeutralElement("div"),controls:[]},t),this.container.onsubmit=function(){return!1},this.element&&(this.element=e.getElement(this.element),this.element.appendChild(this.container),this.element.style.position="relative",this.container.style.width="100%",this.container.style.height="100%"),n=0;n=0)){switch(n.anchor){case e.ControlAnchor.TOP_RIGHT:r=this.controls.topright,i.style.position="relative",i.style.paddingRight="0px",i.style.paddingTop="0px";break;case e.ControlAnchor.BOTTOM_RIGHT:r=this.controls.bottomright,i.style.position="relative",i.style.paddingRight="0px",i.style.paddingBottom="0px";break;case e.ControlAnchor.BOTTOM_LEFT:r=this.controls.bottomleft,i.style.position="relative",i.style.paddingLeft="0px",i.style.paddingBottom="0px";break;case e.ControlAnchor.TOP_LEFT:r=this.controls.topleft,i.style.position="relative",i.style.paddingLeft="0px",i.style.paddingTop="0px";break;case e.ControlAnchor.ABSOLUTE:r=this.container,i.style.margin="0px",i.style.padding="0px";break;default:case e.ControlAnchor.NONE:r=this.container,i.style.margin="0px",i.style.padding="0px"}this.controls.push(new e.Control(i,n,r)),i.style.display="inline-block"}},removeControl:function(i){var n=t(this,i=e.getElement(i));return n>=0&&(this.controls[n].destroy(),this.controls.splice(n,1)),this},clearControls:function(){for(;this.controls.length>0;)this.controls.pop().destroy();return this},areControlsEnabled:function(){var e;for(e=this.controls.length-1;e>=0;e--)if(this.controls[e].isVisible())return!0;return!1},setControlsEnabled:function(e){var t;for(t=this.controls.length-1;t>=0;t--)this.controls[t].setVisible(e);return this}}}(OpenSeadragon),function(e){e.Placement=e.freezeObject({CENTER:0,TOP_LEFT:1,TOP:2,TOP_RIGHT:3,RIGHT:4,BOTTOM_RIGHT:5,BOTTOM:6,BOTTOM_LEFT:7,LEFT:8,properties:{0:{isLeft:!1,isHorizontallyCentered:!0,isRight:!1,isTop:!1,isVerticallyCentered:!0,isBottom:!1},1:{isLeft:!0,isHorizontallyCentered:!1,isRight:!1,isTop:!0,isVerticallyCentered:!1,isBottom:!1},2:{isLeft:!1,isHorizontallyCentered:!0,isRight:!1,isTop:!0,isVerticallyCentered:!1,isBottom:!1},3:{isLeft:!1,isHorizontallyCentered:!1,isRight:!0,isTop:!0,isVerticallyCentered:!1,isBottom:!1},4:{isLeft:!1,isHorizontallyCentered:!1,isRight:!0,isTop:!1,isVerticallyCentered:!0,isBottom:!1},5:{isLeft:!1,isHorizontallyCentered:!1,isRight:!0,isTop:!1,isVerticallyCentered:!1,isBottom:!0},6:{isLeft:!1,isHorizontallyCentered:!0,isRight:!1,isTop:!1,isVerticallyCentered:!1,isBottom:!0},7:{isLeft:!0,isHorizontallyCentered:!1,isRight:!1,isTop:!1,isVerticallyCentered:!1,isBottom:!0},8:{isLeft:!0,isHorizontallyCentered:!1,isRight:!1,isTop:!1,isVerticallyCentered:!0,isBottom:!1}}})}(OpenSeadragon),function(e){var t={},i=1;function n(t){return t=e.getElement(t),new e.Point(0===t.clientWidth?1:t.clientWidth,0===t.clientHeight?1:t.clientHeight)}function r(t,i){if(i instanceof e.Overlay)return i;var n=null;if(i.element)n=e.getElement(i.element);else{var r=i.id?i.id:"openseadragon-overlay-"+Math.floor(1e7*Math.random());(n=e.getElement(i.id))||((n=document.createElement("a")).href="#/overlay/"+r),n.id=r,e.addClass(n,i.className?i.className:"openseadragon-overlay")}var o=i.location,a=i.width,s=i.height;if(!o){var l=i.x,c=i.y;if(void 0!==i.px){var u=t.viewport.imageToViewportRectangle(new e.Rect(i.px,i.py,a||0,s||0));l=u.x,c=u.y,a=void 0!==a?u.width:void 0,s=void 0!==s?u.height:void 0}o=new e.Point(l,c)}var h=i.placement;return h&&"string"===e.type(h)&&(h=e.Placement[i.placement.toUpperCase()]),new e.Overlay({element:n,location:o,placement:h,onDraw:i.onDraw,checkResize:i.checkResize,width:a,height:s,rotationMode:i.rotationMode})}function o(e,t){var i;for(i=e.length-1;i>=0;i--)if(e[i].element===t)return i;return-1}function a(t,i){return e.requestAnimationFrame((function(){i(t)}))}function s(t){e.requestAnimationFrame((function(){!function(t){var i,n,r,o;if(t.controlsShouldFade){for(i=e.now(),n=i-t.controlsFadeBeginTime,r=1-n/t.controlsFadeLength,r=Math.min(1,r),r=Math.max(0,r),o=t.controls.length-1;o>=0;o--)t.controls[o].autoFade&&t.controls[o].setOpacity(r);r>0&&s(t)}}(t)}))}function l(t){t.autoHideControls&&(t.controlsShouldFade=!0,t.controlsFadeBeginTime=e.now()+t.controlsFadeDelay,window.setTimeout((function(){s(t)}),t.controlsFadeDelay))}function c(e){var t;for(e.controlsShouldFade=!1,t=e.controls.length-1;t>=0;t--)e.controls[t].setOpacity(1)}function u(){c(this)}function h(){l(this)}function d(t){var i={originalEvent:t.originalEvent,preventDefaultAction:t.preventDefaultAction,preventVerticalPan:t.preventVerticalPan,preventHorizontalPan:t.preventHorizontalPan};if(this.raiseEvent("canvas-key",i),i.preventDefaultAction||t.ctrl||t.alt||t.meta)return!0;switch(t.keyCode){case 38:return i.preventVerticalPan||(t.shift?this.viewport.zoomBy(1.1):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(0,-this.pixelsPerArrowPress))),this.viewport.applyConstraints()),!1;case 40:return i.preventVerticalPan||(t.shift?this.viewport.zoomBy(.9):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(0,this.pixelsPerArrowPress))),this.viewport.applyConstraints()),!1;case 37:return i.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(-this.pixelsPerArrowPress,0))),this.viewport.applyConstraints()),!1;case 39:return i.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(this.pixelsPerArrowPress,0))),this.viewport.applyConstraints()),!1;default:return!0}}function p(t){var i={originalEvent:t.originalEvent,preventDefaultAction:t.preventDefaultAction,preventVerticalPan:t.preventVerticalPan,preventHorizontalPan:t.preventHorizontalPan};if(this.raiseEvent("canvas-key",i),i.preventDefaultAction||t.ctrl||t.alt||t.meta)return!0;switch(t.keyCode){case 43:case 61:return this.viewport.zoomBy(1.1),this.viewport.applyConstraints(),!1;case 45:return this.viewport.zoomBy(.9),this.viewport.applyConstraints(),!1;case 48:return this.viewport.goHome(),this.viewport.applyConstraints(),!1;case 119:case 87:return i.preventVerticalPan||(t.shift?this.viewport.zoomBy(1.1):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(0,-40))),this.viewport.applyConstraints()),!1;case 115:case 83:return i.preventVerticalPan||(t.shift?this.viewport.zoomBy(.9):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(0,40))),this.viewport.applyConstraints()),!1;case 97:return i.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(-40,0))),this.viewport.applyConstraints()),!1;case 100:return i.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new e.Point(40,0))),this.viewport.applyConstraints()),!1;case 114:return this.viewport.flipped?this.viewport.setRotation(e.positiveModulo(this.viewport.degrees-this.rotationIncrement,360)):this.viewport.setRotation(e.positiveModulo(this.viewport.degrees+this.rotationIncrement,360)),this.viewport.applyConstraints(),!1;case 82:return this.viewport.flipped?this.viewport.setRotation(e.positiveModulo(this.viewport.degrees+this.rotationIncrement,360)):this.viewport.setRotation(e.positiveModulo(this.viewport.degrees-this.rotationIncrement,360)),this.viewport.applyConstraints(),!1;case 102:return this.viewport.toggleFlip(),!1;default:return!0}}function g(e){var t;document.activeElement==this.canvas||this.canvas.focus(),this.viewport.flipped&&(e.position.x=this.viewport.getContainerSize().x-e.position.x);var i={tracker:e.eventSource,position:e.position,quick:e.quick,shift:e.shift,originalEvent:e.originalEvent,preventDefaultAction:e.preventDefaultAction};this.raiseEvent("canvas-click",i),!i.preventDefaultAction&&this.viewport&&e.quick&&(t=this.gestureSettingsByDeviceType(e.pointerType)).clickToZoom&&(this.viewport.zoomBy(e.shift?1/this.zoomPerClick:this.zoomPerClick,t.zoomToRefPoint?this.viewport.pointFromPixel(e.position,!0):null),this.viewport.applyConstraints())}function m(e){var t,i={tracker:e.eventSource,position:e.position,shift:e.shift,originalEvent:e.originalEvent,preventDefaultAction:e.preventDefaultAction};this.raiseEvent("canvas-double-click",i),!i.preventDefaultAction&&this.viewport&&(t=this.gestureSettingsByDeviceType(e.pointerType)).dblClickToZoom&&(this.viewport.zoomBy(e.shift?1/this.zoomPerClick:this.zoomPerClick,t.zoomToRefPoint?this.viewport.pointFromPixel(e.position,!0):null),this.viewport.applyConstraints())}function f(e){var t,i={tracker:e.eventSource,position:e.position,delta:e.delta,speed:e.speed,direction:e.direction,shift:e.shift,originalEvent:e.originalEvent,preventDefaultAction:e.preventDefaultAction};if(this.raiseEvent("canvas-drag",i),!i.preventDefaultAction&&this.viewport){if(t=this.gestureSettingsByDeviceType(e.pointerType),this.panHorizontal||(e.delta.x=0),this.panVertical||(e.delta.y=0),this.viewport.flipped&&(e.delta.x=-e.delta.x),this.constrainDuringPan){var n=this.viewport.deltaPointsFromPixels(e.delta.negate());this.viewport.centerSpringX.target.value+=n.x,this.viewport.centerSpringY.target.value+=n.y;var r=this.viewport.getBounds(),o=this.viewport.getConstrainedBounds();this.viewport.centerSpringX.target.value-=n.x,this.viewport.centerSpringY.target.value-=n.y,r.x!=o.x&&(e.delta.x=0),r.y!=o.y&&(e.delta.y=0)}this.viewport.panBy(this.viewport.deltaPointsFromPixels(e.delta.negate()),t.flickEnabled&&!this.constrainDuringPan)}}function v(t){if(!t.preventDefaultAction&&this.viewport){var i=this.gestureSettingsByDeviceType(t.pointerType);if(i.flickEnabled&&t.speed>=i.flickMinSpeed){var n=0;this.panHorizontal&&(n=i.flickMomentum*t.speed*Math.cos(t.direction));var r=0;this.panVertical&&(r=i.flickMomentum*t.speed*Math.sin(t.direction));var o=this.viewport.pixelFromPoint(this.viewport.getCenter(!0)),a=this.viewport.pointFromPixel(new e.Point(o.x-n,o.y-r));this.viewport.panTo(a,!1)}this.viewport.applyConstraints()}this.raiseEvent("canvas-drag-end",{tracker:t.eventSource,position:t.position,speed:t.speed,direction:t.direction,shift:t.shift,originalEvent:t.originalEvent})}function y(e){this.raiseEvent("canvas-enter",{tracker:e.eventSource,pointerType:e.pointerType,position:e.position,buttons:e.buttons,pointers:e.pointers,insideElementPressed:e.insideElementPressed,buttonDownAny:e.buttonDownAny,originalEvent:e.originalEvent})}function w(t){window.location!=window.parent.location&&e.MouseTracker.resetAllMouseTrackers(),this.raiseEvent("canvas-exit",{tracker:t.eventSource,pointerType:t.pointerType,position:t.position,buttons:t.buttons,pointers:t.pointers,insideElementPressed:t.insideElementPressed,buttonDownAny:t.buttonDownAny,originalEvent:t.originalEvent})}function _(e){this.raiseEvent("canvas-press",{tracker:e.eventSource,pointerType:e.pointerType,position:e.position,insideElementPressed:e.insideElementPressed,insideElementReleased:e.insideElementReleased,originalEvent:e.originalEvent})}function T(e){this.raiseEvent("canvas-release",{tracker:e.eventSource,pointerType:e.pointerType,position:e.position,insideElementPressed:e.insideElementPressed,insideElementReleased:e.insideElementReleased,originalEvent:e.originalEvent})}function S(e){this.raiseEvent("canvas-nonprimary-press",{tracker:e.eventSource,position:e.position,pointerType:e.pointerType,button:e.button,buttons:e.buttons,originalEvent:e.originalEvent})}function x(e){this.raiseEvent("canvas-nonprimary-release",{tracker:e.eventSource,position:e.position,pointerType:e.pointerType,button:e.button,buttons:e.buttons,originalEvent:e.originalEvent})}function b(e){var t,i,n;if(!e.preventDefaultAction&&this.viewport&&((t=this.gestureSettingsByDeviceType(e.pointerType)).pinchToZoom&&(i=this.viewport.pointFromPixel(e.center,!0),n=this.viewport.pointFromPixel(e.lastCenter,!0).minus(i),this.panHorizontal||(n.x=0),this.panVertical||(n.y=0),this.viewport.zoomBy(e.distance/e.lastDistance,i,!0),t.zoomToRefPoint&&this.viewport.panBy(n,!0),this.viewport.applyConstraints()),t.pinchRotate)){var r=Math.atan2(e.gesturePoints[0].currentPos.y-e.gesturePoints[1].currentPos.y,e.gesturePoints[0].currentPos.x-e.gesturePoints[1].currentPos.x),o=Math.atan2(e.gesturePoints[0].lastPos.y-e.gesturePoints[1].lastPos.y,e.gesturePoints[0].lastPos.x-e.gesturePoints[1].lastPos.x);this.viewport.setRotation(this.viewport.getRotation()+(r-o)*(180/Math.PI))}return this.raiseEvent("canvas-pinch",{tracker:e.eventSource,gesturePoints:e.gesturePoints,lastCenter:e.lastCenter,center:e.center,lastDistance:e.lastDistance,distance:e.distance,shift:e.shift,originalEvent:e.originalEvent}),!1}function E(t){var i,n,r;if((r=e.now())-this._lastScrollTime>this.minScrollDeltaTime){if(this._lastScrollTime=r,this.viewport.flipped&&(t.position.x=this.viewport.getContainerSize().x-t.position.x),!t.preventDefaultAction&&this.viewport&&(i=this.gestureSettingsByDeviceType(t.pointerType)).scrollToZoom&&(n=Math.pow(this.zoomPerScroll,t.scroll),this.viewport.zoomBy(n,i.zoomToRefPoint?this.viewport.pointFromPixel(t.position,!0):null),this.viewport.applyConstraints()),this.raiseEvent("canvas-scroll",{tracker:t.eventSource,position:t.position,scroll:t.scroll,shift:t.shift,originalEvent:t.originalEvent}),i&&i.scrollToZoom)return!1}else if((i=this.gestureSettingsByDeviceType(t.pointerType))&&i.scrollToZoom)return!1}function P(e){t[this.hash].mouseInside=!0,c(this),this.raiseEvent("container-enter",{tracker:e.eventSource,position:e.position,buttons:e.buttons,pointers:e.pointers,insideElementPressed:e.insideElementPressed,buttonDownAny:e.buttonDownAny,originalEvent:e.originalEvent})}function R(e){e.pointers<1&&(t[this.hash].mouseInside=!1,t[this.hash].animating||l(this)),this.raiseEvent("container-exit",{tracker:e.eventSource,position:e.position,buttons:e.buttons,pointers:e.pointers,insideElementPressed:e.insideElementPressed,buttonDownAny:e.buttonDownAny,originalEvent:e.originalEvent})}function C(e){!function(e){if(e._opening)return;if(e.autoResize){var i=n(e.container),r=t[e.hash].prevContainerSize;if(!i.equals(r)){var o=e.viewport;if(e.preserveImageSizeOnResize){var a=r.x/i.x,s=o.getZoom()*a,u=o.getCenter();o.resize(i,!1),o.zoomTo(s,null,!0),o.panTo(u,!0)}else{var h=o.getBounds();o.resize(i,!0),o.fitBoundsWithConstraints(h,!0)}t[e.hash].prevContainerSize=i,t[e.hash].forceRedraw=!0}}var d=e.viewport.update(),p=e.world.update()||d;d&&e.raiseEvent("viewport-change");e.referenceStrip&&(p=e.referenceStrip.update(e.viewport)||p);!t[e.hash].animating&&p&&(e.raiseEvent("animation-start"),c(e));(p||t[e.hash].forceRedraw||e.world.needsDraw())&&(!function(e){e.imageLoader.clear(),e.drawer.clear(),e.world.draw(),e.raiseEvent("update-viewport",{})}(e),e._drawOverlays(),e.navigator&&e.navigator.update(e.viewport),t[e.hash].forceRedraw=!1,p&&e.raiseEvent("animation"));t[e.hash].animating&&!p&&(e.raiseEvent("animation-finish"),t[e.hash].mouseInside||l(e));t[e.hash].animating=p}(e),e.isOpen()?e._updateRequestId=a(e,C):e._updateRequestId=!1}function k(e,t){return e?e+t:t}function O(){t[this.hash].lastZoomTime=e.now(),t[this.hash].zoomFactor=this.zoomPerSecond,t[this.hash].zooming=!0,L(this)}function I(){t[this.hash].lastZoomTime=e.now(),t[this.hash].zoomFactor=1/this.zoomPerSecond,t[this.hash].zooming=!0,L(this)}function M(){t[this.hash].zooming=!1}function L(t){e.requestAnimationFrame(e.delegate(t,A))}function A(){var i,n,r;t[this.hash].zooming&&this.viewport&&(n=(i=e.now())-t[this.hash].lastZoomTime,r=Math.pow(t[this.hash].zoomFactor,n/1e3),this.viewport.zoomBy(r),this.viewport.applyConstraints(),t[this.hash].lastZoomTime=i,L(this))}function D(){this.viewport&&(t[this.hash].zooming=!1,this.viewport.zoomBy(this.zoomPerClick/1),this.viewport.applyConstraints())}function H(){this.viewport&&(t[this.hash].zooming=!1,this.viewport.zoomBy(1/this.zoomPerClick),this.viewport.applyConstraints())}function z(){this.buttons.emulateEnter(),this.buttons.emulateExit()}function B(){this.viewport&&this.viewport.goHome()}function F(){this.isFullPage()&&!e.isFullScreen()?this.setFullPage(!1):this.setFullScreen(!this.isFullPage()),this.buttons&&this.buttons.emulateExit(),this.fullPageButton.element.focus(),this.viewport&&this.viewport.applyConstraints()}function N(){if(this.viewport){var t=this.viewport.getRotation();t=this.viewport.flipped?e.positiveModulo(t+this.rotationIncrement,360):e.positiveModulo(t-this.rotationIncrement,360),this.viewport.setRotation(t)}}function V(){if(this.viewport){var t=this.viewport.getRotation();t=this.viewport.flipped?e.positiveModulo(t-this.rotationIncrement,360):e.positiveModulo(t+this.rotationIncrement,360),this.viewport.setRotation(t)}}function j(){this.viewport.toggleFlip()}function $(){var e=this._sequenceIndex-1;this.navPrevNextWrap&&e<0&&(e+=this.tileSources.length),this.goToPage(e)}function U(){var e=this._sequenceIndex+1;this.navPrevNextWrap&&e>=this.tileSources.length&&(e=0),this.goToPage(e)}e.Viewer=function(r){var o,s,c=arguments,u=this;if(e.isPlainObject(r)||(r={id:c[0],xmlPath:c.length>1?c[1]:void 0,prefixUrl:c.length>2?c[2]:void 0,controls:c.length>3?c[3]:void 0,overlays:c.length>4?c[4]:void 0}),r.config&&(e.extend(!0,r,r.config),delete r.config),e.extend(!0,this,{id:r.id,hash:r.hash||i++,initialPage:0,element:null,container:null,canvas:null,overlays:[],overlaysContainer:null,previousBody:[],customControls:[],source:null,drawer:null,world:null,viewport:null,navigator:null,collectionViewport:null,collectionDrawer:null,navImages:null,buttons:null,profiler:null},e.DEFAULT_SETTINGS,r),void 0===this.hash)throw new Error("A hash must be defined, either by specifying options.id or options.hash.");for(void 0!==t[this.hash]&&e.console.warn("Hash "+this.hash+" has already been used."),t[this.hash]={fsBoundsDelta:new e.Point(1,1),prevContainerSize:null,animating:!1,forceRedraw:!1,mouseInside:!1,group:null,zooming:!1,zoomFactor:null,lastZoomTime:null,fullPage:!1,onfullscreenchange:null},this._sequenceIndex=0,this._firstOpen=!0,this._updateRequestId=null,this._loadQueue=[],this.currentOverlays=[],this._lastScrollTime=e.now(),e.EventSource.call(this),this.addHandler("open-failed",(function(t){var i=e.getString("Errors.OpenFailed",t.eventSource,t.message);u._showMessage(i)})),e.ControlDock.call(this,r),this.xmlPath&&(this.tileSources=[this.xmlPath]),this.element=this.element||document.getElementById(this.id),this.canvas=e.makeNeutralElement("div"),this.canvas.className="openseadragon-canvas",(s=this.canvas.style).width="100%",s.height="100%",s.overflow="hidden",s.position="absolute",s.top="0px",s.left="0px",e.setElementTouchActionNone(this.canvas),""!==r.tabIndex&&(this.canvas.tabIndex=void 0===r.tabIndex?0:r.tabIndex),this.container.className="openseadragon-container",function(e){e.width="100%",e.height="100%",e.position="relative",e.overflow="hidden",e.left="0px",e.top="0px",e.textAlign="left"}(this.container.style),this.container.insertBefore(this.canvas,this.container.firstChild),this.element.appendChild(this.container),this.bodyWidth=document.body.style.width,this.bodyHeight=document.body.style.height,this.bodyOverflow=document.body.style.overflow,this.docOverflow=document.documentElement.style.overflow,this.innerTracker=new e.MouseTracker({element:this.canvas,startDisabled:!this.mouseNavEnabled,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,dblClickTimeThreshold:this.dblClickTimeThreshold,dblClickDistThreshold:this.dblClickDistThreshold,keyDownHandler:e.delegate(this,d),keyHandler:e.delegate(this,p),clickHandler:e.delegate(this,g),dblClickHandler:e.delegate(this,m),dragHandler:e.delegate(this,f),dragEndHandler:e.delegate(this,v),enterHandler:e.delegate(this,y),exitHandler:e.delegate(this,w),pressHandler:e.delegate(this,_),releaseHandler:e.delegate(this,T),nonPrimaryPressHandler:e.delegate(this,S),nonPrimaryReleaseHandler:e.delegate(this,x),scrollHandler:e.delegate(this,E),pinchHandler:e.delegate(this,b)}),this.outerTracker=new e.MouseTracker({element:this.container,startDisabled:!this.mouseNavEnabled,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,dblClickTimeThreshold:this.dblClickTimeThreshold,dblClickDistThreshold:this.dblClickDistThreshold,enterHandler:e.delegate(this,P),exitHandler:e.delegate(this,R)}),this.toolbar&&(this.toolbar=new e.ControlDock({element:this.toolbar})),this.bindStandardControls(),t[this.hash].prevContainerSize=n(this.container),this.world=new e.World({viewer:this}),this.world.addHandler("add-item",(function(e){u.source=u.world.getItemAt(0).source,t[u.hash].forceRedraw=!0,u._updateRequestId||(u._updateRequestId=a(u,C))})),this.world.addHandler("remove-item",(function(e){u.world.getItemCount()?u.source=u.world.getItemAt(0).source:u.source=null,t[u.hash].forceRedraw=!0})),this.world.addHandler("metrics-change",(function(e){u.viewport&&u.viewport._setContentBounds(u.world.getHomeBounds(),u.world.getContentFactor())})),this.world.addHandler("item-index-change",(function(e){u.source=u.world.getItemAt(0).source})),this.viewport=new e.Viewport({containerSize:t[this.hash].prevContainerSize,springStiffness:this.springStiffness,animationTime:this.animationTime,minZoomImageRatio:this.minZoomImageRatio,maxZoomPixelRatio:this.maxZoomPixelRatio,visibilityRatio:this.visibilityRatio,wrapHorizontal:this.wrapHorizontal,wrapVertical:this.wrapVertical,defaultZoomLevel:this.defaultZoomLevel,minZoomLevel:this.minZoomLevel,maxZoomLevel:this.maxZoomLevel,viewer:this,degrees:this.degrees,flipped:this.flipped,navigatorRotate:this.navigatorRotate,homeFillsViewer:this.homeFillsViewer,margins:this.viewportMargins}),this.viewport._setContentBounds(this.world.getHomeBounds(),this.world.getContentFactor()),this.imageLoader=new e.ImageLoader({jobLimit:this.imageLoaderLimit,timeout:r.timeout}),this.tileCache=new e.TileCache({maxImageCacheCount:this.maxImageCacheCount}),this.drawer=new e.Drawer({viewer:this,viewport:this.viewport,element:this.canvas,debugGridColor:this.debugGridColor}),this.overlaysContainer=e.makeNeutralElement("div"),this.canvas.appendChild(this.overlaysContainer),this.drawer.canRotate()||(this.rotateLeft&&(o=this.buttons.buttons.indexOf(this.rotateLeft),this.buttons.buttons.splice(o,1),this.buttons.element.removeChild(this.rotateLeft.element)),this.rotateRight&&(o=this.buttons.buttons.indexOf(this.rotateRight),this.buttons.buttons.splice(o,1),this.buttons.element.removeChild(this.rotateRight.element))),this.showNavigator&&(this.navigator=new e.Navigator({id:this.navigatorId,position:this.navigatorPosition,sizeRatio:this.navigatorSizeRatio,maintainSizeRatio:this.navigatorMaintainSizeRatio,top:this.navigatorTop,left:this.navigatorLeft,width:this.navigatorWidth,height:this.navigatorHeight,autoResize:this.navigatorAutoResize,autoFade:this.navigatorAutoFade,prefixUrl:this.prefixUrl,viewer:this,navigatorRotate:this.navigatorRotate,background:this.navigatorBackground,opacity:this.navigatorOpacity,borderColor:this.navigatorBorderColor,displayRegionColor:this.navigatorDisplayRegionColor,crossOriginPolicy:this.crossOriginPolicy})),this.sequenceMode&&this.bindSequenceControls(),this.tileSources&&this.open(this.tileSources),o=0;o-1&&t.index\s*$/))i=e.parseXml(i);else if(i.match(/^\s*[\{\[].*[\}\]]\s*$/))try{var s=e.parseJSON(i);i=s}catch(e){}function l(e,t){e.ready?r(e):(e.addHandler("ready",(function(){r(e)})),e.addHandler("open-failed",(function(e){o({message:e.message,source:t})})))}setTimeout((function(){if("string"==e.type(i))(i=new e.TileSource({url:i,crossOriginPolicy:void 0!==n.crossOriginPolicy?n.crossOriginPolicy:t.crossOriginPolicy,ajaxWithCredentials:t.ajaxWithCredentials,ajaxHeaders:t.ajaxHeaders,useCanvas:t.useCanvas,success:function(e){r(e.tileSource)}})).addHandler("open-failed",(function(e){o(e)}));else if(e.isPlainObject(i)||i.nodeType)if(void 0!==i.crossOriginPolicy||void 0===n.crossOriginPolicy&&void 0===t.crossOriginPolicy||(i.crossOriginPolicy=void 0!==n.crossOriginPolicy?n.crossOriginPolicy:t.crossOriginPolicy),void 0===i.ajaxWithCredentials&&(i.ajaxWithCredentials=t.ajaxWithCredentials),void 0===i.useCanvas&&(i.useCanvas=t.useCanvas),e.isFunction(i.getTileUrl)){var s=new e.TileSource(i);s.getTileUrl=i.getTileUrl,r(s)}else{var c=e.TileSource.determineType(a,i);if(!c)return void o({message:"Unable to load TileSource",source:i});var u=c.prototype.configure.apply(a,[i]);l(new c(u),i)}else l(i,i)}))}(this,t.tileSource,t,(function(e){n.tileSource=e,a()}),(function(e){e.options=t,r(e),a()})))},addSimpleImage:function(t){e.console.assert(t,"[Viewer.addSimpleImage] options is required"),e.console.assert(t.url,"[Viewer.addSimpleImage] options.url is required");var i=e.extend({},t,{tileSource:{type:"image",url:t.url}});delete i.url,this.addTiledImage(i)},addLayer:function(t){var i=this;e.console.error("[Viewer.addLayer] this function is deprecated; use Viewer.addTiledImage() instead.");var n=e.extend({},t,{success:function(e){i.raiseEvent("add-layer",{options:t,drawer:e.item})},error:function(e){i.raiseEvent("add-layer-failed",e)}});return this.addTiledImage(n),this},getLayerAtLevel:function(t){return e.console.error("[Viewer.getLayerAtLevel] this function is deprecated; use World.getItemAt() instead."),this.world.getItemAt(t)},getLevelOfLayer:function(t){return e.console.error("[Viewer.getLevelOfLayer] this function is deprecated; use World.getIndexOfItem() instead."),this.world.getIndexOfItem(t)},getLayersCount:function(){return e.console.error("[Viewer.getLayersCount] this function is deprecated; use World.getItemCount() instead."),this.world.getItemCount()},setLayerLevel:function(t,i){return e.console.error("[Viewer.setLayerLevel] this function is deprecated; use World.setItemIndex() instead."),this.world.setItemIndex(t,i)},removeLayer:function(t){return e.console.error("[Viewer.removeLayer] this function is deprecated; use World.removeItem() instead."),this.world.removeItem(t)},forceRedraw:function(){return t[this.hash].forceRedraw=!0,this},bindSequenceControls:function(){var t=e.delegate(this,u),i=e.delegate(this,h),n=e.delegate(this,U),r=e.delegate(this,$),o=this.navImages,a=!0;return this.showSequenceControl&&((this.previousButton||this.nextButton)&&(a=!1),this.previousButton=new e.Button({element:this.previousButton?e.getElement(this.previousButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.PreviousPage"),srcRest:k(this.prefixUrl,o.previous.REST),srcGroup:k(this.prefixUrl,o.previous.GROUP),srcHover:k(this.prefixUrl,o.previous.HOVER),srcDown:k(this.prefixUrl,o.previous.DOWN),onRelease:r,onFocus:t,onBlur:i}),this.nextButton=new e.Button({element:this.nextButton?e.getElement(this.nextButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.NextPage"),srcRest:k(this.prefixUrl,o.next.REST),srcGroup:k(this.prefixUrl,o.next.GROUP),srcHover:k(this.prefixUrl,o.next.HOVER),srcDown:k(this.prefixUrl,o.next.DOWN),onRelease:n,onFocus:t,onBlur:i}),this.navPrevNextWrap||this.previousButton.disable(),this.tileSources&&this.tileSources.length||this.nextButton.disable(),a&&(this.paging=new e.ButtonGroup({buttons:[this.previousButton,this.nextButton],clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold}),this.pagingControl=this.paging.element,this.toolbar?this.toolbar.addControl(this.pagingControl,{anchor:e.ControlAnchor.BOTTOM_RIGHT}):this.addControl(this.pagingControl,{anchor:this.sequenceControlAnchor||e.ControlAnchor.TOP_LEFT}))),this},bindStandardControls:function(){var t=e.delegate(this,O),i=e.delegate(this,M),n=e.delegate(this,D),r=e.delegate(this,I),o=e.delegate(this,H),a=e.delegate(this,B),s=e.delegate(this,F),l=e.delegate(this,N),c=e.delegate(this,V),d=e.delegate(this,j),p=e.delegate(this,u),g=e.delegate(this,h),m=this.navImages,f=[],v=!0;return this.showNavigationControl&&((this.zoomInButton||this.zoomOutButton||this.homeButton||this.fullPageButton||this.rotateLeftButton||this.rotateRightButton||this.flipButton)&&(v=!1),this.showZoomControl&&(f.push(this.zoomInButton=new e.Button({element:this.zoomInButton?e.getElement(this.zoomInButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.ZoomIn"),srcRest:k(this.prefixUrl,m.zoomIn.REST),srcGroup:k(this.prefixUrl,m.zoomIn.GROUP),srcHover:k(this.prefixUrl,m.zoomIn.HOVER),srcDown:k(this.prefixUrl,m.zoomIn.DOWN),onPress:t,onRelease:i,onClick:n,onEnter:t,onExit:i,onFocus:p,onBlur:g})),f.push(this.zoomOutButton=new e.Button({element:this.zoomOutButton?e.getElement(this.zoomOutButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.ZoomOut"),srcRest:k(this.prefixUrl,m.zoomOut.REST),srcGroup:k(this.prefixUrl,m.zoomOut.GROUP),srcHover:k(this.prefixUrl,m.zoomOut.HOVER),srcDown:k(this.prefixUrl,m.zoomOut.DOWN),onPress:r,onRelease:i,onClick:o,onEnter:r,onExit:i,onFocus:p,onBlur:g}))),this.showHomeControl&&f.push(this.homeButton=new e.Button({element:this.homeButton?e.getElement(this.homeButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.Home"),srcRest:k(this.prefixUrl,m.home.REST),srcGroup:k(this.prefixUrl,m.home.GROUP),srcHover:k(this.prefixUrl,m.home.HOVER),srcDown:k(this.prefixUrl,m.home.DOWN),onRelease:a,onFocus:p,onBlur:g})),this.showFullPageControl&&f.push(this.fullPageButton=new e.Button({element:this.fullPageButton?e.getElement(this.fullPageButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.FullPage"),srcRest:k(this.prefixUrl,m.fullpage.REST),srcGroup:k(this.prefixUrl,m.fullpage.GROUP),srcHover:k(this.prefixUrl,m.fullpage.HOVER),srcDown:k(this.prefixUrl,m.fullpage.DOWN),onRelease:s,onFocus:p,onBlur:g})),this.showRotationControl&&(f.push(this.rotateLeftButton=new e.Button({element:this.rotateLeftButton?e.getElement(this.rotateLeftButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.RotateLeft"),srcRest:k(this.prefixUrl,m.rotateleft.REST),srcGroup:k(this.prefixUrl,m.rotateleft.GROUP),srcHover:k(this.prefixUrl,m.rotateleft.HOVER),srcDown:k(this.prefixUrl,m.rotateleft.DOWN),onRelease:l,onFocus:p,onBlur:g})),f.push(this.rotateRightButton=new e.Button({element:this.rotateRightButton?e.getElement(this.rotateRightButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.RotateRight"),srcRest:k(this.prefixUrl,m.rotateright.REST),srcGroup:k(this.prefixUrl,m.rotateright.GROUP),srcHover:k(this.prefixUrl,m.rotateright.HOVER),srcDown:k(this.prefixUrl,m.rotateright.DOWN),onRelease:c,onFocus:p,onBlur:g}))),this.showFlipControl&&f.push(this.flipButton=new e.Button({element:this.flipButton?e.getElement(this.flipButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:e.getString("Tooltips.Flip"),srcRest:k(this.prefixUrl,m.flip.REST),srcGroup:k(this.prefixUrl,m.flip.GROUP),srcHover:k(this.prefixUrl,m.flip.HOVER),srcDown:k(this.prefixUrl,m.flip.DOWN),onRelease:d,onFocus:p,onBlur:g})),v&&(this.buttons=new e.ButtonGroup({buttons:f,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold}),this.navControl=this.buttons.element,this.addHandler("open",e.delegate(this,z)),this.toolbar?this.toolbar.addControl(this.navControl,{anchor:this.navigationControlAnchor||e.ControlAnchor.TOP_LEFT}):this.addControl(this.navControl,{anchor:this.navigationControlAnchor||e.ControlAnchor.TOP_LEFT}))),this},currentPage:function(){return this._sequenceIndex},goToPage:function(e){return this.tileSources&&e>=0&&e=0)return this;var l=r(this,s);return this.currentOverlays.push(l),l.drawHTML(this.overlaysContainer,this.viewport),this.raiseEvent("add-overlay",{element:t,location:s.location,placement:s.placement}),this},updateOverlay:function(i,n,r){var a;return i=e.getElement(i),(a=o(this.currentOverlays,i))>=0&&(this.currentOverlays[a].update(n,r),t[this.hash].forceRedraw=!0,this.raiseEvent("update-overlay",{element:i,location:n,placement:r})),this},removeOverlay:function(i){var n;return i=e.getElement(i),(n=o(this.currentOverlays,i))>=0&&(this.currentOverlays[n].destroy(),this.currentOverlays.splice(n,1),t[this.hash].forceRedraw=!0,this.raiseEvent("remove-overlay",{element:i})),this},clearOverlays:function(){for(;this.currentOverlays.length>0;)this.currentOverlays.pop().destroy();return t[this.hash].forceRedraw=!0,this.raiseEvent("clear-overlay",{}),this},getOverlayById:function(t){var i;return t=e.getElement(t),(i=o(this.currentOverlays,t))>=0?this.currentOverlays[i]:null},_updateSequenceButtons:function(e){this.nextButton&&(this.tileSources&&this.tileSources.length-1!==e?this.nextButton.enable():this.navPrevNextWrap||this.nextButton.disable()),this.previousButton&&(e>0?this.previousButton.enable():this.navPrevNextWrap||this.previousButton.disable())},_showMessage:function(t){this._hideMessage();var i=e.makeNeutralElement("div");i.appendChild(document.createTextNode(t)),this.messageDiv=e.makeCenteredNode(i),e.addClass(this.messageDiv,"openseadragon-message"),this.container.appendChild(this.messageDiv)},_hideMessage:function(){var e=this.messageDiv;e&&(e.parentNode.removeChild(e),delete this.messageDiv)},gestureSettingsByDeviceType:function(e){switch(e){case"mouse":return this.gestureSettingsMouse;case"touch":return this.gestureSettingsTouch;case"pen":return this.gestureSettingsPen;default:return this.gestureSettingsUnknown}},_drawOverlays:function(){var e,t=this.currentOverlays.length;for(e=0;e1&&(this.referenceStrip=new e.ReferenceStrip({id:this.referenceStripElement,position:this.referenceStripPosition,sizeRatio:this.referenceStripSizeRatio,scroll:this.referenceStripScroll,height:this.referenceStripHeight,width:this.referenceStripWidth,tileSources:this.tileSources,prefixUrl:this.prefixUrl,viewer:this}),this.referenceStrip.setFocus(this._sequenceIndex))}else e.console.warn('Attempting to display a reference strip while "sequenceMode" is off.')}})}(OpenSeadragon),function(e){function t(e){var t={tracker:e.eventSource,position:e.position,quick:e.quick,shift:e.shift,originalEvent:e.originalEvent,preventDefaultAction:e.preventDefaultAction};if(this.viewer.raiseEvent("navigator-click",t),!t.preventDefaultAction&&e.quick&&this.viewer.viewport&&(this.panVertical||this.panHorizontal)){this.viewer.viewport.flipped&&(e.position.x=this.viewport.getContainerSize().x-e.position.x);var i=this.viewport.pointFromPixel(e.position);this.panVertical?this.panHorizontal||(i.x=this.viewer.viewport.getCenter(!0).x):i.y=this.viewer.viewport.getCenter(!0).y,this.viewer.viewport.panTo(i),this.viewer.viewport.applyConstraints()}}function i(e){var t={tracker:e.eventSource,position:e.position,delta:e.delta,speed:e.speed,direction:e.direction,shift:e.shift,originalEvent:e.originalEvent,preventDefaultAction:e.preventDefaultAction};this.viewer.raiseEvent("navigator-drag",t),!t.preventDefaultAction&&this.viewer.viewport&&(this.panHorizontal||(e.delta.x=0),this.panVertical||(e.delta.y=0),this.viewer.viewport.flipped&&(e.delta.x=-e.delta.x),this.viewer.viewport.panBy(this.viewport.deltaPointsFromPixels(e.delta)),this.viewer.constrainDuringPan&&this.viewer.viewport.applyConstraints())}function n(e){e.insideElementPressed&&this.viewer.viewport&&this.viewer.viewport.applyConstraints()}function r(e){return this.viewer.raiseEvent("navigator-scroll",{tracker:e.eventSource,position:e.position,scroll:e.scroll,shift:e.shift,originalEvent:e.originalEvent}),!1}function o(e,t){a(e,"rotate("+t+"deg)")}function a(e,t){e.style.webkitTransform=t,e.style.mozTransform=t,e.style.msTransform=t,e.style.oTransform=t,e.style.transform=t}e.Navigator=function(a){var s,l,c,u,h=a.viewer,d=this;function p(e){o(d.displayRegionContainer,e),o(d.displayRegion,-e),d.viewport.setRotation(e)}(a.id?(this.element=document.getElementById(a.id),a.controlOptions={anchor:e.ControlAnchor.NONE,attachToViewer:!1,autoFade:!1}):(a.id="navigator-"+e.now(),this.element=e.makeNeutralElement("div"),a.controlOptions={anchor:e.ControlAnchor.TOP_RIGHT,attachToViewer:!0,autoFade:a.autoFade},a.position&&("BOTTOM_RIGHT"==a.position?a.controlOptions.anchor=e.ControlAnchor.BOTTOM_RIGHT:"BOTTOM_LEFT"==a.position?a.controlOptions.anchor=e.ControlAnchor.BOTTOM_LEFT:"TOP_RIGHT"==a.position?a.controlOptions.anchor=e.ControlAnchor.TOP_RIGHT:"TOP_LEFT"==a.position?a.controlOptions.anchor=e.ControlAnchor.TOP_LEFT:"ABSOLUTE"==a.position&&(a.controlOptions.anchor=e.ControlAnchor.ABSOLUTE,a.controlOptions.top=a.top,a.controlOptions.left=a.left,a.controlOptions.height=a.height,a.controlOptions.width=a.width))),this.element.id=a.id,this.element.className+=" navigator",(a=e.extend(!0,{sizeRatio:e.DEFAULT_SETTINGS.navigatorSizeRatio},a,{element:this.element,tabIndex:-1,showNavigator:!1,mouseNavEnabled:!1,showNavigationControl:!1,showSequenceControl:!1,immediateRender:!0,blendTime:0,animationTime:0,autoResize:a.autoResize,minZoomImageRatio:1,background:a.background,opacity:a.opacity,borderColor:a.borderColor,displayRegionColor:a.displayRegionColor})).minPixelRatio=this.minPixelRatio=h.minPixelRatio,e.setElementTouchActionNone(this.element),this.borderWidth=2,this.fudge=new e.Point(1,1),this.totalBorderWidths=new e.Point(2*this.borderWidth,2*this.borderWidth).minus(this.fudge),a.controlOptions.anchor!=e.ControlAnchor.NONE&&(c=this.element.style,u=this.borderWidth,c.margin="0px",c.border=u+"px solid "+a.borderColor,c.padding="0px",c.background=a.background,c.opacity=a.opacity,c.overflow="hidden"),this.displayRegion=e.makeNeutralElement("div"),this.displayRegion.id=this.element.id+"-displayregion",this.displayRegion.className="displayregion",function(e,t){e.position="relative",e.top="0px",e.left="0px",e.fontSize="0px",e.overflow="hidden",e.border=t+"px solid "+a.displayRegionColor,e.margin="0px",e.padding="0px",e.background="transparent",e.float="left",e.cssFloat="left",e.styleFloat="left",e.zIndex=999999999,e.cursor="default"}(this.displayRegion.style,this.borderWidth),this.displayRegionContainer=e.makeNeutralElement("div"),this.displayRegionContainer.id=this.element.id+"-displayregioncontainer",this.displayRegionContainer.className="displayregioncontainer",this.displayRegionContainer.style.width="100%",this.displayRegionContainer.style.height="100%",h.addControl(this.element,a.controlOptions),this._resizeWithViewer=a.controlOptions.anchor!=e.ControlAnchor.ABSOLUTE&&a.controlOptions.anchor!=e.ControlAnchor.NONE,this._resizeWithViewer&&(a.width&&a.height?(this.element.style.height="number"==typeof a.height?a.height+"px":a.height,this.element.style.width="number"==typeof a.width?a.width+"px":a.width):(s=e.getElementSize(h.element),this.element.style.height=Math.round(s.y*a.sizeRatio)+"px",this.element.style.width=Math.round(s.x*a.sizeRatio)+"px",this.oldViewerSize=s),l=e.getElementSize(this.element),this.elementArea=l.x*l.y),this.oldContainerSize=new e.Point(0,0),e.Viewer.apply(this,[a]),this.displayRegionContainer.appendChild(this.displayRegion),this.element.getElementsByTagName("div")[0].appendChild(this.displayRegionContainer),a.navigatorRotate)&&(p(a.viewer.viewport?a.viewer.viewport.getRotation():a.viewer.degrees||0),a.viewer.addHandler("rotate",(function(e){p(e.degrees)})));this.innerTracker.destroy(),this.innerTracker=new e.MouseTracker({element:this.element,dragHandler:e.delegate(this,i),clickHandler:e.delegate(this,t),releaseHandler:e.delegate(this,n),scrollHandler:e.delegate(this,r)}),this.addHandler("reset-size",(function(){d.viewport&&d.viewport.goHome(!0)})),h.world.addHandler("item-index-change",(function(e){window.setTimeout((function(){var t=d.world.getItemAt(e.previousIndex);d.world.setItemIndex(t,e.newIndex)}),1)})),h.world.addHandler("remove-item",(function(e){var t=e.item,i=d._getMatchingItem(t);i&&d.world.removeItem(i)})),this.update(h.viewport)},e.extend(e.Navigator.prototype,e.EventSource.prototype,e.Viewer.prototype,{updateSize:function(){if(this.viewport){var t=new e.Point(0===this.container.clientWidth?1:this.container.clientWidth,0===this.container.clientHeight?1:this.container.clientHeight);t.equals(this.oldContainerSize)||(this.viewport.resize(t,!0),this.viewport.goHome(!0),this.oldContainerSize=t,this.drawer.clear(),this.world.draw())}},setFlip:function(e){return this.viewport.setFlip(e),this.setDisplayTransform(this.viewer.viewport.getFlip()?"scale(-1,1)":"scale(1,1)"),this},setDisplayTransform:function(e){a(this.displayRegion,e),a(this.canvas,e),a(this.element,e)},update:function(t){var i,n,r,o,a,s;if(i=e.getElementSize(this.viewer.element),this._resizeWithViewer&&i.x&&i.y&&!i.equals(this.oldViewerSize)&&(this.oldViewerSize=i,this.maintainSizeRatio||!this.elementArea?(n=i.x*this.sizeRatio,r=i.y*this.sizeRatio):(n=Math.sqrt(this.elementArea*(i.x/i.y)),r=this.elementArea/n),this.element.style.width=Math.round(n)+"px",this.element.style.height=Math.round(r)+"px",this.elementArea||(this.elementArea=n*r),this.updateSize()),t&&this.viewport){o=t.getBoundsNoRotate(!0),a=this.viewport.pixelFromPointNoRotate(o.getTopLeft(),!1),s=this.viewport.pixelFromPointNoRotate(o.getBottomRight(),!1).minus(this.totalBorderWidths);var l=this.displayRegion.style;l.display=this.world.getItemCount()?"block":"none",l.top=Math.round(a.y)+"px",l.left=Math.round(a.x)+"px";var c=Math.abs(a.x-s.x),u=Math.abs(a.y-s.y);l.width=Math.round(Math.max(c,0))+"px",l.height=Math.round(Math.max(u,0))+"px"}},addTiledImage:function(t){var i=this,n=t.originalTiledImage;delete t.original;var r=e.extend({},t,{success:function(e){var t=e.item;function r(){i._matchBounds(t,n)}t._originalForNavigator=n,i._matchBounds(t,n,!0),n.addHandler("bounds-change",r),n.addHandler("clip-change",r),n.addHandler("opacity-change",(function(){i._matchOpacity(t,n)})),n.addHandler("composite-operation-change",(function(){i._matchCompositeOperation(t,n)}))}});return e.Viewer.prototype.addTiledImage.apply(this,[r])},_getMatchingItem:function(e){for(var t,i=this.world.getItemCount(),n=0;n1||t.y>1);e++);return e-1},getTileAtPoint:function(t,i){var n=i.x>=0&&i.x<=1&&i.y>=0&&i.y<=1/this.aspectRatio;e.console.assert(n,"[TileSource.getTileAtPoint] must be called with a valid point.");var r=this.dimensions.x*this.getLevelScale(t),o=i.x*r,a=i.y*r,s=Math.floor(o/this.getTileWidth(t)),l=Math.floor(a/this.getTileHeight(t));i.x>=1&&(s=this.getNumTiles(t).x-1);return i.y>=1/this.aspectRatio-1e-15&&(l=this.getNumTiles(t).y-1),new e.Point(s,l)},getTileBounds:function(t,i,n,r){var o=this.dimensions.times(this.getLevelScale(t)),a=this.getTileWidth(t),s=this.getTileHeight(t),l=0===i?0:a*i-this.tileOverlap,c=0===n?0:s*n-this.tileOverlap,u=a+(0===i?1:2)*this.tileOverlap,h=s+(0===n?1:2)*this.tileOverlap,d=1/o.x;return u=Math.min(u,o.x-l),h=Math.min(h,o.y-c),r?new e.Rect(0,0,u,h):new e.Rect(l*d,c*d,u*d,h*d)},getImageInfo:function(t){var i,n,r,o,a,s,l,c=this;t&&(l=(s=(a=t.split("/"))[a.length-1]).lastIndexOf("."))>-1&&(a[a.length-1]=s.slice(0,l)),n=function(i){"string"==typeof i&&(i=e.parseXml(i));var n=e.TileSource.determineType(c,i,t);n?(void 0===(o=n.prototype.configure.apply(c,[i,t])).ajaxWithCredentials&&(o.ajaxWithCredentials=c.ajaxWithCredentials),r=new n(o),c.ready=!0,c.raiseEvent("ready",{tileSource:r})):c.raiseEvent("open-failed",{message:"Unable to load TileSource",source:t})},t.match(/\.js$/)?(i=t.split("/").pop().replace(".js",""),e.jsonp({url:t,async:!1,callbackName:i,callback:n})):e.makeAjaxRequest({url:t,withCredentials:this.ajaxWithCredentials,headers:this.ajaxHeaders,success:function(t){var i=function(t){var i,n,r=t.responseText,o=t.status;if(!t)throw new Error(e.getString("Errors.Security"));if(200!==t.status&&0!==t.status)throw o=t.status,i=404==o?"Not Found":t.statusText,new Error(e.getString("Errors.Status",o,i));if(r.match(/\s*<.*/))try{n=t.responseXML&&t.responseXML.documentElement?t.responseXML:e.parseXml(r)}catch(e){n=t.responseText}else if(r.match(/\s*[\{\[].*/))try{n=e.parseJSON(r)}catch(e){n=r}else n=r;return n}(t);n(i)},error:function(e,i){var n;try{n="HTTP "+e.status+" attempting to load TileSource"}catch(e){n=(void 0!==i&&i.toString?i.toString():"Unknown error")+" attempting to load TileSource"}c.raiseEvent("open-failed",{message:n,source:t})}})},supports:function(e,t){return!1},configure:function(e,t){throw new Error("Method not implemented.")},getTileUrl:function(e,t,i){throw new Error("Method not implemented.")},getTileAjaxHeaders:function(e,t,i){return{}},tileExists:function(e,t,i){var n=this.getNumTiles(e);return e>=this.minLevel&&e<=this.maxLevel&&t>=0&&i>=0&&t=0;u--)for(d=(h=this.displayRects[u]).minLevel;d<=h.maxLevel;d++)this._levelRects[d]||(this._levelRects[d]=[]),this._levelRects[d].push(h);e.TileSource.apply(this,[p])},e.extend(e.DziTileSource.prototype,e.TileSource.prototype,{supports:function(e,t){var i;return e.Image?i=e.Image.xmlns:e.documentElement&&("Image"!=e.documentElement.localName&&"Image"!=e.documentElement.tagName||(i=e.documentElement.namespaceURI)),-1!==(i=(i||"").toLowerCase()).indexOf("schemas.microsoft.com/deepzoom/2008")||-1!==i.indexOf("schemas.microsoft.com/deepzoom/2009")},configure:function(i,n){var r;return r=e.isPlainObject(i)?t(this,i):function(i,n){if(!n||!n.documentElement)throw new Error(e.getString("Errors.Xml"));var r,o,a,s,l,c=n.documentElement,u=c.localName||c.tagName,h=n.documentElement.namespaceURI,d=null,p=[];if("Image"==u)try{if(void 0===(s=c.getElementsByTagName("Size")[0])&&(s=c.getElementsByTagNameNS(h,"Size")[0]),d={Image:{xmlns:"http://schemas.microsoft.com/deepzoom/2008",Url:c.getAttribute("Url"),Format:c.getAttribute("Format"),DisplayRect:null,Overlap:parseInt(c.getAttribute("Overlap"),10),TileSize:parseInt(c.getAttribute("TileSize"),10),Size:{Height:parseInt(s.getAttribute("Height"),10),Width:parseInt(s.getAttribute("Width"),10)}}},!e.imageFormatSupported(d.Image.Format))throw new Error(e.getString("Errors.ImageFormat",d.Image.Format.toUpperCase()));for(void 0===(r=c.getElementsByTagName("DisplayRect"))&&(r=c.getElementsByTagNameNS(h,"DisplayRect")[0]),l=0;lthis.maxLevel)return!1;if(!u||!u.length)return!0;for(c=u.length-1;c>=0;c--)if(!(e<(n=u[c]).minLevel||e>n.maxLevel)&&(r=this.getLevelScale(e),o=n.x*r,a=n.y*r,s=o+n.width*r,l=a+n.height*r,o=Math.floor(o/this._tileWidth),a=Math.floor(a/this._tileWidth),s=Math.ceil(s/this._tileWidth),l=Math.ceil(l/this._tileWidth),o<=t&&t1&&e[1].supports&&(i=-1!==e[1].supports.indexOf("sizeByW"));return!t||i}(t.profile)){for(var o=Math.min(this.height,this.width),a=[256,512,1024],s=[],l=0;l0?t.tileSize=Math.max.apply(null,s):t.tileSize=o}else this.sizes&&this.sizes.length>0?(this.emulateLegacyImagePyramid=!0,t.levels=function(e){for(var t=[],i=0;i0&&t>=this.minLevel&&t<=this.maxLevel&&(i=this.levels[t].width/this.levels[this.maxLevel].width),i}return e.TileSource.prototype.getLevelScale.call(this,t)},getNumTiles:function(t){return this.emulateLegacyImagePyramid?this.getLevelScale(t)?new e.Point(1,1):new e.Point(0,0):e.TileSource.prototype.getNumTiles.call(this,t)},getTileAtPoint:function(t,i){return this.emulateLegacyImagePyramid?new e.Point(0,0):e.TileSource.prototype.getTileAtPoint.call(this,t,i)},getTileUrl:function(e,t,i){if(this.emulateLegacyImagePyramid){var n=null;return this.levels.length>0&&e>=this.minLevel&&e<=this.maxLevel&&(n=this.levels[e].url),n}var r,o,a,s,l,c,u,h,d,p,g,m,f,v=Math.pow(.5,this.maxLevel-e),y=Math.ceil(this.width*v),w=Math.ceil(this.height*v);return r=this.getTileWidth(e),o=this.getTileHeight(e),a=Math.ceil(r/v),s=Math.ceil(o/v),m=(f=this["@context"].indexOf("/1.0/context.json")>-1||this["@context"].indexOf("/1.1/context.json")>-1||this["@context"].indexOf("/1/context.json")>-1)?"native."+this.tileFormat:"default."+this.tileFormat,yc?l/256:c/256,a.maxLevel=Math.ceil(Math.log(s)/Math.log(2))-1,a.tileSize=256,a.width=l,a.height=c,e.TileSource.apply(this,[a])},e.extend(e.TmsTileSource.prototype,e.TileSource.prototype,{supports:function(e,t){return e.type&&"tiledmapservice"==e.type},configure:function(e,t){return e},getTileUrl:function(e,t,i){var n=this.getNumTiles(e).y-1;return this.tilesUrl+e+"/"+t+"/"+(n-i)+".png"}})}(OpenSeadragon),function(e){e.ZoomifyTileSource=function(e){e.tileSize=256;var t={x:e.width,y:e.height};for(e.imageSizes=[{x:e.width,y:e.height}],e.gridSize=[this._getGridSize(e.width,e.height,e.tileSize)];parseInt(t.x,10)>e.tileSize||parseInt(t.y,10)>e.tileSize;)t.x=Math.floor(t.x/2),t.y=Math.floor(t.y/2),e.imageSizes.push({x:t.x,y:t.y}),e.gridSize.push(this._getGridSize(t.x,t.y,e.tileSize));e.imageSizes.reverse(),e.gridSize.reverse(),e.minLevel=0,e.maxLevel=e.gridSize.length-1,OpenSeadragon.TileSource.apply(this,[e])},e.extend(e.ZoomifyTileSource.prototype,e.TileSource.prototype,{_getGridSize:function(e,t,i){return{x:Math.ceil(e/i),y:Math.ceil(t/i)}},_calculateAbsoluteTileNumber:function(e,t,i){for(var n=0,r={},o=0;o");return r.sort((function(e,t){return e.height-t.height}))}(i.levels),i.levels.length>0?(n=i.levels[i.levels.length-1].width,r=i.levels[i.levels.length-1].height):(n=0,r=0,e.console.error("No supported image formats found")),e.extend(!0,i,{width:n,height:r,tileSize:Math.max(r,n),tileOverlap:0,minLevel:0,maxLevel:i.levels.length>0?i.levels.length-1:0}),e.TileSource.apply(this,[i]),this.levels=i.levels},e.extend(e.LegacyTileSource.prototype,e.TileSource.prototype,{supports:function(e,t){return e.type&&"legacy-image-pyramid"==e.type||e.documentElement&&"legacy-image-pyramid"==e.documentElement.getAttribute("type")},configure:function(i,n){return e.isPlainObject(i)?t(this,i):function(i,n){if(!n||!n.documentElement)throw new Error(e.getString("Errors.Xml"));var r,o,a=n.documentElement,s=a.tagName,l=null,c=[];if("image"==s)try{for(l={type:a.getAttribute("type"),levels:[]},c=a.getElementsByTagName("level"),o=0;o0&&e>=this.minLevel&&e<=this.maxLevel&&(t=this.levels[e].width/this.levels[this.maxLevel].width),t},getNumTiles:function(t){return this.getLevelScale(t)?new e.Point(1,1):new e.Point(0,0)},getTileUrl:function(e,t,i){var n=null;return this.levels.length>0&&e>=this.minLevel&&e<=this.maxLevel&&(n=this.levels[e].url),n}})}(OpenSeadragon),function(e){e.ImageTileSource=function(t){t=e.extend({buildPyramid:!0,crossOriginPolicy:!1,ajaxWithCredentials:!1,useCanvas:!0},t),e.TileSource.apply(this,[t])},e.extend(e.ImageTileSource.prototype,e.TileSource.prototype,{supports:function(e,t){return e.type&&"image"===e.type},configure:function(e,t){return e},getImageInfo:function(t){var i=this._image=new Image,n=this;this.crossOriginPolicy&&(i.crossOrigin=this.crossOriginPolicy),this.ajaxWithCredentials&&(i.useCredentials=this.ajaxWithCredentials),e.addEvent(i,"load",(function(){n.width=Object.prototype.hasOwnProperty.call(i,"naturalWidth")?i.naturalWidth:i.width,n.height=Object.prototype.hasOwnProperty.call(i,"naturalHeight")?i.naturalHeight:i.height,n.aspectRatio=n.width/n.height,n.dimensions=new e.Point(n.width,n.height),n._tileWidth=n.width,n._tileHeight=n.height,n.tileOverlap=0,n.minLevel=0,n.levels=n._buildLevels(),n.maxLevel=n.levels.length-1,n.ready=!0,n.raiseEvent("ready",{tileSource:n})})),e.addEvent(i,"error",(function(){n.raiseEvent("open-failed",{message:"Error loading image at "+t,source:t})})),i.src=t},getLevelScale:function(e){var t=NaN;return e>=this.minLevel&&e<=this.maxLevel&&(t=this.levels[e].width/this.levels[this.maxLevel].width),t},getNumTiles:function(t){return this.getLevelScale(t)?new e.Point(1,1):new e.Point(0,0)},getTileUrl:function(e,t,i){var n=null;return e>=this.minLevel&&e<=this.maxLevel&&(n=this.levels[e].url),n},getContext2D:function(e,t,i){var n=null;return e>=this.minLevel&&e<=this.maxLevel&&(n=this.levels[e].context2D),n},_buildLevels:function(){var t=[{url:this._image.src,width:Object.prototype.hasOwnProperty.call(this._image,"naturalWidth")?this._image.naturalWidth:this._image.width,height:Object.prototype.hasOwnProperty.call(this._image,"naturalHeight")?this._image.naturalHeight:this._image.height}];if(!this.buildPyramid||!e.supportsCanvas||!this.useCanvas)return delete this._image,t;var i=Object.prototype.hasOwnProperty.call(this._image,"naturalWidth")?this._image.naturalWidth:this._image.width,n=Object.prototype.hasOwnProperty.call(this._image,"naturalHeight")?this._image.naturalHeight:this._image.height,r=document.createElement("canvas"),o=r.getContext("2d");if(r.width=i,r.height=n,o.drawImage(this._image,0,0,i,n),t[0].context2D=o,delete this._image,e.isCanvasTainted(r))return t;for(;i>=2&&n>=2;){i=Math.floor(i/2),n=Math.floor(n/2);var a=document.createElement("canvas"),s=a.getContext("2d");a.width=i,a.height=n,s.drawImage(r,0,0,i,n),t.splice(0,0,{context2D:s,width:i,height:n}),r=a,o=s}return t}})}(OpenSeadragon),function(e){e.TileSourceCollection=function(t,i,n,r){e.console.error("TileSourceCollection is deprecated; use World instead")}}(OpenSeadragon),function(e){function t(i){e.requestAnimationFrame((function(){!function(i){var n,r,o;i.shouldFade&&(n=e.now(),r=n-i.fadeBeginTime,o=1-r/i.fadeLength,o=Math.min(1,o),o=Math.max(0,o),i.imgGroup&&e.setElementOpacity(i.imgGroup,o,!0),o>0&&t(i))}(i)}))}function i(t,i){t.element.disabled||(i>=e.ButtonState.GROUP&&t.currentState==e.ButtonState.REST&&(!function(t){t.shouldFade=!1,t.imgGroup&&e.setElementOpacity(t.imgGroup,1,!0)}(t),t.currentState=e.ButtonState.GROUP),i>=e.ButtonState.HOVER&&t.currentState==e.ButtonState.GROUP&&(t.imgHover&&(t.imgHover.style.visibility=""),t.currentState=e.ButtonState.HOVER),i>=e.ButtonState.DOWN&&t.currentState==e.ButtonState.HOVER&&(t.imgDown&&(t.imgDown.style.visibility=""),t.currentState=e.ButtonState.DOWN))}function n(i,n){i.element.disabled||(n<=e.ButtonState.HOVER&&i.currentState==e.ButtonState.DOWN&&(i.imgDown&&(i.imgDown.style.visibility="hidden"),i.currentState=e.ButtonState.HOVER),n<=e.ButtonState.GROUP&&i.currentState==e.ButtonState.HOVER&&(i.imgHover&&(i.imgHover.style.visibility="hidden"),i.currentState=e.ButtonState.GROUP),n<=e.ButtonState.REST&&i.currentState==e.ButtonState.GROUP&&(!function(i){i.shouldFade=!0,i.fadeBeginTime=e.now()+i.fadeDelay,window.setTimeout((function(){t(i)}),i.fadeDelay)}(i),i.currentState=e.ButtonState.REST))}e.ButtonState={REST:0,GROUP:1,HOVER:2,DOWN:3},e.Button=function(t){var r=this;e.EventSource.call(this),e.extend(!0,this,{tooltip:null,srcRest:null,srcGroup:null,srcHover:null,srcDown:null,clickTimeThreshold:e.DEFAULT_SETTINGS.clickTimeThreshold,clickDistThreshold:e.DEFAULT_SETTINGS.clickDistThreshold,fadeDelay:0,fadeLength:2e3,onPress:null,onRelease:null,onClick:null,onEnter:null,onExit:null,onFocus:null,onBlur:null},t),this.element=t.element||e.makeNeutralElement("div"),t.element||(this.imgRest=e.makeTransparentImage(this.srcRest),this.imgGroup=e.makeTransparentImage(this.srcGroup),this.imgHover=e.makeTransparentImage(this.srcHover),this.imgDown=e.makeTransparentImage(this.srcDown),this.imgRest.alt=this.imgGroup.alt=this.imgHover.alt=this.imgDown.alt=this.tooltip,this.element.style.position="relative",e.setElementTouchActionNone(this.element),this.imgGroup.style.position=this.imgHover.style.position=this.imgDown.style.position="absolute",this.imgGroup.style.top=this.imgHover.style.top=this.imgDown.style.top="0px",this.imgGroup.style.left=this.imgHover.style.left=this.imgDown.style.left="0px",this.imgHover.style.visibility=this.imgDown.style.visibility="hidden",e.Browser.vendor==e.BROWSERS.FIREFOX&&e.Browser.version<3&&(this.imgGroup.style.top=this.imgHover.style.top=this.imgDown.style.top=""),this.element.appendChild(this.imgRest),this.element.appendChild(this.imgGroup),this.element.appendChild(this.imgHover),this.element.appendChild(this.imgDown)),this.addHandler("press",this.onPress),this.addHandler("release",this.onRelease),this.addHandler("click",this.onClick),this.addHandler("enter",this.onEnter),this.addHandler("exit",this.onExit),this.addHandler("focus",this.onFocus),this.addHandler("blur",this.onBlur),this.currentState=e.ButtonState.GROUP,this.fadeBeginTime=null,this.shouldFade=!1,this.element.style.display="inline-block",this.element.style.position="relative",this.element.title=this.tooltip,this.tracker=new e.MouseTracker({element:this.element,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,enterHandler:function(t){t.insideElementPressed?(i(r,e.ButtonState.DOWN),r.raiseEvent("enter",{originalEvent:t.originalEvent})):t.buttonDownAny||i(r,e.ButtonState.HOVER)},focusHandler:function(e){this.enterHandler(e),r.raiseEvent("focus",{originalEvent:e.originalEvent})},exitHandler:function(t){n(r,e.ButtonState.GROUP),t.insideElementPressed&&r.raiseEvent("exit",{originalEvent:t.originalEvent})},blurHandler:function(e){this.exitHandler(e),r.raiseEvent("blur",{originalEvent:e.originalEvent})},pressHandler:function(t){i(r,e.ButtonState.DOWN),r.raiseEvent("press",{originalEvent:t.originalEvent})},releaseHandler:function(t){t.insideElementPressed&&t.insideElementReleased?(n(r,e.ButtonState.HOVER),r.raiseEvent("release",{originalEvent:t.originalEvent})):t.insideElementPressed?n(r,e.ButtonState.GROUP):i(r,e.ButtonState.HOVER)},clickHandler:function(e){e.quick&&r.raiseEvent("click",{originalEvent:e.originalEvent})},keyHandler:function(e){return 13!==e.keyCode||(r.raiseEvent("click",{originalEvent:e.originalEvent}),r.raiseEvent("release",{originalEvent:e.originalEvent}),!1)}}),n(this,e.ButtonState.REST)},e.extend(e.Button.prototype,e.EventSource.prototype,{notifyGroupEnter:function(){i(this,e.ButtonState.GROUP)},notifyGroupExit:function(){n(this,e.ButtonState.REST)},disable:function(){this.notifyGroupExit(),this.element.disabled=!0,e.setElementOpacity(this.element,.2,!0)},enable:function(){this.element.disabled=!1,e.setElementOpacity(this.element,1,!0),this.notifyGroupEnter()}})}(OpenSeadragon),function(e){e.ButtonGroup=function(t){e.extend(!0,this,{buttons:[],clickTimeThreshold:e.DEFAULT_SETTINGS.clickTimeThreshold,clickDistThreshold:e.DEFAULT_SETTINGS.clickDistThreshold,labelText:""},t);var i,n=this.buttons.concat([]),r=this;if(this.element=t.element||e.makeNeutralElement("div"),!t.group)for(this.element.style.display="inline-block",i=0;i=270?(a=this.getTopRight(),this.x=a.x,this.y=a.y,s=this.height,this.height=this.width,this.width=s,this.degrees-=270):this.degrees>=180?(a=this.getBottomRight(),this.x=a.x,this.y=a.y,this.degrees-=180):this.degrees>=90&&(a=this.getBottomLeft(),this.x=a.x,this.y=a.y,s=this.height,this.height=this.width,this.width=s,this.degrees-=90)},e.Rect.fromSummits=function(t,i,n){var r=t.distanceTo(i),o=t.distanceTo(n),a=i.minus(t),s=Math.atan(a.y/a.x);return a.x<0?s+=Math.PI:a.y<0&&(s+=2*Math.PI),new e.Rect(t.x,t.y,r,o,s/Math.PI*180)},e.Rect.prototype={clone:function(){return new e.Rect(this.x,this.y,this.width,this.height,this.degrees)},getAspectRatio:function(){return this.width/this.height},getTopLeft:function(){return new e.Point(this.x,this.y)},getBottomRight:function(){return new e.Point(this.x+this.width,this.y+this.height).rotate(this.degrees,this.getTopLeft())},getTopRight:function(){return new e.Point(this.x+this.width,this.y).rotate(this.degrees,this.getTopLeft())},getBottomLeft:function(){return new e.Point(this.x,this.y+this.height).rotate(this.degrees,this.getTopLeft())},getCenter:function(){return new e.Point(this.x+this.width/2,this.y+this.height/2).rotate(this.degrees,this.getTopLeft())},getSize:function(){return new e.Point(this.width,this.height)},equals:function(t){return t instanceof e.Rect&&this.x===t.x&&this.y===t.y&&this.width===t.width&&this.height===t.height&&this.degrees===t.degrees},times:function(t){return new e.Rect(this.x*t,this.y*t,this.width*t,this.height*t,this.degrees)},translate:function(t){return new e.Rect(this.x+t.x,this.y+t.y,this.width,this.height,this.degrees)},union:function(t){var i=this.getBoundingBox(),n=t.getBoundingBox(),r=Math.min(i.x,n.x),o=Math.min(i.y,n.y),a=Math.max(i.x+i.width,n.x+n.width),s=Math.max(i.y+i.height,n.y+n.height);return new e.Rect(r,o,a-r,s-o)},intersection:function(t){var i=1e-10,n=[],r=this.getTopLeft();t.containsPoint(r,i)&&n.push(r);var o=this.getTopRight();t.containsPoint(o,i)&&n.push(o);var a=this.getBottomLeft();t.containsPoint(a,i)&&n.push(a);var s=this.getBottomRight();t.containsPoint(s,i)&&n.push(s);var l=t.getTopLeft();this.containsPoint(l,i)&&n.push(l);var c=t.getTopRight();this.containsPoint(c,i)&&n.push(c);var u=t.getBottomLeft();this.containsPoint(u,i)&&n.push(u);var h=t.getBottomRight();this.containsPoint(h,i)&&n.push(h);for(var d=this._getSegments(),p=t._getSegments(),g=0;gT&&(T=E.x),E.yx&&(x=E.y)}return new e.Rect(_,S,T-_,x-S)},_getSegments:function(){var e=this.getTopLeft(),t=this.getTopRight(),i=this.getBottomLeft(),n=this.getBottomRight();return[[e,t],[t,n],[n,i],[i,e]]},rotate:function(t,i){if(0===(t=e.positiveModulo(t,360)))return this.clone();i=i||this.getCenter();var n=this.getTopLeft().rotate(t,i),r=this.getTopRight().rotate(t,i).minus(n);r=r.apply((function(e){return Math.abs(e)<1e-15?0:e}));var o=Math.atan(r.y/r.x);return r.x<0?o+=Math.PI:r.y<0&&(o+=2*Math.PI),new e.Rect(n.x,n.y,this.width,this.height,o/Math.PI*180)},getBoundingBox:function(){if(0===this.degrees)return this.clone();var t=this.getTopLeft(),i=this.getTopRight(),n=this.getBottomLeft(),r=this.getBottomRight(),o=Math.min(t.x,i.x,n.x,r.x),a=Math.max(t.x,i.x,n.x,r.x),s=Math.min(t.y,i.y,n.y,r.y),l=Math.max(t.y,i.y,n.y,r.y);return new e.Rect(o,s,a-o,l-s)},getIntegerBoundingBox:function(){var t=this.getBoundingBox(),i=Math.floor(t.x),n=Math.floor(t.y),r=Math.ceil(t.width+t.x-i),o=Math.ceil(t.height+t.y-n);return new e.Rect(i,n,r,o)},containsPoint:function(e,t){t=t||0;var i=this.getTopLeft(),n=this.getTopRight(),r=this.getBottomLeft(),o=n.minus(i),a=r.minus(i);return(e.x-i.x)*o.x+(e.y-i.y)*o.y>=-t&&(e.x-n.x)*o.x+(e.y-n.y)*o.y<=t&&(e.x-i.x)*a.x+(e.y-i.y)*a.y>=-t&&(e.x-r.x)*a.x+(e.y-r.y)*a.y<=t},toString:function(){return"["+Math.round(100*this.x)/100+", "+Math.round(100*this.y)/100+", "+Math.round(100*this.width)/100+"x"+Math.round(100*this.height)/100+", "+Math.round(100*this.degrees)/100+"deg]"}}}(OpenSeadragon),function(e){var t={};function i(t){var i=Number(this.element.style.marginLeft.replace("px","")),n=Number(this.element.style.marginTop.replace("px","")),o=Number(this.element.style.width.replace("px","")),a=Number(this.element.style.height.replace("px","")),s=e.getElementSize(this.viewer.canvas);return this.dragging=!0,this.element&&("horizontal"==this.scroll?-t.delta.x>0?i>-(o-s.x)&&(this.element.style.marginLeft=i+2*t.delta.x+"px",r(this,s.x,i+2*t.delta.x)):-t.delta.x<0&&i<0&&(this.element.style.marginLeft=i+2*t.delta.x+"px",r(this,s.x,i+2*t.delta.x)):-t.delta.y>0?n>-(a-s.y)&&(this.element.style.marginTop=n+2*t.delta.y+"px",r(this,s.y,n+2*t.delta.y)):-t.delta.y<0&&n<0&&(this.element.style.marginTop=n+2*t.delta.y+"px",r(this,s.y,n+2*t.delta.y))),!1}function n(t){var i=Number(this.element.style.marginLeft.replace("px","")),n=Number(this.element.style.marginTop.replace("px","")),o=Number(this.element.style.width.replace("px","")),a=Number(this.element.style.height.replace("px","")),s=e.getElementSize(this.viewer.canvas);return this.element&&("horizontal"==this.scroll?t.scroll>0?i>-(o-s.x)&&(this.element.style.marginLeft=i-60*t.scroll+"px",r(this,s.x,i-60*t.scroll)):t.scroll<0&&i<0&&(this.element.style.marginLeft=i-60*t.scroll+"px",r(this,s.x,i-60*t.scroll)):t.scroll<0?n>s.y-a&&(this.element.style.marginTop=n+60*t.scroll+"px",r(this,s.y,n+60*t.scroll)):t.scroll>0&&n<0&&(this.element.style.marginTop=n+60*t.scroll+"px",r(this,s.y,n+60*t.scroll))),!1}function r(t,i,n){var r,o,a,s,l,c,u;for(r="horizontal"==t.scroll?t.panelWidth:t.panelHeight,o=Math.ceil(i/r)+5,c=o=(o=(a=Math.ceil((Math.abs(n)+i)/r)+1)-o)<0?0:o;cc+a.x-this.panelWidth?(i=Math.min(i,s-a.x),this.element.style.marginLeft=-i+"px",r(this,a.x,-i)):iu+a.y-this.panelHeight?(i=Math.min(i,l-a.y),this.element.style.marginTop=-i+"px",r(this,a.y,-i)):i1?i[1].springStiffness:5,animationTime:i.length>1?i[1].animationTime:1.5}),e.console.assert("number"==typeof t.springStiffness&&0!==t.springStiffness,"[OpenSeadragon.Spring] options.springStiffness must be a non-zero number"),e.console.assert("number"==typeof t.animationTime&&t.animationTime>=0,"[OpenSeadragon.Spring] options.animationTime must be a number greater than or equal to 0"),t.exponential&&(this._exponential=!0,delete t.exponential),e.extend(!0,this,t),this.current={value:"number"==typeof this.initial?this.initial:this._exponential?0:1,time:e.now()},e.console.assert(!this._exponential||0!==this.current.value,"[OpenSeadragon.Spring] value must be non-zero for exponential springs"),this.start={value:this.current.value,time:this.current.time},this.target={value:this.current.value,time:this.current.time},this._exponential&&(this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value),this.current._logValue=Math.log(this.current.value))},e.Spring.prototype={resetTo:function(t){e.console.assert(!this._exponential||0!==t,"[OpenSeadragon.Spring.resetTo] target must be non-zero for exponential springs"),this.start.value=this.target.value=this.current.value=t,this.start.time=this.target.time=this.current.time=e.now(),this._exponential&&(this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value),this.current._logValue=Math.log(this.current.value))},springTo:function(t){e.console.assert(!this._exponential||0!==t,"[OpenSeadragon.Spring.springTo] target must be non-zero for exponential springs"),this.start.value=this.current.value,this.start.time=this.current.time,this.target.value=t,this.target.time=this.start.time+1e3*this.animationTime,this._exponential&&(this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value))},shiftBy:function(t){this.start.value+=t,this.target.value+=t,this._exponential&&(e.console.assert(0!==this.target.value&&0!==this.start.value,"[OpenSeadragon.Spring.shiftBy] spring value must be non-zero for exponential springs"),this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value))},setExponential:function(t){this._exponential=t,this._exponential&&(e.console.assert(0!==this.current.value&&0!==this.target.value&&0!==this.start.value,"[OpenSeadragon.Spring.setExponential] spring value must be non-zero for exponential springs"),this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value),this.current._logValue=Math.log(this.current.value))},update:function(){var t,i;this.current.time=e.now(),this._exponential?(t=this.start._logValue,i=this.target._logValue):(t=this.start.value,i=this.target.value);var n,r,o=this.current.time>=this.target.time?i:t+(i-t)*(n=this.springStiffness,r=(this.current.time-this.start.time)/(this.target.time-this.start.time),(1-Math.exp(n*-r))/(1-Math.exp(-n))),a=this.current.value;return this._exponential?this.current.value=Math.exp(o):this.current.value=o,a!=this.current.value},isAtTargetValue:function(){return this.current.value===this.target.value}}}(OpenSeadragon),function(e){function t(t){e.extend(!0,this,{timeout:e.DEFAULT_SETTINGS.timeout,jobId:null},t),this.image=null}t.prototype={errorMsg:null,start:function(){var t=this,i=this.abort;this.image=new Image,this.image.onload=function(){t.finish(!0)},this.image.onabort=this.image.onerror=function(){t.errorMsg="Image load aborted",t.finish(!1)},this.jobId=window.setTimeout((function(){t.errorMsg="Image load exceeded timeout ("+t.timeout+" ms)",t.finish(!1)}),this.timeout),this.loadWithAjax?(this.request=e.makeAjaxRequest({url:this.src,withCredentials:this.ajaxWithCredentials,headers:this.ajaxHeaders,responseType:"arraybuffer",success:function(e){var i;try{i=new window.Blob([e.response])}catch(t){var n=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder;if("TypeError"===t.name&&n){var r=new n;r.append(e.response),i=r.getBlob()}}0===i.size&&(t.errorMsg="Empty image response.",t.finish(!1));var o=(window.URL||window.webkitURL).createObjectURL(i);t.image.src=o},error:function(e){t.errorMsg="Image load aborted - XHR error",t.finish(!1)}}),this.abort=function(){t.request.abort(),"function"==typeof i&&i()}):(!1!==this.crossOriginPolicy&&(this.image.crossOrigin=this.crossOriginPolicy),this.image.src=this.src)},finish:function(e){this.image.onload=this.image.onerror=this.image.onabort=null,e||(this.image=null),this.jobId&&window.clearTimeout(this.jobId),this.callback(this)}},e.ImageLoader=function(t){e.extend(!0,this,{jobLimit:e.DEFAULT_SETTINGS.imageLoaderLimit,timeout:e.DEFAULT_SETTINGS.timeout,jobQueue:[],jobsInProgress:0},t)},e.ImageLoader.prototype={addJob:function(e){var i=this,n=new t({src:e.src,loadWithAjax:e.loadWithAjax,ajaxHeaders:e.loadWithAjax?e.ajaxHeaders:null,crossOriginPolicy:e.crossOriginPolicy,ajaxWithCredentials:e.ajaxWithCredentials,callback:function(t){!function(e,t,i){e.jobsInProgress--,(!e.jobLimit||e.jobsInProgress0&&(e.jobQueue.shift().start(),e.jobsInProgress++);i(t.image,t.errorMsg,t.request)}(i,t,e.callback)},abort:e.abort,timeout:this.timeout});!this.jobLimit||this.jobsInProgressi&&(i=r)}return i},needsUpdate:function(){return e.console.error("[Drawer.needsUpdate] this function is deprecated. Use World.needsDraw instead."),this.viewer.world.needsDraw()},numTilesLoaded:function(){return e.console.error("[Drawer.numTilesLoaded] this function is deprecated. Use TileCache.numTilesLoaded instead."),this.viewer.tileCache.numTilesLoaded()},reset:function(){return e.console.error("[Drawer.reset] this function is deprecated. Use World.resetItems instead."),this.viewer.world.resetItems(),this},update:function(){return e.console.error("[Drawer.update] this function is deprecated. Use Drawer.clear and World.draw instead."),this.clear(),this.viewer.world.draw(),this},canRotate:function(){return this.useCanvas},destroy:function(){this.canvas.width=1,this.canvas.height=1,this.sketchCanvas=null,this.sketchContext=null},clear:function(){if(this.canvas.innerHTML="",this.useCanvas){var e=this._calculateCanvasSize();if((this.canvas.width!=e.x||this.canvas.height!=e.y)&&(this.canvas.width=e.x,this.canvas.height=e.y,this._updateImageSmoothingEnabled(this.context),null!==this.sketchCanvas)){var t=this._calculateSketchCanvasSize();this.sketchCanvas.width=t.x,this.sketchCanvas.height=t.y,this._updateImageSmoothingEnabled(this.sketchContext)}this._clear()}},_clear:function(e,t){if(this.useCanvas){var i=this._getContext(e);if(t)i.clearRect(t.x,t.y,t.width,t.height);else{var n=i.canvas;i.clearRect(0,0,n.width,n.height)}}},viewportToDrawerRectangle:function(t){var i=this.viewport.pixelFromPointNoRotate(t.getTopLeft(),!0),n=this.viewport.deltaPixelsFromPointsNoRotate(t.getSize(),!0);return new e.Rect(i.x*e.pixelDensityRatio,i.y*e.pixelDensityRatio,n.x*e.pixelDensityRatio,n.y*e.pixelDensityRatio)},drawTile:function(t,i,n,r,o){if(e.console.assert(t,"[Drawer.drawTile] tile is required"),e.console.assert(i,"[Drawer.drawTile] drawingHandler is required"),this.useCanvas){var a=this._getContext(n);r=r||1,t.drawCanvas(a,i,r,o)}else t.drawHTML(this.canvas)},_getContext:function(e){var t=this.context;if(e){if(null===this.sketchCanvas){this.sketchCanvas=document.createElement("canvas");var i=this._calculateSketchCanvasSize();if(this.sketchCanvas.width=i.x,this.sketchCanvas.height=i.y,this.sketchContext=this.sketchCanvas.getContext("2d"),0===this.viewport.getRotation()){var n=this;this.viewer.addHandler("rotate",(function e(){if(0!==n.viewport.getRotation()){n.viewer.removeHandler("rotate",e);var t=n._calculateSketchCanvasSize();n.sketchCanvas.width=t.x,n.sketchCanvas.height=t.y}}))}this._updateImageSmoothingEnabled(this.sketchContext)}t=this.sketchContext}return t},saveContext:function(e){this.useCanvas&&this._getContext(e).save()},restoreContext:function(e){this.useCanvas&&this._getContext(e).restore()},setClip:function(e,t){if(this.useCanvas){var i=this._getContext(t);i.beginPath(),i.rect(e.x,e.y,e.width,e.height),i.clip()}},drawRectangle:function(e,t,i){if(this.useCanvas){var n=this._getContext(i);n.save(),n.fillStyle=t,n.fillRect(e.x,e.y,e.width,e.height),n.restore()}},blendSketch:function(t,i,n,r){var o=t;if(e.isPlainObject(o)||(o={opacity:t,scale:i,translate:n,compositeOperation:r}),this.useCanvas&&this.sketchCanvas){t=o.opacity,r=o.compositeOperation;var a=o.bounds;if(this.context.save(),this.context.globalAlpha=t,r&&(this.context.globalCompositeOperation=r),a)a.x<0&&(a.width+=a.x,a.x=0),a.x+a.width>this.canvas.width&&(a.width=this.canvas.width-a.x),a.y<0&&(a.height+=a.y,a.y=0),a.y+a.height>this.canvas.height&&(a.height=this.canvas.height-a.y),this.context.drawImage(this.sketchCanvas,a.x,a.y,a.width,a.height,a.x,a.y,a.width,a.height);else{i=o.scale||1;var s=(n=o.translate)instanceof e.Point?n:new e.Point(0,0),l=0,c=0;if(n){var u=this.sketchCanvas.width-this.canvas.width,h=this.sketchCanvas.height-this.canvas.height;l=Math.round(u/2),c=Math.round(h/2)}this.context.drawImage(this.sketchCanvas,s.x-l*i,s.y-c*i,(this.canvas.width+2*l)*i,(this.canvas.height+2*c)*i,-l,-c,this.canvas.width+2*l,this.canvas.height+2*c)}this.context.restore()}},drawDebugInfo:function(t,i,n,r){if(this.useCanvas){var o=this.viewer.world.getIndexOfItem(r)%this.debugGridColor.length,a=this.context;a.save(),a.lineWidth=2*e.pixelDensityRatio,a.font="small-caps bold "+13*e.pixelDensityRatio+"px arial",a.strokeStyle=this.debugGridColor[o],a.fillStyle=this.debugGridColor[o],0!==this.viewport.degrees&&this._offsetForRotation({degrees:this.viewport.degrees}),r.getRotation(!0)%360!=0&&this._offsetForRotation({degrees:r.getRotation(!0),point:r.viewport.pixelFromPointNoRotate(r._getRotationPoint(!0),!0)}),0===r.viewport.degrees&&r.getRotation(!0)%360==0&&r._drawer.viewer.viewport.getFlip()&&r._drawer._flip(),a.strokeRect(t.position.x*e.pixelDensityRatio,t.position.y*e.pixelDensityRatio,t.size.x*e.pixelDensityRatio,t.size.y*e.pixelDensityRatio);var s=(t.position.x+t.size.x/2)*e.pixelDensityRatio,l=(t.position.y+t.size.y/2)*e.pixelDensityRatio;a.translate(s,l),a.rotate(Math.PI/180*-this.viewport.degrees),a.translate(-s,-l),0===t.x&&0===t.y&&(a.fillText("Zoom: "+this.viewport.getZoom(),t.position.x*e.pixelDensityRatio,(t.position.y-30)*e.pixelDensityRatio),a.fillText("Pan: "+this.viewport.getBounds().toString(),t.position.x*e.pixelDensityRatio,(t.position.y-20)*e.pixelDensityRatio)),a.fillText("Level: "+t.level,(t.position.x+10)*e.pixelDensityRatio,(t.position.y+20)*e.pixelDensityRatio),a.fillText("Column: "+t.x,(t.position.x+10)*e.pixelDensityRatio,(t.position.y+30)*e.pixelDensityRatio),a.fillText("Row: "+t.y,(t.position.x+10)*e.pixelDensityRatio,(t.position.y+40)*e.pixelDensityRatio),a.fillText("Order: "+n+" of "+i,(t.position.x+10)*e.pixelDensityRatio,(t.position.y+50)*e.pixelDensityRatio),a.fillText("Size: "+t.size.toString(),(t.position.x+10)*e.pixelDensityRatio,(t.position.y+60)*e.pixelDensityRatio),a.fillText("Position: "+t.position.toString(),(t.position.x+10)*e.pixelDensityRatio,(t.position.y+70)*e.pixelDensityRatio),0!==this.viewport.degrees&&this._restoreRotationChanges(),r.getRotation(!0)%360!=0&&this._restoreRotationChanges(),0===r.viewport.degrees&&r.getRotation(!0)%360==0&&r._drawer.viewer.viewport.getFlip()&&r._drawer._flip(),a.restore()}},debugRect:function(t){if(this.useCanvas){var i=this.context;i.save(),i.lineWidth=2*e.pixelDensityRatio,i.strokeStyle=this.debugGridColor[0],i.fillStyle=this.debugGridColor[0],i.strokeRect(t.x*e.pixelDensityRatio,t.y*e.pixelDensityRatio,t.width*e.pixelDensityRatio,t.height*e.pixelDensityRatio),i.restore()}},setImageSmoothingEnabled:function(e){this.useCanvas&&(this._imageSmoothingEnabled=e,this._updateImageSmoothingEnabled(this.context),this.viewer.forceRedraw())},_updateImageSmoothingEnabled:function(e){e.mozImageSmoothingEnabled=this._imageSmoothingEnabled,e.webkitImageSmoothingEnabled=this._imageSmoothingEnabled,e.msImageSmoothingEnabled=this._imageSmoothingEnabled,e.imageSmoothingEnabled=this._imageSmoothingEnabled},getCanvasSize:function(t){var i=this._getContext(t).canvas;return new e.Point(i.width,i.height)},getCanvasCenter:function(){return new e.Point(this.canvas.width/2,this.canvas.height/2)},_offsetForRotation:function(t){var i=t.point?t.point.times(e.pixelDensityRatio):this.getCanvasCenter(),n=this._getContext(t.useSketch);n.save(),n.translate(i.x,i.y),this.viewer.viewport.flipped?(n.rotate(Math.PI/180*-t.degrees),n.scale(-1,1)):n.rotate(Math.PI/180*t.degrees),n.translate(-i.x,-i.y)},_flip:function(t){var i=(t=t||{}).point?t.point.times(e.pixelDensityRatio):this.getCanvasCenter(),n=this._getContext(t.useSketch);n.translate(i.x,0),n.scale(-1,1),n.translate(-i.x,0)},_restoreRotationChanges:function(e){this._getContext(e).restore()},_calculateCanvasSize:function(){var t=e.pixelDensityRatio,i=this.viewport.getContainerSize();return{x:Math.round(i.x*t),y:Math.round(i.y*t)}},_calculateSketchCanvasSize:function(){var e=this._calculateCanvasSize();if(0===this.viewport.getRotation())return e;var t=Math.ceil(Math.sqrt(e.x*e.x+e.y*e.y));return{x:t,y:t}}}}(OpenSeadragon),function(e){e.Viewport=function(t){var i=arguments;i.length&&i[0]instanceof e.Point&&(t={containerSize:i[0],contentSize:i[1],config:i[2]}),t.config&&(e.extend(!0,t,t.config),delete t.config),this._margins=e.extend({left:0,top:0,right:0,bottom:0},t.margins||{}),delete t.margins,e.extend(!0,this,{containerSize:null,contentSize:null,zoomPoint:null,viewer:null,springStiffness:e.DEFAULT_SETTINGS.springStiffness,animationTime:e.DEFAULT_SETTINGS.animationTime,minZoomImageRatio:e.DEFAULT_SETTINGS.minZoomImageRatio,maxZoomPixelRatio:e.DEFAULT_SETTINGS.maxZoomPixelRatio,visibilityRatio:e.DEFAULT_SETTINGS.visibilityRatio,wrapHorizontal:e.DEFAULT_SETTINGS.wrapHorizontal,wrapVertical:e.DEFAULT_SETTINGS.wrapVertical,defaultZoomLevel:e.DEFAULT_SETTINGS.defaultZoomLevel,minZoomLevel:e.DEFAULT_SETTINGS.minZoomLevel,maxZoomLevel:e.DEFAULT_SETTINGS.maxZoomLevel,degrees:e.DEFAULT_SETTINGS.degrees,flipped:e.DEFAULT_SETTINGS.flipped,homeFillsViewer:e.DEFAULT_SETTINGS.homeFillsViewer},t),this._updateContainerInnerSize(),this.centerSpringX=new e.Spring({initial:0,springStiffness:this.springStiffness,animationTime:this.animationTime}),this.centerSpringY=new e.Spring({initial:0,springStiffness:this.springStiffness,animationTime:this.animationTime}),this.zoomSpring=new e.Spring({exponential:!0,initial:1,springStiffness:this.springStiffness,animationTime:this.animationTime}),this._oldCenterX=this.centerSpringX.current.value,this._oldCenterY=this.centerSpringY.current.value,this._oldZoom=this.zoomSpring.current.value,this._setContentBounds(new e.Rect(0,0,1,1),1),this.goHome(!0),this.update()},e.Viewport.prototype={resetContentSize:function(t){return e.console.assert(t,"[Viewport.resetContentSize] contentSize is required"),e.console.assert(t instanceof e.Point,"[Viewport.resetContentSize] contentSize must be an OpenSeadragon.Point"),e.console.assert(t.x>0,"[Viewport.resetContentSize] contentSize.x must be greater than 0"),e.console.assert(t.y>0,"[Viewport.resetContentSize] contentSize.y must be greater than 0"),this._setContentBounds(new e.Rect(0,0,1,t.y/t.x),t.x),this},setHomeBounds:function(t,i){e.console.error("[Viewport.setHomeBounds] this function is deprecated; The content bounds should not be set manually."),this._setContentBounds(t,i)},_setContentBounds:function(t,i){e.console.assert(t,"[Viewport._setContentBounds] bounds is required"),e.console.assert(t instanceof e.Rect,"[Viewport._setContentBounds] bounds must be an OpenSeadragon.Rect"),e.console.assert(t.width>0,"[Viewport._setContentBounds] bounds.width must be greater than 0"),e.console.assert(t.height>0,"[Viewport._setContentBounds] bounds.height must be greater than 0"),this._contentBoundsNoRotate=t.clone(),this._contentSizeNoRotate=this._contentBoundsNoRotate.getSize().times(i),this._contentBounds=t.rotate(this.degrees).getBoundingBox(),this._contentSize=this._contentBounds.getSize().times(i),this._contentAspectRatio=this._contentSize.x/this._contentSize.y,this.viewer&&this.viewer.raiseEvent("reset-size",{contentSize:this._contentSizeNoRotate.clone(),contentFactor:i,homeBounds:this._contentBoundsNoRotate.clone(),contentBounds:this._contentBounds.clone()})},getHomeZoom:function(){if(this.defaultZoomLevel)return this.defaultZoomLevel;var e=this._contentAspectRatio/this.getAspectRatio();return(this.homeFillsViewer?e>=1?e:1:e>=1?1:e)/this._contentBounds.width},getHomeBounds:function(){return this.getHomeBoundsNoRotate().rotate(-this.getRotation())},getHomeBoundsNoRotate:function(){var t=this._contentBounds.getCenter(),i=1/this.getHomeZoom(),n=i/this.getAspectRatio();return new e.Rect(t.x-i/2,t.y-n/2,i,n)},goHome:function(e){return this.viewer&&this.viewer.raiseEvent("home",{immediately:e}),this.fitBounds(this.getHomeBounds(),e)},getMinZoom:function(){var e=this.getHomeZoom();return this.minZoomLevel?this.minZoomLevel:this.minZoomImageRatio*e},getMaxZoom:function(){var e=this.maxZoomLevel;return e||(e=this._contentSize.x*this.maxZoomPixelRatio/this._containerInnerSize.x,e/=this._contentBounds.width),Math.max(e,this.getHomeZoom())},getAspectRatio:function(){return this._containerInnerSize.x/this._containerInnerSize.y},getContainerSize:function(){return new e.Point(this.containerSize.x,this.containerSize.y)},getMargins:function(){return e.extend({},this._margins)},setMargins:function(t){e.console.assert("object"===e.type(t),"[Viewport.setMargins] margins must be an object"),this._margins=e.extend({left:0,top:0,right:0,bottom:0},t),this._updateContainerInnerSize(),this.viewer&&this.viewer.forceRedraw()},getBounds:function(e){return this.getBoundsNoRotate(e).rotate(-this.getRotation())},getBoundsNoRotate:function(t){var i=this.getCenter(t),n=1/this.getZoom(t),r=n/this.getAspectRatio();return new e.Rect(i.x-n/2,i.y-r/2,n,r)},getBoundsWithMargins:function(e){return this.getBoundsNoRotateWithMargins(e).rotate(-this.getRotation(),this.getCenter(e))},getBoundsNoRotateWithMargins:function(e){var t=this.getBoundsNoRotate(e),i=this._containerInnerSize.x*this.getZoom(e);return t.x-=this._margins.left/i,t.y-=this._margins.top/i,t.width+=(this._margins.left+this._margins.right)/i,t.height+=(this._margins.top+this._margins.bottom)/i,t},getCenter:function(t){var i,n,r,o,a,s,l=new e.Point(this.centerSpringX.current.value,this.centerSpringY.current.value),c=new e.Point(this.centerSpringX.target.value,this.centerSpringY.target.value);return t?l:this.zoomPoint?(i=this.pixelFromPoint(this.zoomPoint,!0),o=(r=1/(n=this.getZoom()))/this.getAspectRatio(),a=new e.Rect(l.x-r/2,l.y-o/2,r,o),s=this._pixelFromPoint(this.zoomPoint,a).minus(i).divide(this._containerInnerSize.x*n),c.plus(s)):c},getZoom:function(e){return e?this.zoomSpring.current.value:this.zoomSpring.target.value},_applyZoomConstraints:function(e){return Math.max(Math.min(e,this.getMaxZoom()),this.getMinZoom())},_applyBoundaryConstraints:function(t){var i=new e.Rect(t.x,t.y,t.width,t.height);if(this.wrapHorizontal);else{var n=this.visibilityRatio*i.width,r=i.x+i.width,o=this._contentBoundsNoRotate.x+this._contentBoundsNoRotate.width,a=this._contentBoundsNoRotate.x-r+n,s=o-i.x-n;n>this._contentBoundsNoRotate.width?i.x+=(a+s)/2:s<0?i.x+=s:a>0&&(i.x+=a)}if(this.wrapVertical);else{var l=this.visibilityRatio*i.height,c=i.y+i.height,u=this._contentBoundsNoRotate.y+this._contentBoundsNoRotate.height,h=this._contentBoundsNoRotate.y-c+l,d=u-i.y-l;l>this._contentBoundsNoRotate.height?i.y+=(h+d)/2:d<0?i.y+=d:h>0&&(i.y+=h)}return i},_raiseConstraintsEvent:function(e){this.viewer&&this.viewer.raiseEvent("constrain",{immediately:e})},applyConstraints:function(e){var t=this.getZoom(),i=this._applyZoomConstraints(t);t!==i&&this.zoomTo(i,this.zoomPoint,e);var n=this.getBoundsNoRotate(),r=this._applyBoundaryConstraints(n);return this._raiseConstraintsEvent(e),(n.x!==r.x||n.y!==r.y||e)&&this.fitBounds(r.rotate(-this.getRotation()),e),this},ensureVisible:function(e){return this.applyConstraints(e)},_fitBounds:function(t,i){var n=(i=i||{}).immediately||!1,r=i.constraints||!1,o=this.getAspectRatio(),a=t.getCenter(),s=new e.Rect(t.x,t.y,t.width,t.height,t.degrees+this.getRotation()).getBoundingBox();s.getAspectRatio()>=o?s.height=s.width/o:s.width=s.height*o,s.x=a.x-s.width/2,s.y=a.y-s.height/2;var l=1/s.width;if(r){var c=s.getAspectRatio(),u=this._applyZoomConstraints(l);l!==u&&(l=u,s.width=1/l,s.x=a.x-s.width/2,s.height=s.width/c,s.y=a.y-s.height/2),a=(s=this._applyBoundaryConstraints(s)).getCenter(),this._raiseConstraintsEvent(n)}if(n)return this.panTo(a,!0),this.zoomTo(l,null,!0);this.panTo(this.getCenter(!0),!0),this.zoomTo(this.getZoom(!0),null,!0);var h=this.getBounds(),d=this.getZoom();if(0===d||Math.abs(l/d-1)<1e-8)return this.zoomTo(l,!0),this.panTo(a,n);var p=(s=s.rotate(-this.getRotation())).getTopLeft().times(l).minus(h.getTopLeft().times(d)).divide(l-d);return this.zoomTo(l,p,n)},fitBounds:function(e,t){return this._fitBounds(e,{immediately:t,constraints:!1})},fitBoundsWithConstraints:function(e,t){return this._fitBounds(e,{immediately:t,constraints:!0})},fitVertically:function(t){var i=new e.Rect(this._contentBounds.x+this._contentBounds.width/2,this._contentBounds.y,0,this._contentBounds.height);return this.fitBounds(i,t)},fitHorizontally:function(t){var i=new e.Rect(this._contentBounds.x,this._contentBounds.y+this._contentBounds.height/2,this._contentBounds.width,0);return this.fitBounds(i,t)},getConstrainedBounds:function(e){var t;return t=this.getBounds(e),this._applyBoundaryConstraints(t)},panBy:function(t,i){var n=new e.Point(this.centerSpringX.target.value,this.centerSpringY.target.value);return this.panTo(n.plus(t),i)},panTo:function(e,t){return t?(this.centerSpringX.resetTo(e.x),this.centerSpringY.resetTo(e.y)):(this.centerSpringX.springTo(e.x),this.centerSpringY.springTo(e.y)),this.viewer&&this.viewer.raiseEvent("pan",{center:e,immediately:t}),this},zoomBy:function(e,t,i){return this.zoomTo(this.zoomSpring.target.value*e,t,i)},zoomTo:function(t,i,n){var r=this;return this.zoomPoint=i instanceof e.Point&&!isNaN(i.x)&&!isNaN(i.y)?i:null,n?this._adjustCenterSpringsForZoomPoint((function(){r.zoomSpring.resetTo(t)})):this.zoomSpring.springTo(t),this.viewer&&this.viewer.raiseEvent("zoom",{zoom:t,refPoint:i,immediately:n}),this},setRotation:function(t){return this.viewer&&this.viewer.drawer.canRotate()?(this.degrees=e.positiveModulo(t,360),this._setContentBounds(this.viewer.world.getHomeBounds(),this.viewer.world.getContentFactor()),this.viewer.forceRedraw(),this.viewer.raiseEvent("rotate",{degrees:t}),this):this},getRotation:function(){return this.degrees},resize:function(e,t){var i,n=this.getBoundsNoRotate(),r=n;return this.containerSize.x=e.x,this.containerSize.y=e.y,this._updateContainerInnerSize(),t&&(i=e.x/this.containerSize.x,r.width=n.width*i,r.height=r.width/this.getAspectRatio()),this.viewer&&this.viewer.raiseEvent("resize",{newContainerSize:e,maintain:t}),this.fitBounds(r,!0)},_updateContainerInnerSize:function(){this._containerInnerSize=new e.Point(Math.max(1,this.containerSize.x-(this._margins.left+this._margins.right)),Math.max(1,this.containerSize.y-(this._margins.top+this._margins.bottom)))},update:function(){var e=this;this._adjustCenterSpringsForZoomPoint((function(){e.zoomSpring.update()})),this.centerSpringX.update(),this.centerSpringY.update();var t=this.centerSpringX.current.value!==this._oldCenterX||this.centerSpringY.current.value!==this._oldCenterY||this.zoomSpring.current.value!==this._oldZoom;return this._oldCenterX=this.centerSpringX.current.value,this._oldCenterY=this.centerSpringY.current.value,this._oldZoom=this.zoomSpring.current.value,t},_adjustCenterSpringsForZoomPoint:function(e){if(this.zoomPoint){var t=this.pixelFromPoint(this.zoomPoint,!0);e();var i=this.pixelFromPoint(this.zoomPoint,!0).minus(t),n=this.deltaPointsFromPixels(i,!0);this.centerSpringX.shiftBy(n.x),this.centerSpringY.shiftBy(n.y),this.zoomSpring.isAtTargetValue()&&(this.zoomPoint=null)}else e()},deltaPixelsFromPointsNoRotate:function(e,t){return e.times(this._containerInnerSize.x*this.getZoom(t))},deltaPixelsFromPoints:function(e,t){return this.deltaPixelsFromPointsNoRotate(e.rotate(this.getRotation()),t)},deltaPointsFromPixelsNoRotate:function(e,t){return e.divide(this._containerInnerSize.x*this.getZoom(t))},deltaPointsFromPixels:function(e,t){return this.deltaPointsFromPixelsNoRotate(e,t).rotate(-this.getRotation())},pixelFromPointNoRotate:function(e,t){return this._pixelFromPointNoRotate(e,this.getBoundsNoRotate(t))},pixelFromPoint:function(e,t){return this._pixelFromPoint(e,this.getBoundsNoRotate(t))},_pixelFromPointNoRotate:function(t,i){return t.minus(i.getTopLeft()).times(this._containerInnerSize.x/i.width).plus(new e.Point(this._margins.left,this._margins.top))},_pixelFromPoint:function(e,t){return this._pixelFromPointNoRotate(e.rotate(this.getRotation(),this.getCenter(!0)),t)},pointFromPixelNoRotate:function(t,i){var n=this.getBoundsNoRotate(i);return t.minus(new e.Point(this._margins.left,this._margins.top)).divide(this._containerInnerSize.x/n.width).plus(n.getTopLeft())},pointFromPixel:function(e,t){return this.pointFromPixelNoRotate(e,t).rotate(-this.getRotation(),this.getCenter(!0))},_viewportToImageDelta:function(t,i){var n=this._contentBoundsNoRotate.width;return new e.Point(t*this._contentSizeNoRotate.x/n,i*this._contentSizeNoRotate.x/n)},viewportToImageCoordinates:function(t,i){if(t instanceof e.Point)return this.viewportToImageCoordinates(t.x,t.y);if(this.viewer){var n=this.viewer.world.getItemCount();if(n>1)e.console.error("[Viewport.viewportToImageCoordinates] is not accurate with multi-image; use TiledImage.viewportToImageCoordinates instead.");else if(1===n){return this.viewer.world.getItemAt(0).viewportToImageCoordinates(t,i,!0)}}return this._viewportToImageDelta(t-this._contentBoundsNoRotate.x,i-this._contentBoundsNoRotate.y)},_imageToViewportDelta:function(t,i){var n=this._contentBoundsNoRotate.width;return new e.Point(t/this._contentSizeNoRotate.x*n,i/this._contentSizeNoRotate.x*n)},imageToViewportCoordinates:function(t,i){if(t instanceof e.Point)return this.imageToViewportCoordinates(t.x,t.y);if(this.viewer){var n=this.viewer.world.getItemCount();if(n>1)e.console.error("[Viewport.imageToViewportCoordinates] is not accurate with multi-image; use TiledImage.imageToViewportCoordinates instead.");else if(1===n){return this.viewer.world.getItemAt(0).imageToViewportCoordinates(t,i,!0)}}var r=this._imageToViewportDelta(t,i);return r.x+=this._contentBoundsNoRotate.x,r.y+=this._contentBoundsNoRotate.y,r},imageToViewportRectangle:function(t,i,n,r){var o=t;if(o instanceof e.Rect||(o=new e.Rect(t,i,n,r)),this.viewer){var a=this.viewer.world.getItemCount();if(a>1)e.console.error("[Viewport.imageToViewportRectangle] is not accurate with multi-image; use TiledImage.imageToViewportRectangle instead.");else if(1===a){return this.viewer.world.getItemAt(0).imageToViewportRectangle(t,i,n,r,!0)}}var s=this.imageToViewportCoordinates(o.x,o.y),l=this._imageToViewportDelta(o.width,o.height);return new e.Rect(s.x,s.y,l.x,l.y,o.degrees)},viewportToImageRectangle:function(t,i,n,r){var o=t;if(o instanceof e.Rect||(o=new e.Rect(t,i,n,r)),this.viewer){var a=this.viewer.world.getItemCount();if(a>1)e.console.error("[Viewport.viewportToImageRectangle] is not accurate with multi-image; use TiledImage.viewportToImageRectangle instead.");else if(1===a){return this.viewer.world.getItemAt(0).viewportToImageRectangle(t,i,n,r,!0)}}var s=this.viewportToImageCoordinates(o.x,o.y),l=this._viewportToImageDelta(o.width,o.height);return new e.Rect(s.x,s.y,l.x,l.y,o.degrees)},viewerElementToImageCoordinates:function(e){var t=this.pointFromPixel(e,!0);return this.viewportToImageCoordinates(t)},imageToViewerElementCoordinates:function(e){var t=this.imageToViewportCoordinates(e);return this.pixelFromPoint(t,!0)},windowToImageCoordinates:function(t){e.console.assert(this.viewer,"[Viewport.windowToImageCoordinates] the viewport must have a viewer.");var i=t.minus(e.getElementPosition(this.viewer.element));return this.viewerElementToImageCoordinates(i)},imageToWindowCoordinates:function(t){return e.console.assert(this.viewer,"[Viewport.imageToWindowCoordinates] the viewport must have a viewer."),this.imageToViewerElementCoordinates(t).plus(e.getElementPosition(this.viewer.element))},viewerElementToViewportCoordinates:function(e){return this.pointFromPixel(e,!0)},viewportToViewerElementCoordinates:function(e){return this.pixelFromPoint(e,!0)},viewerElementToViewportRectangle:function(t){return e.Rect.fromSummits(this.pointFromPixel(t.getTopLeft(),!0),this.pointFromPixel(t.getTopRight(),!0),this.pointFromPixel(t.getBottomLeft(),!0))},viewportToViewerElementRectangle:function(t){return e.Rect.fromSummits(this.pixelFromPoint(t.getTopLeft(),!0),this.pixelFromPoint(t.getTopRight(),!0),this.pixelFromPoint(t.getBottomLeft(),!0))},windowToViewportCoordinates:function(t){e.console.assert(this.viewer,"[Viewport.windowToViewportCoordinates] the viewport must have a viewer.");var i=t.minus(e.getElementPosition(this.viewer.element));return this.viewerElementToViewportCoordinates(i)},viewportToWindowCoordinates:function(t){return e.console.assert(this.viewer,"[Viewport.viewportToWindowCoordinates] the viewport must have a viewer."),this.viewportToViewerElementCoordinates(t).plus(e.getElementPosition(this.viewer.element))},viewportToImageZoom:function(t){if(this.viewer){var i=this.viewer.world.getItemCount();if(i>1)e.console.error("[Viewport.viewportToImageZoom] is not accurate with multi-image.");else if(1===i){return this.viewer.world.getItemAt(0).viewportToImageZoom(t)}}var n=this._contentSizeNoRotate.x;return t*(this._containerInnerSize.x/n*this._contentBoundsNoRotate.width)},imageToViewportZoom:function(t){if(this.viewer){var i=this.viewer.world.getItemCount();if(i>1)e.console.error("[Viewport.imageToViewportZoom] is not accurate with multi-image.");else if(1===i){return this.viewer.world.getItemAt(0).imageToViewportZoom(t)}}return t*(this._contentSizeNoRotate.x/this._containerInnerSize.x/this._contentBoundsNoRotate.width)},toggleFlip:function(){return this.setFlip(!this.getFlip()),this},getFlip:function(){return this.flipped},setFlip:function(e){return this.flipped===e?this:(this.flipped=e,this.viewer.navigator&&this.viewer.navigator.setFlip(this.getFlip()),this.viewer.forceRedraw(),this.viewer.raiseEvent("flip",{flipped:e}),this)}}}(OpenSeadragon),function(e){function t(e,t,n,r,o,a,l,c,u){var h=l.getBoundingBox().getTopLeft(),d=l.getBoundingBox().getBottomRight();e.viewer&&e.viewer.raiseEvent("update-level",{tiledImage:e,havedrawn:t,level:r,opacity:o,visibility:a,drawArea:l,topleft:h,bottomright:d,currenttime:c,best:u}),s(e.coverage,r),s(e.loadingCoverage,r);for(var p=e._getCornerTiles(r,h,d),g=p.topLeft,m=p.bottomRight,f=e.source.getNumTiles(r),v=e.viewport.pixelFromPoint(e.viewport.getCenter()),y=g.x;y<=m.x;y++)for(var w=g.y;w<=m.y;w++){if(!e.wrapHorizontal&&!e.wrapVertical){var _=e.source.getTileBounds(r,y,w);if(null===l.intersection(_))continue}u=i(e,n,t,y,w,r,o,a,v,f,c,u)}return u}function i(t,i,r,s,l,c,u,h,d,p,g,m){var f=function(t,i,n,r,o,a,s,l,c,u){var h,d,p,g,m,f,v,y,w;a[n]||(a[n]={});a[n][t]||(a[n][t]={});a[n][t][i]||(h=(l.x+t%l.x)%l.x,d=(l.y+i%l.y)%l.y,p=o.getTileBounds(n,h,d),g=o.getTileBounds(n,h,d,!0),m=o.tileExists(n,h,d),f=o.getTileUrl(n,h,d),r.loadTilesWithAjax?(v=o.getTileAjaxHeaders(n,h,d),e.isPlainObject(r.ajaxHeaders)&&(v=e.extend({},r.ajaxHeaders,v))):v=null,y=o.getContext2D?o.getContext2D(n,h,d):void 0,p.x+=(t-h)/l.x,p.y+=u/c*((i-d)/l.y),w=new e.Tile(n,t,i,p,m,f,y,r.loadTilesWithAjax,v,g),h===l.x-1&&(w.isRightMost=!0),d===l.y-1&&(w.isBottomMost=!0),a[n][t][i]=w);return(w=a[n][t][i]).lastTouchTime=s,w}(s,l,c,t,t.source,t.tilesMatrix,g,p,t._worldWidthCurrent,t._worldHeightCurrent),v=r;t.viewer&&t.viewer.raiseEvent("update-tile",{tiledImage:t,tile:f}),a(t.coverage,c,s,l,!1);var y=f.loaded||f.loading||o(t.loadingCoverage,c,s,l);if(a(t.loadingCoverage,c,s,l,y),!f.exists)return m;if(i&&!v&&(o(t.coverage,c,s,l)?a(t.coverage,c,s,l,!0):v=!0),!v)return m;if(function(t,i,n,r,o,a){var s=t.bounds.getTopLeft();s.x*=a._scaleSpring.current.value,s.y*=a._scaleSpring.current.value,s.x+=a._xSpring.current.value,s.y+=a._ySpring.current.value;var l=t.bounds.getSize();l.x*=a._scaleSpring.current.value,l.y*=a._scaleSpring.current.value;var c=n.pixelFromPointNoRotate(s,!0),u=n.pixelFromPointNoRotate(s,!1),h=n.deltaPixelsFromPointsNoRotate(l,!0),d=n.deltaPixelsFromPointsNoRotate(l,!1),p=u.plus(d.divide(2)),g=r.squaredDistanceTo(p);i||(h=h.plus(new e.Point(1,1)));t.isRightMost&&a.wrapHorizontal&&(h.x+=.75);t.isBottomMost&&a.wrapVertical&&(h.y+=.75);t.position=c,t.size=h,t.squaredDistance=g,t.visibility=o}(f,t.source.tileOverlap,t.viewport,d,h,t),!f.loaded)if(f.context2D)n(t,f);else{var w=t._tileCache.getImageRecord(f.cacheKey);if(w)n(t,f,w.getImage())}f.loaded?function(e,t,i,n,r,o,s){var l,c,u=1e3*e.blendTime;t.blendStart||(t.blendStart=s);l=s-t.blendStart,c=u?Math.min(1,l/u):1,e.alwaysBlend&&(c*=o);if(t.opacity=c,e.lastDrawn.push(t),1===c)a(e.coverage,r,i,n,!0),e._hasOpaqueTile=!0;else if(le.visibility)return t;if(t.visibility==e.visibility&&t.squaredDistanceo?(a=this._clip.x/this._clip.height*t.height,s=this._clip.y/this._clip.height*t.height):(a=this._clip.x/this._clip.width*t.width,s=this._clip.y/this._clip.width*t.width)),t.getAspectRatio()>o){var u=t.height/c,h=0;r.isHorizontallyCentered?h=(t.width-t.height*o)/2:r.isRight&&(h=t.width-t.height*o),this.setPosition(new e.Point(t.x-a+h,t.y-s),n),this.setHeight(u,n)}else{var d=t.width/l,p=0;r.isVerticallyCentered?p=(t.height-t.width/o)/2:r.isBottom&&(p=t.height-t.width/o),this.setPosition(new e.Point(t.x-a,t.y-s+p),n),this.setWidth(d,n)}},getClip:function(){return this._clip?this._clip.clone():null},setClip:function(t){e.console.assert(!t||t instanceof e.Rect,"[TiledImage.setClip] newClip must be an OpenSeadragon.Rect or null"),t instanceof e.Rect?this._clip=t.clone():this._clip=null,this._needsDraw=!0,this.raiseEvent("clip-change")},getOpacity:function(){return this.opacity},setOpacity:function(e){e!==this.opacity&&(this.opacity=e,this._needsDraw=!0,this.raiseEvent("opacity-change",{opacity:this.opacity}))},getPreload:function(){return this._preload},setPreload:function(e){this._preload=!!e,this._needsDraw=!0},getRotation:function(e){return e?this._degreesSpring.current.value:this._degreesSpring.target.value},setRotation:function(e,t){this._degreesSpring.target.value===e&&this._degreesSpring.isAtTargetValue()||(t?this._degreesSpring.resetTo(e):this._degreesSpring.springTo(e),this._needsDraw=!0,this._raiseBoundsChange())},_getRotationPoint:function(e){return this.getBoundsNoRotate(e).getCenter()},getCompositeOperation:function(){return this.compositeOperation},setCompositeOperation:function(e){e!==this.compositeOperation&&(this.compositeOperation=e,this._needsDraw=!0,this.raiseEvent("composite-operation-change",{compositeOperation:this.compositeOperation}))},_setScale:function(e,t){var i=this._scaleSpring.target.value===e;if(t){if(i&&this._scaleSpring.current.value===e)return;this._scaleSpring.resetTo(e),this._updateForScale(),this._needsDraw=!0}else{if(i)return;this._scaleSpring.springTo(e),this._updateForScale(),this._needsDraw=!0}i||this._raiseBoundsChange()},_updateForScale:function(){this._worldWidthTarget=this._scaleSpring.target.value,this._worldHeightTarget=this.normHeight*this._scaleSpring.target.value,this._worldWidthCurrent=this._scaleSpring.current.value,this._worldHeightCurrent=this.normHeight*this._scaleSpring.current.value},_raiseBoundsChange:function(){this.raiseEvent("bounds-change")},_isBottomItem:function(){return this.viewer.world.getItemAt(0)===this},_getLevelsInterval:function(){var e=Math.max(this.source.minLevel,Math.floor(Math.log(this.minZoomImageRatio)/Math.log(2))),t=this.viewport.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(0),!0).x*this._scaleSpring.current.value,i=Math.min(Math.abs(this.source.maxLevel),Math.abs(Math.floor(Math.log(t/this.minPixelRatio)/Math.log(2))));return i=Math.max(i,this.source.minLevel||0),{lowestLevel:e=Math.min(e,i),highestLevel:i}},_updateViewport:function(){for(this._needsDraw=!1,this._tilesLoading=0,this.loadingCoverage={};this.lastDrawn.length>0;){this.lastDrawn.pop().beingDrawn=!1}var i=this.viewport,o=this._viewportToTiledImageRectangle(i.getBoundsWithMargins(!0));if(!this.wrapHorizontal&&!this.wrapVertical){var a=this._viewportToTiledImageRectangle(this.getClippedBounds(!0));if(null===(o=o.intersection(a)))return}for(var s=this._getLevelsInterval(),l=s.lowestLevel,c=s.highestLevel,u=null,h=!1,d=e.now(),p=c;p>=l;p--){var g=!1,m=i.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(p),!0).x*this._scaleSpring.current.value;if(p===l||!h&&m>=this.minPixelRatio)g=!0,h=!0;else if(!h)continue;var f=i.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(p),!1).x*this._scaleSpring.current.value,v=i.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(Math.max(this.source.getClosestLevel(),0)),!1).x*this._scaleSpring.current.value,y=this.immediateRender?1:v;if(u=t(this,h,g,p,Math.min(1,(m-.5)/.5),y/Math.abs(y-f),o,d,u),r(this.coverage,p))break}!function(t,i){if(0===t.opacity||0===i.length&&!t.placeholderFillStyle)return;var n,r,o,a=i[0];a&&(n=t.opacity<1||t.compositeOperation&&"source-over"!==t.compositeOperation||!t._isBottomItem()&&a._hasTransparencyChannel());var s,l=t.viewport.getZoom(!0),c=t.viewportToImageZoom(l);i.length>1&&c>t.smoothTileEdgesMinZoom&&!t.iOSDevice&&t.getRotation(!0)%360==0&&e.supportsCanvas&&(n=!0,r=a.getScaleForEdgeSmoothing(),o=a.getTranslationForEdgeSmoothing(r,t._drawer.getCanvasSize(!1),t._drawer.getCanvasSize(!0)));n&&(r||(s=t.viewport.viewportToViewerElementRectangle(t.getClippedBounds(!0)).getIntegerBoundingBox().times(e.pixelDensityRatio),t._drawer.viewer.viewport.getFlip()&&(0===t.viewport.degrees&&t.getRotation(!0)%360==0||(s.x=t._drawer.viewer.container.clientWidth-(s.x+s.width)))),t._drawer._clear(!0,s));r||(0!==t.viewport.degrees&&t._drawer._offsetForRotation({degrees:t.viewport.degrees,useSketch:n}),t.getRotation(!0)%360!=0&&t._drawer._offsetForRotation({degrees:t.getRotation(!0),point:t.viewport.pixelFromPointNoRotate(t._getRotationPoint(!0),!0),useSketch:n}),0===t.viewport.degrees&&t.getRotation(!0)%360==0&&t._drawer.viewer.viewport.getFlip()&&t._drawer._flip());var u=!1;if(t._clip){t._drawer.saveContext(n);var h=t.imageToViewportRectangle(t._clip,!0);h=h.rotate(-t.getRotation(!0),t._getRotationPoint(!0));var d=t._drawer.viewportToDrawerRectangle(h);r&&(d=d.times(r)),o&&(d=d.translate(o)),t._drawer.setClip(d,n),u=!0}if(t.placeholderFillStyle&&!1===t._hasOpaqueTile){var p=t._drawer.viewportToDrawerRectangle(t.getBounds(!0));r&&(p=p.times(r)),o&&(p=p.translate(o));var g=null;g="function"==typeof t.placeholderFillStyle?t.placeholderFillStyle(t,t._drawer.context):t.placeholderFillStyle,t._drawer.drawRectangle(p,g,n)}for(var m=i.length-1;m>=0;m--)a=i[m],t._drawer.drawTile(a,t._drawingHandler,n,r,o),a.beingDrawn=!0,t.viewer&&t.viewer.raiseEvent("tile-drawn",{tiledImage:t,tile:a});u&&t._drawer.restoreContext(n);r||(t.getRotation(!0)%360!=0&&t._drawer._restoreRotationChanges(n),0!==t.viewport.degrees&&t._drawer._restoreRotationChanges(n));n&&(r&&(0!==t.viewport.degrees&&t._drawer._offsetForRotation({degrees:t.viewport.degrees,useSketch:!1}),t.getRotation(!0)%360!=0&&t._drawer._offsetForRotation({degrees:t.getRotation(!0),point:t.viewport.pixelFromPointNoRotate(t._getRotationPoint(!0),!0),useSketch:!1})),t._drawer.blendSketch({opacity:t.opacity,scale:r,translate:o,compositeOperation:t.compositeOperation,bounds:s}),r&&(t.getRotation(!0)%360!=0&&t._drawer._restoreRotationChanges(!1),0!==t.viewport.degrees&&t._drawer._restoreRotationChanges(!1)));r||0===t.viewport.degrees&&t.getRotation(!0)%360==0&&t._drawer.viewer.viewport.getFlip()&&t._drawer._flip();!function(t,i){if(t.debugMode)for(var n=i.length-1;n>=0;n--){var r=i[n];try{t._drawer.drawDebugInfo(r,i.length,n,t)}catch(t){e.console.error(t)}}}(t,i)}(this,this.lastDrawn),u&&!u.context2D?(!function(t,i,r){i.loading=!0,t._imageLoader.addJob({src:i.url,loadWithAjax:i.loadWithAjax,ajaxHeaders:i.ajaxHeaders,crossOriginPolicy:t.crossOriginPolicy,ajaxWithCredentials:t.ajaxWithCredentials,callback:function(o,a,s){!function(t,i,r,o,a,s){if(!o)return e.console.log("Tile %s failed to load: %s - error: %s",i,i.url,a),t.viewer.raiseEvent("tile-load-failed",{tile:i,tiledImage:t,time:r,message:a,tileRequest:s}),i.loading=!1,void(i.exists=!1);if(rthis._maxImageCacheCount){for(var s,l,c,u,h,d,p=null,g=-1,m=null,f=this._tilesLoaded.length-1;f>=0;f--)(s=(d=this._tilesLoaded[f]).tile).level<=r||s.beingDrawn||(p?(u=s.lastTouchTime,l=p.lastTouchTime,h=s.level,c=p.level,(uc)&&(p=s,g=f,m=d)):(p=s,g=f,m=d));p&&g>=0&&(this._unloadTile(m),o=g)}this._tilesLoaded[o]=new t({tile:n.tile,tiledImage:n.tiledImage})},clearTilesFor:function(t){var i;e.console.assert(t,"[TileCache.clearTilesFor] tiledImage is required");for(var n=0;n=this._items.length)throw new Error("Index bigger than number of layers.");i!==n&&-1!==n&&(this._items.splice(n,1),this._items.splice(i,0,t),this._needsDraw=!0,this.raiseEvent("item-index-change",{item:t,previousIndex:n,newIndex:i}))},removeItem:function(t){e.console.assert(t,"[World.removeItem] item is required");var i=e.indexOf(this._items,t);-1!==i&&(t.removeHandler("bounds-change",this._delegatedFigureSizes),t.removeHandler("clip-change",this._delegatedFigureSizes),t.destroy(),this._items.splice(i,1),this._figureSizes(),this._needsDraw=!0,this._raiseRemoveItem(t))},removeAll:function(){var e,t;for(this.viewer._cancelPendingImages(),t=0;tu.height?s:s*(u.width/u.height))*(u.height/u.width),p=new e.Point(g+(s-h)/2,m+(s-d)/2),c.setPosition(p,n),c.setWidth(h,n),"horizontal"===r?g+=l:m+=l;this.setAutoRefigureSizes(!0)},_figureSizes:function(){var t=this._homeBounds?this._homeBounds.clone():null,i=this._contentSize?this._contentSize.clone():null,n=this._contentFactor||0;if(this._items.length){var r=this._items[0],o=r.getBounds();this._contentFactor=r.getContentSize().x/o.width;for(var a=r.getClippedBounds().getBoundingBox(),s=a.x,l=a.y,c=a.x+a.width,u=a.y+a.height,h=1;h=0||(r[i]=e[i]);return r}const is={arr:Array.isArray,obj:e=>"[object Object]"===Object.prototype.toString.call(e),fun:e=>"function"==typeof e,str:e=>"string"==typeof e,num:e=>"number"==typeof e,und:e=>void 0===e,nul:e=>null===e,set:e=>e instanceof Set,map:e=>e instanceof Map,equ(e,t){if(typeof e!=typeof t)return!1;if(is.str(e)||is.num(e))return e===t;if(is.obj(e)&&is.obj(t)&&Object.keys(e).length+Object.keys(t).length===0)return!0;let i;for(i in e)if(!(i in t))return!1;for(i in t)if(e[i]!==t[i])return!1;return!is.und(i)||e===t}};function merge(e,t){return void 0===t&&(t=!0),i=>(is.arr(i)?i:Object.keys(i)).reduce((i,n)=>{const r=t?n[0].toLowerCase()+n.substring(1):n;return i[r]=e(r),i},e)}function useForceUpdate(){const e=React.useState(!1)[1];return React.useCallback(()=>e(e=>!e),[])}function withDefault(e,t){return is.und(e)||is.nul(e)?t:e}function toArray(e){return is.und(e)?[]:is.arr(e)?e:[e]}function callProp(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;nis.und(t[n])?_extends$1({},i,{[n]:e[n]}):i,{});return _extends$1({to:t},i)}function handleRef(e,t){return t&&(is.fun(t)?t(e):is.obj(t)&&(t.current=e)),e}class Animated{constructor(){this.payload=void 0,this.children=[]}getAnimatedValue(){return this.getValue()}getPayload(){return this.payload||this}attach(){}detach(){}getChildren(){return this.children}addChild(e){0===this.children.length&&this.attach(),this.children.push(e)}removeChild(e){const t=this.children.indexOf(e);this.children.splice(t,1),0===this.children.length&&this.detach()}}class AnimatedArray extends Animated{constructor(){super(...arguments),this.payload=[],this.attach=()=>this.payload.forEach(e=>e instanceof Animated&&e.addChild(this)),this.detach=()=>this.payload.forEach(e=>e instanceof Animated&&e.removeChild(this))}}class AnimatedObject extends Animated{constructor(){super(...arguments),this.payload={},this.attach=()=>Object.values(this.payload).forEach(e=>e instanceof Animated&&e.addChild(this)),this.detach=()=>Object.values(this.payload).forEach(e=>e instanceof Animated&&e.removeChild(this))}getValue(e){void 0===e&&(e=!1);const t={};for(const i in this.payload){const n=this.payload[i];(!e||n instanceof Animated)&&(t[i]=n instanceof Animated?n[e?"getAnimatedValue":"getValue"]():n)}return t}getAnimatedValue(){return this.getValue(!0)}}let applyAnimatedValues,colorNames;function injectApplyAnimatedValues(e,t){applyAnimatedValues={fn:e,transform:t}}function injectColorNames(e){colorNames=e}let requestFrame=e=>"undefined"!=typeof window?window.requestAnimationFrame(e):-1,interpolation;function injectStringInterpolator(e){interpolation=e}let now=()=>Date.now(),animatedApi=e=>e.current,createAnimatedStyle,manualFrameloop;function injectCreateAnimatedStyle(e){createAnimatedStyle=e}class AnimatedProps extends AnimatedObject{constructor(e,t){super(),this.update=void 0,this.payload=e.style?_extends$1({},e,{style:createAnimatedStyle(e.style)}):e,this.update=t,this.attach()}}const isFunctionComponent=e=>is.fun(e)&&!(e.prototype instanceof React__default.Component),createAnimatedComponent=e=>{return React.forwardRef((t,i)=>{const n=useForceUpdate(),r=React.useRef(!0),o=React.useRef(null),a=React.useRef(null),s=React.useCallback(e=>{const t=o.current;o.current=new AnimatedProps(e,()=>{let e=!1;a.current&&(e=applyAnimatedValues.fn(a.current,o.current.getAnimatedValue())),a.current&&!1!==e||n()}),t&&t.detach()},[]);React.useEffect(()=>()=>{r.current=!1,o.current&&o.current.detach()},[]),React.useImperativeHandle(i,()=>animatedApi(a,r,n)),s(t);const l=o.current.getValue(),c=(l.scrollTop,l.scrollLeft,_objectWithoutPropertiesLoose(l,["scrollTop","scrollLeft"])),u=isFunctionComponent(e)?void 0:e=>a.current=handleRef(e,i);return React__default.createElement(e,_extends$1({},c,{ref:u}))})};let active=!1;const controllers=new Set,update=()=>{if(!active)return!1;let e=now();for(let t of controllers){let i=!1;for(let n=0;n=n.startTime+a.duration;else if(a.decay)c=s+h/(1-.998)*(1-Math.exp(-(1-.998)*(e-n.startTime))),r=Math.abs(n.lastPosition-c)<.1,r&&(l=c);else{o=void 0!==n.lastTime?n.lastTime:e,h=void 0!==n.lastVelocity?n.lastVelocity:a.initialVelocity,e>o+64&&(o=e);let t=Math.floor(e-o);for(let e=0;el:c{controllers.has(e)||controllers.add(e),active||(active=!0,requestFrame(manualFrameloop||update))},stop=e=>{controllers.has(e)&&controllers.delete(e)};function createInterpolator(e,t,i){if("function"==typeof e)return e;if(Array.isArray(e))return createInterpolator({range:e,output:t,extrapolate:i});if(interpolation&&"string"==typeof e.output[0])return interpolation(e);const n=e,r=n.output,o=n.range||[0,1],a=n.extrapolateLeft||n.extrapolate||"extend",s=n.extrapolateRight||n.extrapolate||"extend",l=n.easing||(e=>e);return e=>{const t=findRange(e,o);return interpolate(e,o[t],o[t+1],r[t],r[t+1],l,a,s,n.map)}}function interpolate(e,t,i,n,r,o,a,s,l){let c=l?l(e):e;if(ci){if("identity"===s)return c;"clamp"===s&&(c=i)}return n===r?n:t===i?e<=t?n:r:(t===-1/0?c=-c:i===1/0?c-=t:c=(c-t)/(i-t),c=o(c),n===-1/0?c=-c:r===1/0?c+=n:c=c*(r-n)+n,c)}function findRange(e,t){for(var i=1;i=e);++i);return i-1}class AnimatedInterpolation extends AnimatedArray{constructor(e,t,i,n){super(),this.calc=void 0,this.payload=e instanceof AnimatedArray&&!(e instanceof AnimatedInterpolation)?e.getPayload():Array.isArray(e)?e:[e],this.calc=createInterpolator(t,i,n)}getValue(){return this.calc(...this.payload.map(e=>e.getValue()))}updateConfig(e,t,i){this.calc=createInterpolator(e,t,i)}interpolate(e,t,i){return new AnimatedInterpolation(this,e,t,i)}}function addAnimatedStyles(e,t){"update"in e?t.add(e):e.getChildren().forEach(e=>addAnimatedStyles(e,t))}class AnimatedValue extends Animated{constructor(e){var t;super(),t=this,this.animatedStyles=new Set,this.value=void 0,this.startPosition=void 0,this.lastPosition=void 0,this.lastVelocity=void 0,this.startTime=void 0,this.lastTime=void 0,this.done=!1,this.setValue=function(e,i){void 0===i&&(i=!0),t.value=e,i&&t.flush()},this.value=e,this.startPosition=e,this.lastPosition=e}flush(){0===this.animatedStyles.size&&addAnimatedStyles(this,this.animatedStyles),this.animatedStyles.forEach(e=>e.update())}clearStyles(){this.animatedStyles.clear()}getValue(){return this.value}interpolate(e,t,i){return new AnimatedInterpolation(this,e,t,i)}}class AnimatedValueArray extends AnimatedArray{constructor(e){super(),this.payload=e.map(e=>new AnimatedValue(e))}setValue(e,t){void 0===t&&(t=!0),Array.isArray(e)?e.length===this.payload.length&&e.forEach((e,i)=>this.payload[i].setValue(e,t)):this.payload.forEach(i=>i.setValue(e,t))}getValue(){return this.payload.map(e=>e.getValue())}interpolate(e,t){return new AnimatedInterpolation(this,e,t)}}let G=0;class Controller{constructor(){this.id=void 0,this.idle=!0,this.hasChanged=!1,this.guid=0,this.local=0,this.props={},this.merged={},this.animations={},this.interpolations={},this.values={},this.configs=[],this.listeners=[],this.queue=[],this.localQueue=void 0,this.getValues=()=>this.interpolations,this.id=G++}update(e){if(!e)return this;const t=interpolateTo(e),i=t.delay,n=void 0===i?0:i,r=t.to,o=_objectWithoutPropertiesLoose(t,["delay","to"]);if(is.arr(r)||is.fun(r))this.queue.push(_extends$1({},o,{delay:n,to:r}));else if(r){let e={};Object.entries(r).forEach(t=>{let i=t[0];const r=_extends$1({to:{[i]:t[1]},delay:callProp(n,i)},o),a=e[r.delay]&&e[r.delay].to;e[r.delay]=_extends$1({},e[r.delay],r,{to:_extends$1({},a,r.to)})}),this.queue=Object.values(e)}return this.queue=this.queue.sort((e,t)=>e.delay-t.delay),this.diff(o),this}start(e){if(this.queue.length){this.idle=!1,this.localQueue&&this.localQueue.forEach(e=>{let t=e.from,i=void 0===t?{}:t,n=e.to,r=void 0===n?{}:n;is.obj(i)&&(this.merged=_extends$1({},i,this.merged)),is.obj(r)&&(this.merged=_extends$1({},this.merged,r))});const t=this.local=++this.guid,i=this.localQueue=this.queue;this.queue=[],i.forEach((n,r)=>{let o=n.delay,a=_objectWithoutPropertiesLoose(n,["delay"]);const s=n=>{r===i.length-1&&t===this.guid&&n&&(this.idle=!0,this.props.onRest&&this.props.onRest(this.merged)),e&&e()};let l=is.arr(a.to)||is.fun(a.to);o?setTimeout(()=>{t===this.guid&&(l?this.runAsync(a,s):this.diff(a).start(s))},o):l?this.runAsync(a,s):this.diff(a).start(s)})}else is.fun(e)&&this.listeners.push(e),this.props.onStart&&this.props.onStart(),start(this);return this}stop(e){return this.listeners.forEach(t=>t(e)),this.listeners=[],this}pause(e){return this.stop(!0),e&&stop(this),this}runAsync(e,t){var i=this;e.delay;let n=_objectWithoutPropertiesLoose(e,["delay"]);const r=this.local;let o=Promise.resolve(void 0);if(is.arr(n.to))for(let e=0;e{if(r===this.guid)return new Promise(e=>this.diff(i).start(e))})}else if(is.fun(n.to)){let e,t=0;o=o.then(()=>n.to(i=>{const o=_extends$1({},n,interpolateTo(i));if(is.arr(o.config)&&(o.config=o.config[t]),t++,r===this.guid)return e=new Promise(e=>this.diff(o).start(e))},(function(e){return void 0===e&&(e=!0),i.stop(e)})).then(()=>e))}o.then(t)}diff(e){this.props=_extends$1({},this.props,e);let t=this.props,i=t.from,n=void 0===i?{}:i,r=t.to,o=void 0===r?{}:r,a=t.config,s=void 0===a?{}:a,l=t.reverse,c=t.attach,u=t.reset,h=t.immediate;if(l){var d=[o,n];n=d[0],o=d[1]}this.merged=_extends$1({},n,this.merged,o),this.hasChanged=!1;let p=c&&c(this);if(this.animations=Object.entries(this.merged).reduce((e,t)=>{let i=t[0],r=t[1],o=e[i]||{};const a=is.num(r),l=is.str(r)&&!r.startsWith("#")&&!/\d/.test(r)&&!colorNames[r],c=is.arr(r),d=!a&&!c&&!l;let g=is.und(n[i])?r:n[i],m=a||c?r:l?r:1,f=callProp(s,i);p&&(m=p.animations[i].parent);let v,y=o.parent,w=o.interpolation,_=toArray(p?m.getPayload():m),T=r;d&&(T=interpolation({range:[0,1],output:[r,r]})(1));let S=w&&w.getValue();const x=!is.und(y)&&o.animatedValues.some(e=>!e.done),b=!is.equ(T,S),E=!is.equ(T,o.previous),P=!is.equ(f,o.config);if(u||E&&b||P){if(a||l)y=w=o.parent||new AnimatedValue(g);else if(c)y=w=o.parent||new AnimatedValueArray(g);else if(d){let e=o.interpolation&&o.interpolation.calc(o.parent.value);e=void 0===e||u?g:e,o.parent?(y=o.parent,y.setValue(0,!1)):y=new AnimatedValue(0);const t={output:[e,r]};o.interpolation?(w=o.interpolation,o.interpolation.updateConfig(t)):w=y.interpolate(t)}return _=toArray(p?m.getPayload():m),v=toArray(y.getPayload()),u&&!d&&y.setValue(g,!1),this.hasChanged=!0,v.forEach(e=>{e.startPosition=e.value,e.lastPosition=e.value,e.lastVelocity=x?e.lastVelocity:void 0,e.lastTime=x?e.lastTime:void 0,e.startTime=now(),e.done=!1,e.animatedStyles.clear()}),callProp(h,i)&&y.setValue(d?m:r,!1),_extends$1({},e,{[i]:_extends$1({},o,{name:i,parent:y,interpolation:w,animatedValues:v,toValues:_,previous:T,config:f,fromValues:toArray(y.getValue()),immediate:callProp(h,i),initialVelocity:withDefault(f.velocity,0),clamp:withDefault(f.clamp,!1),precision:withDefault(f.precision,.01),tension:withDefault(f.tension,170),friction:withDefault(f.friction,26),mass:withDefault(f.mass,1),duration:f.duration,easing:withDefault(f.easing,e=>e),decay:f.decay})})}return b?e:(d&&(y.setValue(1,!1),w.updateConfig({output:[T,T]})),y.done=!0,this.hasChanged=!0,_extends$1({},e,{[i]:_extends$1({},e[i],{previous:T})}))},this.animations),this.hasChanged){this.configs=Object.values(this.animations),this.values={},this.interpolations={};for(let e in this.animations)this.interpolations[e]=this.animations[e].interpolation,this.values[e]=this.animations[e].interpolation.getValue()}return this}destroy(){this.stop(),this.props={},this.merged={},this.animations={},this.interpolations={},this.values={},this.configs=[],this.local=0}}const useSprings=(e,t)=>{const i=React.useRef(!1),n=React.useRef(),r=is.fun(t),o=React.useMemo(()=>{let i;return(n.current&&(n.current.map(e=>e.destroy()),n.current=void 0),[new Array(e).fill().map((e,n)=>{const o=new Controller,a=r?callProp(t,n,o):t[n];return 0===n&&(i=a.ref),o.update(a),i||o.start(),o}),i])},[e]),a=o[0],s=o[1];n.current=a;React.useImperativeHandle(s,()=>({start:()=>Promise.all(n.current.map(e=>new Promise(t=>e.start(t)))),stop:e=>n.current.forEach(t=>t.stop(e)),get controllers(){return n.current}}));const l=React.useMemo(()=>e=>n.current.map((t,i)=>{t.update(r?callProp(e,i,t):e[i]),s||t.start()}),[e]);React.useEffect(()=>{i.current?r||l(t):s||n.current.forEach(e=>e.start())}),React.useEffect(()=>(i.current=!0,()=>n.current.forEach(e=>e.destroy())),[]);const c=n.current.map(e=>e.getValues());return r?[c,l,e=>n.current.forEach(t=>t.pause(e))]:c},useSpring=e=>{const t=is.fun(e),i=useSprings(1,t?e:[e]),n=i[0],r=i[1],o=i[2];return t?[n[0],r,o]:n};class AnimatedStyle extends AnimatedObject{constructor(e){void 0===e&&(e={}),super(),!e.transform||e.transform instanceof Animated||(e=applyAnimatedValues.transform(e)),this.payload=e}}const colors={transparent:0,aliceblue:4042850303,antiquewhite:4209760255,aqua:16777215,aquamarine:2147472639,azure:4043309055,beige:4126530815,bisque:4293182719,black:255,blanchedalmond:4293643775,blue:65535,blueviolet:2318131967,brown:2771004159,burlywood:3736635391,burntsienna:3934150143,cadetblue:1604231423,chartreuse:2147418367,chocolate:3530104575,coral:4286533887,cornflowerblue:1687547391,cornsilk:4294499583,crimson:3692313855,cyan:16777215,darkblue:35839,darkcyan:9145343,darkgoldenrod:3095792639,darkgray:2846468607,darkgreen:6553855,darkgrey:2846468607,darkkhaki:3182914559,darkmagenta:2332068863,darkolivegreen:1433087999,darkorange:4287365375,darkorchid:2570243327,darkred:2332033279,darksalmon:3918953215,darkseagreen:2411499519,darkslateblue:1211993087,darkslategray:793726975,darkslategrey:793726975,darkturquoise:13554175,darkviolet:2483082239,deeppink:4279538687,deepskyblue:12582911,dimgray:1768516095,dimgrey:1768516095,dodgerblue:512819199,firebrick:2988581631,floralwhite:4294635775,forestgreen:579543807,fuchsia:4278255615,gainsboro:3705462015,ghostwhite:4177068031,gold:4292280575,goldenrod:3668254975,gray:2155905279,green:8388863,greenyellow:2919182335,grey:2155905279,honeydew:4043305215,hotpink:4285117695,indianred:3445382399,indigo:1258324735,ivory:4294963455,khaki:4041641215,lavender:3873897215,lavenderblush:4293981695,lawngreen:2096890111,lemonchiffon:4294626815,lightblue:2916673279,lightcoral:4034953471,lightcyan:3774873599,lightgoldenrodyellow:4210742015,lightgray:3553874943,lightgreen:2431553791,lightgrey:3553874943,lightpink:4290167295,lightsalmon:4288707327,lightseagreen:548580095,lightskyblue:2278488831,lightslategray:2005441023,lightslategrey:2005441023,lightsteelblue:2965692159,lightyellow:4294959359,lime:16711935,limegreen:852308735,linen:4210091775,magenta:4278255615,maroon:2147483903,mediumaquamarine:1724754687,mediumblue:52735,mediumorchid:3126187007,mediumpurple:2473647103,mediumseagreen:1018393087,mediumslateblue:2070474495,mediumspringgreen:16423679,mediumturquoise:1221709055,mediumvioletred:3340076543,midnightblue:421097727,mintcream:4127193855,mistyrose:4293190143,moccasin:4293178879,navajowhite:4292783615,navy:33023,oldlace:4260751103,olive:2155872511,olivedrab:1804477439,orange:4289003775,orangered:4282712319,orchid:3664828159,palegoldenrod:4008225535,palegreen:2566625535,paleturquoise:2951671551,palevioletred:3681588223,papayawhip:4293907967,peachpuff:4292524543,peru:3448061951,pink:4290825215,plum:3718307327,powderblue:2967529215,purple:2147516671,rebeccapurple:1714657791,red:4278190335,rosybrown:3163525119,royalblue:1097458175,saddlebrown:2336560127,salmon:4202722047,sandybrown:4104413439,seagreen:780883967,seashell:4294307583,sienna:2689740287,silver:3233857791,skyblue:2278484991,slateblue:1784335871,slategray:1887473919,slategrey:1887473919,snow:4294638335,springgreen:16744447,steelblue:1182971135,tan:3535047935,teal:8421631,thistle:3636451583,tomato:4284696575,turquoise:1088475391,violet:4001558271,wheat:4125012991,white:4294967295,whitesmoke:4126537215,yellow:4294902015,yellowgreen:2597139199},NUMBER="[-+]?\\d*\\.?\\d+",PERCENTAGE=NUMBER+"%";function call(){for(var e=arguments.length,t=new Array(e),i=0;i>>0===e&&e>=0&&e<=4294967295?e:null:(t=hex6.exec(e))?parseInt(t[1]+"ff",16)>>>0:colors.hasOwnProperty(e)?colors[e]:(t=rgb.exec(e))?(parse255(t[1])<<24|parse255(t[2])<<16|parse255(t[3])<<8|255)>>>0:(t=rgba.exec(e))?(parse255(t[1])<<24|parse255(t[2])<<16|parse255(t[3])<<8|parse1(t[4]))>>>0:(t=hex3.exec(e))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+"ff",16)>>>0:(t=hex8.exec(e))?parseInt(t[1],16)>>>0:(t=hex4.exec(e))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+t[4]+t[4],16)>>>0:(t=hsl.exec(e))?(255|hslToRgb(parse360(t[1]),parsePercentage(t[2]),parsePercentage(t[3])))>>>0:(t=hsla.exec(e))?(hslToRgb(parse360(t[1]),parsePercentage(t[2]),parsePercentage(t[3]))|parse1(t[4]))>>>0:null}function hue2rgb(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}function hslToRgb(e,t,i){const n=i<.5?i*(1+t):i+t-i*t,r=2*i-n,o=hue2rgb(r,n,e+1/3),a=hue2rgb(r,n,e),s=hue2rgb(r,n,e-1/3);return Math.round(255*o)<<24|Math.round(255*a)<<16|Math.round(255*s)<<8}function parse255(e){const t=parseInt(e,10);return t<0?0:t>255?255:t}function parse360(e){return(parseFloat(e)%360+360)%360/360}function parse1(e){const t=parseFloat(e);return t<0?0:t>1?255:Math.round(255*t)}function parsePercentage(e){const t=parseFloat(e);return t<0?0:t>100?1:t/100}function colorToRgba(e){let t=normalizeColor(e);return null===t?e:(t=t||0,`rgba(${(4278190080&t)>>>24}, ${(16711680&t)>>>16}, ${(65280&t)>>>8}, ${(255&t)/255})`)}const stringShapeRegex=/[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,colorRegex=/(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi,colorNamesRegex=new RegExp(`(${Object.keys(colors).join("|")})`,"g"),createStringInterpolator=e=>{const t=e.output.map(e=>e.replace(colorRegex,colorToRgba)).map(e=>e.replace(colorNamesRegex,colorToRgba)),i=t[0].match(stringShapeRegex).map(()=>[]);t.forEach(e=>{e.match(stringShapeRegex).forEach((e,t)=>i[t].push(+e))});const n=t[0].match(stringShapeRegex).map((t,n)=>createInterpolator(_extends$1({},e,{output:i[n]})));return e=>{let i=0;return t[0].replace(stringShapeRegex,()=>n[i++](e)).replace(/rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi,(e,t,i,n,r)=>`rgba(${Math.round(t)}, ${Math.round(i)}, ${Math.round(n)}, ${r})`)}};let isUnitlessNumber={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0};const prefixKey=(e,t)=>e+t.charAt(0).toUpperCase()+t.substring(1),prefixes$1=["Webkit","Ms","Moz","O"];function dangerousStyleValue(e,t,i){return null==t||"boolean"==typeof t||""===t?"":i||"number"!=typeof t||0===t||isUnitlessNumber.hasOwnProperty(e)&&isUnitlessNumber[e]?(""+t).trim():t+"px"}isUnitlessNumber=Object.keys(isUnitlessNumber).reduce((e,t)=>(prefixes$1.forEach(i=>e[prefixKey(i,t)]=e[t]),e),isUnitlessNumber);const attributeCache={};injectCreateAnimatedStyle(e=>new AnimatedStyle(e)),injectStringInterpolator(createStringInterpolator),injectColorNames(colors),injectApplyAnimatedValues((e,t)=>{if(!e.nodeType||void 0===e.setAttribute)return!1;{const r=t.style,o=t.children,a=t.scrollTop,s=t.scrollLeft,l=_objectWithoutPropertiesLoose(t,["style","children","scrollTop","scrollLeft"]),c="filter"===e.nodeName||e.parentNode&&"filter"===e.parentNode.nodeName;void 0!==a&&(e.scrollTop=a),void 0!==s&&(e.scrollLeft=s),void 0!==o&&(e.textContent=o);for(let t in r)if(r.hasOwnProperty(t)){var i=0===t.indexOf("--"),n=dangerousStyleValue(t,r[t],i);"float"===t&&(t="cssFloat"),i?e.style.setProperty(t,n):e.style[t]=n}for(let t in l){const i=c?t:attributeCache[t]||(attributeCache[t]=t.replace(/([A-Z])/g,e=>"-"+e.toLowerCase()));void 0!==e.getAttribute(i)&&e.setAttribute(i,l[t])}}},e=>e);const domElements=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"],apply=merge(createAnimatedComponent,!1),extendedAnimated=apply(domElements),Tooltip=React__default.forwardRef(({title:e,children:t,placement:i="top",...n},r)=>{const o=reakit.useTooltipState({placement:i,unstable_animated:!0}),a=()=>{o.unstable_stopAnimation()},[{opacity:s},l,c]=useSpring(()=>({delay:0,opacity:0,onRest:a,config:{clamp:!0,velocity:14,friction:20}}));return React.useEffect(()=>{o.place(i)},[i]),React.useEffect(()=>{l({delay:o.visible?400:0,opacity:o.visible?1:0})},[o.visible]),React__default.createElement(React__default.Fragment,null,React__default.createElement(reakit.TooltipReference,_extends({},o,n,{ref:r}),e=>React__default.cloneElement(React__default.Children.only(t),e)),React__default.createElement(reakit.Tooltip,_extends({},o,{style:{opacity:s},unstable_portal:!1,className:"villain-tooltip",as:extendedAnimated.div}),React__default.createElement(LocalizedConsumer,{value:e})))});var Tooltip$1=React__default.memo(Tooltip);const ToolbarButton=React__default.forwardRef(({icon:e,iconSize:t,label:i,title:n,active:r,tooltip:o,onClick:a,children:s,typeClass:l,tooltipPlacement:c,...u},h)=>{const d={ref:h,...u},p=o?{}:d;let g=React__default.createElement(reakit.Button,_extends({focusable:!0,title:n,onClick:a,"aria-label":o,className:clsx("villain-button",l&&`villain-button--${l}`,r&&"villain-button--active")},p),e&&React__default.createElement(Icon$1,{path:e,size:t||"24px",className:"villain-icon"}),i&&React__default.createElement("span",{className:"villain-button__label"},i),s);return o&&(g=React__default.createElement(Tooltip$1,_extends({},d,{title:o,placement:c}),g)),g});var Button=React__default.memo(ToolbarButton);function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArrayLimit(e,t){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)){var i=[],n=!0,r=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(i.push(a.value),!t||i.length!==t);n=!0);}catch(e){r=!0,o=e}finally{try{n||null==s.return||s.return()}finally{if(r)throw o}}return i}}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var i=0;i2?n-2:0);for(var r=2;r0&&void 0!==arguments[0]?arguments[0]:{},t=i.props,n=t.emitMouse,r=t.emitTouch;return _objectSpread({},e,{onMouseDown:callAll(e.onMouseDown,n),onTouchStart:callAll(e.onTouchStart,r)})})),i}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){var e=this.getRailProps,t=this.props,i=t.getEventData,n=t.activeHandleID,r=(0,t.children)({getEventData:i,activeHandleID:n,getRailProps:e});return r&&React__default.Children.only(r)}}]),t}(React.Component);Rail.propTypes={getEventData:propTypes.func,activeHandleID:propTypes.string,emitMouse:propTypes.func,emitTouch:propTypes.func,children:propTypes.func.isRequired};var Ticks=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,_getPrototypeOf(t).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){var e=this.props,t=e.children,i=e.values,n=e.scale,r=e.count,o=t({getEventData:e.getEventData,activeHandleID:e.activeHandleID,ticks:(i||n.getTicks(r)).map((function(e){return{id:"$$-".concat(e),value:e,percent:n.getValue(e)}}))});return o&&React__default.Children.only(o)}}]),t}(React.Component);function ownKeys$1(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function _objectSpread$1(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=i.props,n=t.emitMouse,r=t.emitTouch;return _objectSpread$1({},e,{onMouseDown:callAll(e.onMouseDown,n),onTouchStart:callAll(e.onTouchStart,r)})})),i}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){for(var e=this.getTrackProps,t=this.props,i=t.children,n=t.left,r=t.right,o=t.scale,a=t.handles,s=t.getEventData,l=t.activeHandleID,c=o.getDomain(),u=[],h=0;h1&&void 0!==arguments[1]?arguments[1]:{},n=i.props,r=n.emitKeyboard,o=n.emitMouse,a=n.emitTouch;return _objectSpread$2({},t,{onKeyDown:callAll(t.onKeyDown,(function(t){return r(t,e)})),onMouseDown:callAll(t.onMouseDown,i.autofocus,(function(t){return o(t,e)})),onTouchStart:callAll(t.onTouchStart,(function(t){return a(t,e)}))})})),i}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){var e=this.getHandleProps,t=this.props,i=t.activeHandleID,n=(0,t.children)({handles:t.handles,activeHandleID:i,getHandleProps:e});return n&&React__default.Children.only(n)}}]),t}(React.Component);function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,i=new Array(e.length);ti.val?e?-1:1:i.val>t.val?e?1:-1:0}}function getUpdatedHandles(e,t,i,n){var r=e.findIndex((function(e){return e.key===t}));if(-1!==r){var o=e[r],a=o.key;return o.val===i?e:[].concat(_toConsumableArray(e.slice(0,r)),[{key:a,val:i}],_toConsumableArray(e.slice(r+1))).sort(getSortByVal(n))}return e}function getSliderDomain(e,t){if(!e)return[0,0];var i=e.getBoundingClientRect();return[t?i.top:i.left,t?i.bottom:i.right]}function isNotValidTouch(e){var t=e.type,i=void 0===t?"":t,n=e.touches;return!n||n.length>1||"touchend"===i.toLowerCase()&&n.length>0}function getTouchPosition(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function getHandles(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,r=0;return{handles:e.map((function(e){var t=i.getValue(e);return e!==t&&(r+=1,warning_1(!n,"".concat(prfx," Invalid value encountered. Changing ").concat(e," to ").concat(t,"."))),t})).map((function(e,t){return{key:"$$-".concat(t),val:e}})).sort(getSortByVal(t)),changes:r}}function mode1(e,t){return t}function mode2(e,t){for(var i=0;i0)}if(-1===o)return e;for(var u=a?i:-i,h=0;ht?1:e>=t?0:NaN}function bisector(e){return 1===e.length&&(e=ascendingComparator(e)),{left:function(t,i,n,r){for(null==n&&(n=0),null==r&&(r=t.length);n>>1;e(t[o],i)<0?n=o+1:r=o}return n},right:function(t,i,n,r){for(null==n&&(n=0),null==r&&(r=t.length);n>>1;e(t[o],i)>0?r=o:n=o+1}return n}}}function ascendingComparator(e){return function(t,i){return ascending(e(t),i)}}var ascendingBisect=bisector(ascending),e10=Math.sqrt(50),e5=Math.sqrt(10),e2=Math.sqrt(2);function ticks(e,t,i){var n,r,o,a,s=-1;if(i=+i,(e=+e)===(t=+t)&&i>0)return[e];if((n=t0)for(e=Math.ceil(e/a),t=Math.floor(t/a),o=new Array(r=Math.ceil(t-e+1));++s=0?(o>=e10?10:o>=e5?5:o>=e2?2:1)*Math.pow(10,r):-Math.pow(10,-r)/(o>=e10?10:o>=e5?5:o>=e2?2:1)}var LinearScale=function(){function e(){_classCallCheck(this,e),this.domain=[0,1],this.range=[0,1],this.interpolator=null}return _createClass(e,[{key:"createInterpolator",value:function(e,t){var i=e[0],n=e[1],r=t[0],o=t[1];return na?s:a)})),this.step=1,this.domain=[0,1],this.range=[0,1]},isBrowser="undefined"!=typeof window&&"undefined"!=typeof document,noop=function(){},compare=function(e){return function(t,i,n){return t&&e[n]===i}},equal=function(e,t){return e===t||e.length===t.length&&e.reduce(compare(t),!0)},getNextValue=function(e,t,i,n){var r=n?e-t:e+t;return n?Math.max(i[0],r):Math.min(i[1],r)},getPrevValue=function(e,t,i,n){var r=n?e+t:e-t;return n?Math.min(i[1],r):Math.max(i[0],r)},Slider=function(e){function t(){var e,i;_classCallCheck(this,t);for(var n=arguments.length,r=new Array(n),o=0;og,"".concat(prfx," Max must be greater than min (even if reversed). Max is ").concat(m,". Min is ").concat(g,"."));var f=getHandles(n||t.values,o,u,l),v=f.handles;(f.changes||void 0===n||n===t.values)&&(a(v.map((function(e){return e.val}))),s(v.map((function(e){return e.val})))),d.step=i,d.values=n,d.domain=r,d.handles=v,d.reversed=o}else if(!equal(n,t.values)){var y=getHandles(n,o,u,l),w=y.handles;y.changes&&(a(w.map((function(e){return e.val}))),s(w.map((function(e){return e.val})))),d.values=n,d.handles=w}return Object.keys(d).length?d:null}}]),t}(React.PureComponent);Slider.propTypes={component:propTypes.string,rootStyle:propTypes.object,rootProps:propTypes.object,className:propTypes.string,domain:propTypes.array,values:propTypes.array,step:propTypes.number,mode:propTypes.oneOfType([propTypes.number,propTypes.func]),vertical:propTypes.bool,reversed:propTypes.bool,onChange:propTypes.func,onUpdate:propTypes.func,onSlideStart:propTypes.func,onSlideEnd:propTypes.func,disabled:propTypes.bool,flatten:propTypes.bool,warnOnChanges:propTypes.bool,children:propTypes.any},Slider.defaultProps={mode:1,step:.1,domain:[0,100],component:"div",rootProps:{},rootStyle:{},vertical:!1,reversed:!1,onChange:noop,onUpdate:noop,onSlideStart:noop,onSlideEnd:noop,disabled:!1,flatten:!1,warnOnChanges:!1},Slider.Rail=Rail,Slider.Ticks=Ticks,Slider.Tracks=Tracks,Slider.Handles=Handles;const HandlerTooltip=React.memo(({value:e,visible:t})=>{const[i,n]=React.useState(!1),[r,o,a]=useSpring(()=>({delay:0,opacity:1,transform:"scale(1)",config:{clamp:!0,velocity:14,friction:20}}));return React.useEffect(()=>{o({delay:t?200:800,opacity:t?1:0,onRest:()=>{t||n(!1)},onStart:()=>{t&&n(!0)},transform:`scale(${t?1:0})`})},[t]),i&&React__default.createElement(extendedAnimated.div,{className:"villain-tooltip--slider",style:r},e)});HandlerTooltip.propTypes={value:propTypes.number};const Handle=({domain:[e,t],handle:{id:i,value:n,percent:r},isActive:o,disabled:a,getHandleProps:s})=>{const[l,c]=React.useState(!1),u=(l||o)&&!a;return React__default.createElement(Button,_extends({role:"slider","aria-valuemin":e,"aria-valuemax":t,"aria-valuenow":n,style:{height:14,width:14,left:`${r}%`,display:"block",position:"absolute",transform:"translate(-50%, -50%)",WebkitTapHighlightColor:"rgba(0,0,0,0)",border:0,borderRadius:"50%",backgroundColor:a?"transparent":"var(--slider-track-bg)",zIndex:1,margin:0,padding:0,outline:"none"}},s(i,{onMouseEnter:()=>{c(!0)},onMouseLeave:()=>{c(!1)}})),React__default.createElement(HandlerTooltip,{value:n,visible:u}))};Handle.propTypes={domain:propTypes.array.isRequired,handle:propTypes.shape({id:propTypes.string.isRequired,value:propTypes.number.isRequired,percent:propTypes.number.isRequired}).isRequired,getHandleProps:propTypes.func.isRequired,isActive:propTypes.bool.isRequired,disabled:propTypes.bool};var Handle$1=React.memo(Handle);const railStyle={position:"absolute",margin:0,width:"100%",height:"100%",cursor:"pointer",borderRadius:"4px",backgroundColor:"var(--slider-bg)",zIndex:-1},SliderRail=React.memo(({activeHandleID:e,getEventData:t,getRailProps:i})=>React__default.createElement("div",_extends({style:railStyle},i())));SliderRail.propTypes={activeHandleID:propTypes.string,getEventData:propTypes.func.isRequired,getRailProps:propTypes.func.isRequired};const sliderStyle={position:"absolute",width:"100%",height:4,display:"flex",alignItems:"center",borderRadius:"4px",justifyContent:"center",zIndex:99},Track=React.memo(({source:e,target:t,getTrackProps:i})=>React__default.createElement("div",_extends({className:"villain-slider__track",style:{zIndex:0,left:`${e.percent}%`,width:`${t.percent-e.percent}%`}},i()))),BufferLoader=React.memo(({bufferProgress:e,reversed:t})=>React__default.createElement("div",{className:"villain-slider__buffer",style:{width:`${e}%`,right:t?0:"initial"}})),defaultValues=[1],SliderUI=React.memo(({max:e=1,bufferProgress:t=0,reversed:i,onChange:n,value:r})=>{const[o,a]=React.useState(!1),[s,l]=React.useState(defaultValues.slice()),c=[1,e];if(1==e)return null;return React.useEffect(()=>{o||l([r+1])},[r]),React__default.createElement("div",{className:"villain-slider",style:{height:sliderStyle.height}},React__default.createElement(Slider,{rootStyle:sliderStyle,domain:c,step:1,mode:2,values:s,onUpdate:()=>a(!0),onChange:e=>{a(!1),n(e[0]-1)},reversed:i},React__default.createElement(Rail,null,({activeHandleID:e,getEventData:t,getRailProps:i})=>React__default.createElement(SliderRail,{activeHandleID:e,getEventData:t,getRailProps:i})),React__default.createElement(Handles,null,({handles:e,activeHandleID:t,getHandleProps:i})=>React__default.createElement("div",{className:"villain-slider__handles"},e.map(e=>React__default.createElement(Handle$1,{key:e.id,handle:e,domain:c,isActive:e.id===t,getHandleProps:i})))),React__default.createElement(Tracks,{right:i,left:!i},({tracks:e,getTrackProps:t})=>React__default.createElement("div",{className:"villain-slider__tracks"},e.map(({id:e,source:i,target:n})=>React__default.createElement(Track,{key:e,source:i,target:n,getTrackProps:t}))))),React__default.createElement(BufferLoader,{bufferProgress:t,reversed:i}))}),CustomSeparator=React__default.forwardRef((e,t)=>React__default.createElement(reakit.MenuSeparator,_extends({},e,{ref:t,className:"villain-menu__separator"}))),CustomItem=React__default.forwardRef(({children:e,...t},i)=>React__default.createElement(reakit.MenuItem,_extends({as:Button,className:"villain-menu__item"},t,{ref:i}),React__default.createElement("div",{className:"villain-menu__item__content"},React__default.createElement("div",{className:"villain-menu__item__label"},e)))),CustomCheckbox=React__default.forwardRef(({children:e,...t},i)=>React__default.createElement(reakit.MenuItemCheckbox,_extends({as:Button},t,{ref:i}),React__default.createElement("div",{className:"villain-menu__item__content"},React__default.createElement("div",{className:"villain-menu__item__label"},e),React__default.createElement("div",{className:"villain-menu__item__toggler"})))),CustomRadio=React__default.forwardRef(({children:e,...t},i)=>React__default.createElement(reakit.MenuItemRadio,_extends({as:Button,icon:t.checked?mdiRadioboxMarked:mdiRadioboxBlank,iconSize:"20px"},t,{ref:i}),React__default.createElement("div",{className:"villain-menu__item__content"},React__default.createElement("div",{className:"villain-menu__item__label"},e)))),CustomSubmenu=React__default.forwardRef(({children:e,...t},i)=>React__default.createElement(reakit.MenuItem,_extends({},t,{ref:i,as:Button}),React__default.createElement("div",{className:"villain-menu__item__content"},React__default.createElement("div",{className:"villain-menu__item__label"},e),React__default.createElement(Icon$1,{path:mdiChevronRight,size:"24px",className:"villain-icon villain-menu__item__icon"})))),MenuHeader=React__default.forwardRef(({title:e,closeSubmenu:t,menuProps:i,...n},r)=>React__default.createElement("div",_extends({},n,{className:"villain-menu__header"}),React__default.createElement(CustomItem,_extends({},i,{icon:mdiChevronLeft,onClick:t,ref:r}),React__default.createElement(LocalizedConsumer,{value:e})),React__default.createElement(CustomSeparator,_extends({},i,{style:{margin:0}})))),CustomItems={item:React__default.memo(CustomItem),radio:React__default.memo(CustomRadio),submenu:React__default.memo(CustomSubmenu),checkbox:React__default.memo(CustomCheckbox),separator:React__default.memo(CustomSeparator)},Item=React__default.memo(React__default.forwardRef(({id:e,itemType:t,content:i,children:n,openSubmenu:r,onClick:o,...a},s)=>{const l=CustomItems[t]||CustomItems.item,c=clsx("separator"!==t&&"villain-menu__item",t&&`villain-menu__${t}`);return React__default.createElement(l,_extends({onClick:i=>{o&&o(i),"submenu"===t&&r&&r(e)},className:c},a,{ref:s}),i?React__default.createElement(LocalizedConsumer,{value:i}):n)})),ItemList=React__default.memo(({title:e,items:t,getProps:i,menuProps:n,getContent:r,closeSubmenu:o})=>React__default.createElement(reakit.MenuGroup,n,t.map((t,a)=>React__default.createElement(Item,_extends({},n,i({item:t,title:e,closeSubmenu:o}),{key:t}),r&&r(t))))),MenuPanel=React__default.forwardRef(({title:e,items:t,list:i,openSubmenu:n,closeSubmenu:r,menuProps:o},a)=>React__default.createElement("div",{className:"villain-menu__panel",ref:a},e&&React__default.createElement(MenuHeader,{menuProps:o,closeSubmenu:r,title:e}),i?React__default.createElement(ItemList,_extends({},i,{title:e,menuProps:o,closeSubmenu:r})):t&&t.map(({nestedTitle:t,nestedItems:i,nestedList:r,...a})=>React__default.createElement(Item,_extends({},o,a,{key:a.id,title:e,openSubmenu:n}))))),PureMenuPanel=React__default.memo(MenuPanel),defaultSubmenuState={id:null,list:null,title:null,items:null,visible:!1},BaseMenu=React__default.forwardRef(({disclosure:e,tooltip:t,items:i,placement:n,ariaLabel:r,forceClose:o,...a},s)=>{const l=reakit.useMenuState({placement:n,gutter:20,unstable_animated:!0}),c=React__default.useRef(null),u=React__default.useRef(null),[h,d]=React__default.useState(0),[p,g]=React__default.useState(defaultSubmenuState),[m,f]=React__default.useState(!1),v=()=>{g({...defaultSubmenuState})},y=e=>{g({...p,id:e})},w=()=>{v()},_=()=>{f(!0)},T=()=>{f(!1),l.unstable_stopAnimation()},[S,x,b]=useSpring(()=>({height:`${h}px`,opacity:0,onRest:T,onStart:_,config:{clamp:!0,velocity:5,friction:20}}));return React__default.useEffect(()=>{x({height:`${h}px`})},[h]),React__default.useEffect(()=>{l.visible&&null!==u.current&&setTimeout(()=>{const e=u.current.clientHeight;d(e>240?240:e),l.unstable_update()},100),x({opacity:l.visible?1:0})},[l.visible]),React__default.useEffect(()=>{o&&l.hide()},[o]),React__default.useEffect(()=>{m||l.visible||v()},[m]),React__default.useEffect(()=>{if(p.id){const e=i&&i.length>0&&i.find(e=>e.id===p.id);if(e){const t=e.nestedList&&e.nestedList.items&&e.nestedList.items.length>0,i=e.nestedItems&&e.nestedItems.length>0;(t||i)&&g({...p,visible:!0,list:t?e.nestedList:null,items:i?e.nestedItems:null,title:e.nestedTitle})}}},[p.id]),React__default.useEffect(()=>{if(p.visible&&c.current){const e=c.current.clientHeight,t=e>240?240:e;h!==t&&d(t)}if(!p.visible&&u.current){const e=u.current.clientHeight,t=e>240?240:e;h!==t&&d(t)}l.unstable_update()},[p.visible]),React__default.createElement(React__default.Fragment,null,React__default.createElement(reakit.MenuDisclosure,_extends({},a,l,{as:e,ref:s})),React__default.createElement(reakit.Menu,_extends({},l,{style:{height:h},className:"villain-menu","aria-label":r}),React__default.createElement(extendedAnimated.div,{style:S,"data-animation":m,className:"villain-menu__animated-content"},p.visible?React__default.createElement(PureMenuPanel,{menuProps:l,list:p.list,title:p.title,items:p.items,openSubmenu:y,closeSubmenu:w,ref:c}):React__default.createElement(PureMenuPanel,{menuProps:l,items:i,openSubmenu:y,closeSubmenu:w,ref:u}))))});var Menu=React__default.memo(BaseMenu);const Languages$8={EN:"English",ES:"Español",DE:"Deutsch",FR:"Français",PT:"Português",ID:"Bahasa Indonesia",RU:"Русский",ZH:"話僮"};function getLanguageName(e){return Languages$8[e]||e}const SettingsButton=React__default.memo(React__default.forwardRef((e,t)=>React__default.createElement(Button,_extends({},e,{ref:t,icon:mdiSettings,typeClass:"icon",tooltip:"Settings"})))),SettingsMenu=React__default.forwardRef(({theme:e,mangaMode:t,forceClose:i,updateContextState:n},r)=>{const o=[{id:"toggler-manga-mode",icon:mdiPagePrevious,content:"Manga mode",checked:!0===t,itemType:"checkbox",onChange:()=>{n(e=>({mangaMode:!e.mangaMode}))}},{id:"toggler-dark-theme",icon:mdiBrightness4,content:"Dark theme",checked:"Dark"===e,itemType:"checkbox",onChange:()=>{n(e=>({theme:"Dark"===e.theme?"Light":"Dark"}))}},{id:"first-separator",itemType:"separator"},{id:"submenu-select-langauge",icon:mdiTranslate,content:"Language",itemType:"submenu",nestedTitle:"Languages",nestedList:{items:localize.getAvailableLanguages(),getProps:({item:e,closeSubmenu:t,title:i})=>({id:`language-${e}`,name:i,value:e,itemType:"radio",checked:localize.getLanguage()===e,onClick:t,onChange:()=>(e=>{n({language:e})})(e)}),getContent:e=>getLanguageName(e)}}];return React__default.createElement(Menu,{ref:r,items:o,placement:"top",disclosure:SettingsButton,forceClose:i,ariaLabel:localize.Settings})}),PureSettingsMenu=React__default.memo(SettingsMenu),SettingsMenuConsumer=React__default.forwardRef((e,t)=>React__default.createElement(ReaderContext.Consumer,null,({theme:i,mangaMode:n,updateState:r})=>React__default.createElement(PureSettingsMenu,_extends({},e,{ref:t,theme:i,mangaMode:n,updateContextState:r}))));var Settings$8=React__default.memo(SettingsMenuConsumer);const ZoomInButton=React.memo(({zoomIn:e,disabled:t})=>React__default.createElement(ReaderContext.Consumer,null,({canZoomIn:i})=>React__default.createElement(Button,{typeClass:"icon",tooltip:"Zoom in",icon:mdiPlus,disabled:!i||t,onClick:e,focusable:!0}))),ZoomOutButton=React.memo(({zoomOut:e,disabled:t})=>React__default.createElement(ReaderContext.Consumer,null,({canZoomOut:i})=>React__default.createElement(Button,{typeClass:"icon",tooltip:"Zoom out",icon:mdiMinus,disabled:!i||t,onClick:e,focusable:!0}))),ZoomInput=React.memo(({onUpdate:e,currentZoom:t,disabled:i})=>{const[n,r]=React.useState(""),[o,a]=React.useState(!1),[s,l]=useFocus();React.useEffect(()=>{c()},[t]);const c=()=>{t&&r(t)},u=()=>{s.current.valueAsNumber?e(s.current.valueAsNumber):c()};return React__default.createElement("div",{className:"villain-wrapper-input","data-focus":o,onClick:()=>{l()}},React__default.createElement("input",{step:1,size:3,pattern:"d+",ref:s,type:"number",role:"textbox",contentEditable:"true",title:"Zoom","aria-label":"Zoom to percentage value",onBlur:()=>{u(),a(!1)},onFocus:()=>{a(!0),s.current.select()},onChange:e=>{r(e.target.value)},onKeyPress:e=>{"Enter"===e.key&&u()},className:"villain-input",disabled:i,value:n}),React__default.createElement("div",{className:"villain-label villain-label--center"},"%"))}),ZoomControls=React.memo(({zoomIn:e,zoomOut:t,onUpdate:i,disabled:n})=>React__default.createElement("div",{className:"villain-toolbar__group"},React__default.createElement(ZoomInButton,{zoomIn:e,disabled:n}),React__default.createElement(ZoomOutButton,{zoomOut:t,disabled:n}),React__default.createElement(ReaderContext.Consumer,null,({currentZoom:e})=>React__default.createElement(ZoomInput,{currentZoom:e,onUpdate:i,disabled:n})))),LayoutButton=React__default.memo(({disabled:e,bookMode:t,toggleSetting:i,allowFullScreen:n})=>React__default.createElement(Button,{typeClass:"icon",icon:t?mdiBookOpen:mdiBookOpenOutline,onClick:()=>i("bookMode"),disabled:e,tooltip:t?"Page view":"Book view",tooltipPlacement:n?"top":"top-end",focusable:!0})),LayoutConsumer=React__default.memo(({disabled:e})=>React__default.createElement(ReaderContext.Consumer,null,({bookMode:t,allowFullScreen:i,toggleSetting:n})=>React__default.createElement(LayoutButton,{disabled:e,toggleSetting:n,allowFullScreen:i,bookMode:t}))),FullscreenButton=React__default.memo(({fullscreen:e,container:t,disabled:i})=>{return React__default.createElement(Button,{typeClass:"icon",icon:e?mdiFullscreenExit:mdiFullscreen,onClick:()=>{toggleFullscreen(t)},disabled:i,tooltip:e?"Exit fullscreen":"Enter fullscreen",tooltipPlacement:"top-end",focusable:!0})}),FullscreenConsumer=React__default.memo(({container:e,disabled:t})=>React__default.createElement(ReaderContext.Consumer,null,({fullscreen:i,allowFullScreen:n})=>n&&React__default.createElement(FullscreenButton,{disabled:t,container:e,fullscreen:i,allowFullScreen:n}))),NavigationButton=React.memo(({icon:e,action:t,disabled:i,tooltip:n})=>React__default.createElement(Button,{typeClass:"icon",icon:e,onClick:t,disabled:i,tooltip:n,tooltipPlacement:"top-start",focusable:!0})),NavigationInput=React.memo(({totalPages:e,currentPage:t,navigateToPage:i})=>{const[n,r]=React.useState({value:t||1}),[o,a]=React.useState(!1),[s,l]=useFocus();React.useEffect(()=>{c()},[t]);const c=()=>{r({value:t+1})},u=()=>{const{value:t}=n;if(t){const n=parseInt(t,10);n<=e&&n>0?i(n-1):c()}else c()};return React__default.createElement("div",{className:"villain-wrapper-input","data-focus":o,onClick:e=>{l()}},React__default.createElement("input",{min:1,step:1,size:3,ref:s,max:e,type:"number","aria-label":"Go to page number",role:"textbox",contentEditable:"true",title:"Page",pattern:"d+",className:"villain-input",onBlur:()=>{u(),a(!1)},onFocus:()=>{a(!0)},onChange:e=>{const{value:i}=e.target,n=i.replace(/\..*|^0+/gm,"");n.length<4&&r({value:i?n:t+1})},onKeyPress:e=>{"Enter"===e.key&&u()},value:n.value}),React__default.createElement("div",{className:"villain-label villain-label--center"},"/"),React__default.createElement("div",{className:"villain-label"},`${e}`))}),NavigationControls=()=>React__default.createElement("div",{className:"villain-toolbar__group"},React__default.createElement(ReaderContext.Consumer,null,({mangaMode:e,navigateBackward:t,navigateForward:i,isFirstPage:n,isLastPage:r})=>React__default.createElement(React__default.Fragment,null,React__default.createElement(NavigationButton,{icon:mdiChevronLeft,action:e?i:t,disabled:e?r:n,tooltip:e?"Next page":"Previous page"}),React__default.createElement(NavigationButton,{icon:mdiChevronRight,action:e?t:i,disabled:e?n:r,tooltip:e?"Previous page":"Next page"}))),React__default.createElement(ReaderContext.Consumer,null,({totalPages:e,currentPage:t,navigateToPage:i})=>React__default.createElement(NavigationInput,{totalPages:e,currentPage:t,navigateToPage:i}))),Toolbar=React.memo(({visible:e,container:t,updateZoom:i,zoomIn:n,zoomOut:r,...o})=>{const{togglePin:a,renderError:s,autoHideControls:l}=o,[c,u]=React__default.useState(!0),[h,d]=React__default.useState(!1);return React.useEffect(()=>{const t=e||h;t!==c&&u(t)},[e,h]),React__default.createElement("div",{"aria-label":"Toolbar",onMouseOver:()=>{d(!0)},onMouseLeave:()=>{d(!1)},className:clsx("villain-toolbar",!c&&"villain-toolbar--hide")},React__default.createElement(NavigationControls,null),React__default.createElement(ReaderContext.Consumer,null,({pages:e,totalPages:t,currentPage:i,mangaMode:n,navigateToPage:r})=>{const o=10*Math.round(e.length/t*10);return t&&React__default.createElement("div",{className:"villain-toolbar__group villain-toolbar__group--expand"},React__default.createElement(SliderUI,{max:t,value:i,reversed:n,onChange:r,bufferProgress:o}))}),React__default.createElement("div",{className:"villain-toolbar__group",disabled:s},React__default.createElement(ZoomControls,{zoomIn:n,zoomOut:r,onUpdate:i,disabled:s}),React__default.createElement("hr",{className:"villain-toolbar__divider"}),React__default.createElement(Settings$8,{forceClose:!c}),React__default.createElement(Button,{typeClass:"icon",icon:l?mdiPin:mdiPinOff,onClick:a,disabled:s,tooltip:l?"Pin toolbar":"Unpin toolbar",focusable:!0}),React__default.createElement(LayoutConsumer,{disabled:s}),React__default.createElement(FullscreenConsumer,{container:t,disabled:s})))}),ToolbarConsumer=React.memo(e=>{const[t,i]=React.useState(!1),[n,r]=React.useState(!1),o=()=>{i(!0)},a=()=>{i(!1)},s=()=>{r(!0)},l=()=>{r(!1)};return React.useEffect(()=>(e.container.addEventListener("blur",l,!0),e.container.addEventListener("focus",s,!0),e.container.addEventListener("mouseover",o),e.container.addEventListener("mouseleave",a),()=>{e.container.removeEventListener("blur",l,!0),e.container.removeEventListener("focus",s,!0),e.container.removeEventListener("mouseover",o),e.container.removeEventListener("mouseleave",a)}),[]),React__default.createElement(ReaderContext.Consumer,null,({fullscreen:i,renderError:r,autoHideControls:o,togglePin:a})=>React__default.createElement(Toolbar,_extends({},e,{visible:!o||n||t&&!i,renderError:r,autoHideControls:o,togglePin:a})))});function areInputsEqual(e,t){if(e.length!==t.length)return!1;for(var i=0;i{let n=e/100*t;return n>t&&(n=t),nparseInt(e/t*100),memoizeZoomPercent=memoizeOne(zoomPercent);class CanvasRender extends React__default.Component{constructor(e){super(e),_defineProperty(this,"getTargetZoom",(e=1)=>{let t=[];const{viewport:i,world:n}=this.viewer,r=n.getItemCount();for(let i=0;i{const{viewport:e}=this.viewer,t=this.getTargetZoom(),i=this.viewer.world.getHomeBounds(),n=e.getBounds(),r=i.width/i.height/(n.width/n.height),o=.9*(r>=1?1:r)/i.width,a=t<=o?t:o;e.defaultZoomLevel=a,e.minZoomLevel=a,e.maxZoomLevel=t}),_defineProperty(this,"updateZoom",(e=1)=>{const{viewport:t}=this.viewer,i=t.getMaxZoom(),n=t.getMinZoom();if(e){let r=memoizeZoomClamp(e,i,n);t.zoomTo(r,!0),t.ensureVisible(!0)}}),_defineProperty(this,"zoomIn",()=>{const{viewport:e}=this.viewer,t=e.getMaxZoom(),i=e.getZoom(),n=memoizeZoomPercent(i,t);this.updateZoom(n+10)}),_defineProperty(this,"zoomOut",()=>{const{viewport:e}=this.viewer,t=e.getMaxZoom(),i=e.getZoom(),n=memoizeZoomPercent(i,t);this.updateZoom(n-10)}),_defineProperty(this,"zoomToOriginalSize",()=>{const e=this.getTargetZoom();this.viewer.viewport.zoomTo(e,null,!0)}),_defineProperty(this,"handleError",e=>{const{updateCotextState:t}=this.props;this.viewer.close(),updateContextState({renderError:!0}),console.error(e)}),_defineProperty(this,"handleFullscreenChange",()=>{const{updateContextState:e}=this.props;e({fullscreen:null!==fullscreenElement()}),this.updateZoomLimits()}),_defineProperty(this,"handleZoom",({zoom:e})=>{const{viewport:t}=this.viewer,{updateContextState:i}=this.props,n=t.getMinZoom(),r=t.getMaxZoom(),o=memoizeZoomPercent(e,r);i({currentZoom:o,canZoomIn:en})}),_defineProperty(this,"handleZoomOptimized",debounce(e=>{this.isScrolling||this.handleZoom(e)},200)),_defineProperty(this,"handleScrollOptimized",()=>{this.isScrolling=!0,window.clearTimeout(this.clearScrollingDelay),this.clearScrollingDelay=setTimeout(()=>{this.isScrolling=!1,this.handleZoomOptimized({zoom:this.viewer.viewport.getZoom()})},400)}),_defineProperty(this,"initOpenSeaDragon",()=>{const{id:e,container:t,pages:i,renderError:n,updateContextState:r}=this.props;this.browser=getKeyByValue(openseadragon.BROWSERS,openseadragon.Browser.vendor),this.viewer=openseadragon({element:this.OSDContainer.current,tileSources:i[0],...config}),this.viewer.addHandler("open",()=>{this.renderLayout(),this.fitBounds(),n&&r({renderError:!1})}),this.viewer.addHandler("resize",()=>{this.updateZoomLimits()}),this.viewer.addHandler("zoom",this.handleZoomOptimized),this.viewer.addHandler("canvas-scroll",this.handleScrollOptimized),this.viewer.addHandler("open-failed",this.handleError),onFullscreenChange(t,"add",this.handleFullscreenChange)}),this.viewer=null,this.browser=null,this.isScrolling=!1,this.OSDContainer=React__default.createRef(),this.clearScrollingDelay=null}renderPage(e){const t=this.props.getPage(e);t&&this.viewer.open(t)}renderCover(){this.renderPage(0)}fitBounds(){const{viewport:e}=this.viewer;this.fitPages(),this.updateZoomLimits(),e.zoomTo(e.getMinZoom(),null,!0)}renderLayout(){const{world:e}=this.viewer,{mangaMode:t,bookMode:i}=this.props,n=new openseadragon.Point(0,0),r=e.getItemCount();let o=null,a=i&&t&&r>1?1:0,s=null,l=null,c=null,u=i&&t?0:1;r>0&&(o=e.getItemAt(a),s=o.getBounds(),r>1&&(l=e.getItemAt(u),c=l.getBounds(),s.height>c.height&&(l.setHeight(s.height,!0),c=l.getBounds()),c.height>s.height&&(o.setHeight(c.height,!0),s=o.getBounds())),o&&s&&(o.setPosition(n,!0),n.x+=s.width),l&&c&&(l.setPosition(n,!0),n.x+=c.width))}fitPagesLegacy(){const{viewport:e,world:t}=this.viewer,i=t.getHomeBounds();e.fitBoundsWithConstraints(i,!0)}fitPages(e){const{viewport:t,world:i}=this.viewer;e||this.fitPagesLegacy(),"vertical"===e&&t.fitVertically(!0),"horizontal"===e&&t.fitHorizontally(!0)}componentDidMount(){const{initialPage:e}=this.props;this.initOpenSeaDragon(),this.renderPage(e)}componentWillUnmount(){const{container:e}=this.props;onFullscreenChange(e,"remove",this.handleFullscreenChange),this.viewer.destroy(),this.viewer=null}componentDidUpdate(e){const{bookMode:t,mangaMode:i,totalPages:n,currentPage:r}=this.props;r===e.currentPage&&t===e.bookMode||r>=0&&rReact__default.createElement(ReaderContext.Consumer,null,({ready:t,error:i,hover:n,pages:r,bookMode:o,mangaMode:a,totalPages:s,currentPage:l,renderError:c,allowFullScreen:u,allowGlobalShortcuts:h,getPage:d,updateState:p})=>{return t&&!i&&React__default.createElement(CanvasRender,{hover:n,pages:r,container:e,currentPage:l,getPage:d,bookMode:o,mangaMode:a,totalPages:s,renderError:c,allowFullScreen:u,allowGlobalShortcuts:h,updateContextState:p})})),Villain=({source:e,style:t,options:i,workerUrl:n})=>React__default.createElement(ReaderProvider,{externalOptions:i},React__default.createElement(Wrapp,{style:t},t=>React__default.createElement(React__default.Fragment,null,React__default.createElement(KeyboardConsumer,{container:t}),React__default.createElement(OptionsConsumer,{options:i}),React__default.createElement(UncompressConsumer,{source:e,workerUrl:n}),React__default.createElement(CanvasRenderConsumer,{container:t}))));Villain.propTypes={source:propTypes.oneOfType([propTypes.string,propTypes.instanceOf(Blob)]),workerUrl:propTypes.string,options:propTypes.shape({theme:propTypes.string,maxPages:propTypes.number,allowFullscreen:propTypes.boolean,allowGlobalShortcuts:propTypes.boolean})};var index=React__default.memo(Villain);return index})); diff --git a/packages/villain-react/package.json b/packages/villain-react/package.json deleted file mode 100644 index 19d998a6..00000000 --- a/packages/villain-react/package.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "name": "villain-react", - "version": "1.0.9", - "description": "An open source web based comic book reader as a react component", - "main": "./dist/villain.js", - "scripts": { - "start": "webpack-dev-server --config ./webpack.config.js --mode development --open --hot", - "build": "rollup -c rollup.config.js", - "watch": "rollup -c rollup.config.js -w", - "test": "jest" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/btzr-io/Villain.git" - }, - "files": [ - "dist/" - ], - "keywords": [ - "comic", - "comics", - "comic book", - "react", - "reader", - "viewer" - ], - "author": "Baltazar Gomez", - "license": "MIT", - "bugs": { - "url": "https://github.com/btzr-io/Villain/issues" - }, - "homepage": "https://github.com/btzr-io/Villain#readme", - "jest": { - "setupFilesAfterEnv": [ - "test/setupTests.js" - ] - }, - "dependencies": { - "clsx": "^1.1.1", - "libarchive.js": "^1.3.0", - "memoize-one": "^5.1.1", - "openseadragon": "^2.4.2", - "prop-types": "^15.7.2", - "react-compound-slider": "^2.5.0", - "react-localization": "^1.0.15", - "react-spring": "^8.0.27" - }, - "devDependencies": { - "@babel/core": "^7.7.7", - "@babel/plugin-proposal-class-properties": "^7.4.4", - "@babel/preset-env": "^7.9.5", - "@babel/preset-react": "^7.0.0", - "babel-plugin-transform-xregexp": "^1.0.0", - "@mdi/js": "^5.0.45", - "@mdi/react": "^1.1.1", - "@rollup/plugin-alias": "^3.0.0", - "@rollup/plugin-json": "^4.0.1", - "@rollup/plugin-node-resolve": "^6.1.0", - "@rollup/plugin-replace": "^2.3.0", - "babel-jest": "^25.3.0", - "babel-loader": "^8.0.5", - "babel-plugin-module-resolver": "^4.0.0", - "css-loader": "^3.4.1", - "enzyme": "^3.11.0", - "enzyme-adapter-react-16": "^1.15.2", - "eslint": "^6.8.0", - "eslint-plugin-react": "^7.16.0", - "jest": "^25.3.0", - "node-sass": "^4.13.0", - "react": "^16.8.6", - "react-dom": "^16.8.6", - "reakit": "^1.0.0-beta.14", - "rollup": "^2.0.5", - "rollup-plugin-babel": "^4.3.2", - "rollup-plugin-commonjs": "^10.1.0", - "rollup-plugin-peer-deps-external": "^2.2.0", - "rollup-plugin-postcss": "^3.1.3", - "rollup-plugin-terser": "^5.3.0", - "sass-loader": "^9.0.2", - "style-loader": "^1.1.1", - "webpack": "^4.41.4", - "webpack-cli": "^3.3.2", - "webpack-dev-server": "^3.10.1", - "worker-loader": "^2.0.0" - }, - "peerDependencies": { - "react": "^16.8.6", - "react-dom": "^16.8.6", - "reakit": "^1.0.0-beta.14" - } -} diff --git a/packages/villain-react/rollup.config.js b/packages/villain-react/rollup.config.js deleted file mode 100644 index 335e2c23..00000000 --- a/packages/villain-react/rollup.config.js +++ /dev/null @@ -1,51 +0,0 @@ -import babel from 'rollup-plugin-babel' -import resolve from '@rollup/plugin-node-resolve' -import commonjs from 'rollup-plugin-commonjs' -import replace from '@rollup/plugin-replace' -import alias from '@rollup/plugin-alias' -import { terser } from 'rollup-plugin-terser' -import json from '@rollup/plugin-json' -import path from 'path' -import postcss from 'rollup-plugin-postcss' -import peerDepsExternal from 'rollup-plugin-peer-deps-external' -import { fileURLToPath } from 'url' - -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - -export default { - input: './src/index.js', - - output: { - file: './dist/villain.js', - name: 'villain', - format: 'umd', - globals: { - react: 'React', - reakit: 'reakit', - 'react-dom': 'ReactDOM', - }, - }, - plugins: [ - peerDepsExternal(), - postcss({ - extract: './dist/style.css', - modules: false, - minimize: true, - }), - babel({ - exclude: 'node_modules/**', - }), - replace({ - 'process.env.NODE_ENV': JSON.stringify('development'), - }), - alias({ - resolve: ['/index.js', '/index.jsx', '.js', '.jsx', '.json', '.css', '.scss'], - }), - json(), - commonjs(), - resolve(), - terser(), - ], - - external: ['react', 'react-dom', 'reakit'], -} diff --git a/packages/villain-react/src/components/keyboard.js b/packages/villain-react/src/components/keyboard.js deleted file mode 100644 index 84223dab..00000000 --- a/packages/villain-react/src/components/keyboard.js +++ /dev/null @@ -1,73 +0,0 @@ -import React from 'react' -import { ReaderContext } from '@/context' -import { getNestedFocus, getInteractionFocus } from '@/hooks/use-focus' -import { toggleFullscreen } from '@/lib/full-screen' - -const KeyboardConsumer = React.memo(({ container }) => { - const context = React.useContext(ReaderContext) - - const { - error, - mangaMode, - navigateBackward, - navigateForward, - allowGlobalShortcuts, - allowFullScreen, - } = context - - // Note: We should provide an api to add, define, overwrite key shortcuts - const handleShortcuts = React.useCallback( - event => { - // Check if it should restrict listening for key shortcuts on player focus - if (error || getInteractionFocus()) { - return - } - - if (!allowGlobalShortcuts && !getNestedFocus(container)) { - return - } - - const navigateRight = mangaMode ? navigateBackward : navigateForward - const navigateLeft = mangaMode ? navigateForward : navigateBackward - - switch (event.key) { - // Toggle fullscreen of viewer. - // Note: PreventDefault is used to remove flp shortcut. - case 'f': - event.preventDefault() - toggleFullscreen(container) - break - - // Navigation to next page (previous when in mangaMode) - case 'ArrowRight': - navigateRight() - break - - // Navigation to previous page (next when in mangaMode) - case 'ArrowLeft': - navigateLeft() - break - } - }, - [ - allowFullScreen, - allowGlobalShortcuts, - mangaMode, - navigateBackward, - navigateForward, - container, - ] - ) - - React.useEffect(() => { - document.addEventListener('keydown', handleShortcuts) - - return () => { - document.removeEventListener('keydown', handleShortcuts) - } - }, [handleShortcuts]) - - return null -}) - -export default KeyboardConsumer diff --git a/packages/villain-react/src/components/loader.js b/packages/villain-react/src/components/loader.js deleted file mode 100644 index 7bf4cc74..00000000 --- a/packages/villain-react/src/components/loader.js +++ /dev/null @@ -1,9 +0,0 @@ -import React from 'react' - -const Loader = React.memo(({ id }) => ( -
-
-
-)) - -export default Loader diff --git a/packages/villain-react/src/components/localized.js b/packages/villain-react/src/components/localized.js deleted file mode 100644 index e43a0e1e..00000000 --- a/packages/villain-react/src/components/localized.js +++ /dev/null @@ -1,12 +0,0 @@ -import React from 'react' -import { ReaderContext } from '@/context' -import Localize from '@/localize' - -const Localized = React.memo(({ value, language }) => Localize[value]) - -const LocalizedConsumer = React.memo(({ value }) => { - const { language } = React.useContext(ReaderContext) - return -}) - -export default LocalizedConsumer diff --git a/packages/villain-react/src/components/menu/custom.js b/packages/villain-react/src/components/menu/custom.js deleted file mode 100644 index ed920f9f..00000000 --- a/packages/villain-react/src/components/menu/custom.js +++ /dev/null @@ -1,88 +0,0 @@ -import React from 'react' -import Icon from '@mdi/react' -import Button from '@/components/toolbar/button' -import Localized from '@/components/localized' - -import { - MenuItem, - MenuSeparator, - MenuItemRadio, - MenuItemCheckbox, - useMenuState, -} from 'reakit' - -import { - mdiChevronLeft, - mdiChevronRight, - mdiRadioboxBlank, - mdiRadioboxMarked, -} from '@mdi/js' - -export const CustomSeparator = React.forwardRef((props, ref) => ( - -)) - -export const CustomItem = React.forwardRef(({ children, ...props }, ref) => ( - -
-
{children}
-
-
-)) - -export const CustomCheckbox = React.forwardRef(({ children, ...props }, ref) => ( - -
-
{children}
-
-
- -)) - -export const CustomRadio = React.forwardRef(({ children, ...props }, ref) => ( - -
-
{children}
-
-
-)) - -export const CustomSubmenu = React.forwardRef(({ children, ...props }, ref) => ( - -
-
{children}
- -
-
-)) - -export const MenuHeader = React.forwardRef( - ({ title, closeSubmenu, menuProps, ...props }, ref) => { - return ( -
- - - - -
- ) - } -) - -export const CustomItems = { - item: React.memo(CustomItem), - radio: React.memo(CustomRadio), - submenu: React.memo(CustomSubmenu), - checkbox: React.memo(CustomCheckbox), - separator: React.memo(CustomSeparator), -} diff --git a/packages/villain-react/src/components/menu/index.js b/packages/villain-react/src/components/menu/index.js deleted file mode 100644 index a7b8c111..00000000 --- a/packages/villain-react/src/components/menu/index.js +++ /dev/null @@ -1,231 +0,0 @@ -import React from 'react' -import { MenuHeader } from '@/components/menu/custom' -import { Item, ItemList } from '@/components/menu/item' -import { animated, useSpring } from 'react-spring' - -import { Menu, MenuDisclosure, useMenuState } from 'reakit' - -const MenuPanel = React.forwardRef( - ({ title, items, list, openSubmenu, closeSubmenu, menuProps }, ref) => { - return ( -
- {title && ( - - )} - {list ? ( - - ) : ( - items && - items.map(({ nestedTitle, nestedItems, nestedList, ...itemProps }) => { - return ( - - ) - }) - )} -
- ) - } -) - -const PureMenuPanel = React.memo(MenuPanel) - -const defaultSubmenuState = { - id: null, - list: null, - title: null, - items: null, - visible: false, -} - -const BaseMenu = React.forwardRef( - ({ disclosure, tooltip, items, placement, ariaLabel, forceClose, ...props }, ref) => { - const menu = useMenuState({ placement, gutter: 20, unstable_animated: true }) - const subRef = React.useRef(null) - const mainRef = React.useRef(null) - - const [menuHeight, setMenuHeight] = React.useState(0) - const [submenuState, setSubmenuState] = React.useState(defaultSubmenuState) - const [animationState, setAnimationState] = React.useState(false) - - const maxHeight = 240 - - const reset = () => { - setSubmenuState({ ...defaultSubmenuState }) - } - - const handleSubmenuOpen = id => { - setSubmenuState({ ...submenuState, id }) - } - - const handleSubmenuClose = () => { - reset() - } - - const handleMenuClose = () => { - reset() - } - - const handleAnimationStart = () => { - setAnimationState(true) - } - - const handleAnimationRest = () => { - setAnimationState(false) - menu.unstable_stopAnimation() - } - - const [menuAnimatedProps, updateMenuSpring, stopMenuSpring] = useSpring(() => ({ - height: `${menuHeight}px`, - opacity: 0, - onRest: handleAnimationRest, - onStart: handleAnimationStart, - config: { clamp: true, velocity: 5, friction: 20 }, - })) - - React.useEffect(() => { - // Animated height - updateMenuSpring({ height: `${menuHeight}px` }) - }, [menuHeight]) - - // Handle menu - React.useEffect(() => { - if (menu.visible && mainRef.current !== null) { - // In rare cases like on electron, this will be executed before the menu - // is truly visible, so height will always be equal to "0px" - // - Todo: Find a better solution for this! - setTimeout(() => { - const mainElementHeight = mainRef.current.clientHeight - const nextHeight = mainElementHeight > maxHeight ? maxHeight : mainElementHeight - setMenuHeight(nextHeight) - menu.unstable_update() - }, 100) - } - - // Animated opacity - updateMenuSpring({ opacity: menu.visible ? 1 : 0 }) - }, [menu.visible]) - - // Handle parent close - React.useEffect(() => { - if (forceClose) { - menu.hide() - } - }, [forceClose]) - - React.useEffect(() => { - if (!animationState && !menu.visible) { - handleMenuClose() - } - }, [animationState]) - - // Handle submenu - React.useEffect(() => { - // Update submenu content - if (submenuState.id) { - // Check if selected iteam exist - const selected = - items && items.length > 0 && items.find(item => item.id === submenuState.id) - - if (selected) { - // Contains a list of similar items - const hasNestedList = - selected.nestedList && - selected.nestedList.items && - selected.nestedList.items.length > 0 - - // Contains items - const hasNestedItems = selected.nestedItems && selected.nestedItems.length > 0 - - // Validate state update - const visible = hasNestedList || hasNestedItems - - // Update submenu state and show it - if (visible) { - setSubmenuState({ - ...submenuState, - visible: true, - list: hasNestedList ? selected.nestedList : null, - items: hasNestedItems ? selected.nestedItems : null, - title: selected.nestedTitle, - }) - } - } - } - }, [submenuState.id]) - - // Submenu transition - React.useEffect(() => { - // Submenu open - if (submenuState.visible && subRef.current) { - const subElementHeight = subRef.current.clientHeight - const nextHeight = subElementHeight > maxHeight ? maxHeight : subElementHeight - - if (menuHeight !== nextHeight) { - setMenuHeight(nextHeight) - } - } - - // Submenu close - if (!submenuState.visible && mainRef.current) { - const mainElementHeight = mainRef.current.clientHeight - const nextHeight = mainElementHeight > maxHeight ? maxHeight : mainElementHeight - - if (menuHeight !== nextHeight) { - setMenuHeight(nextHeight) - } - } - menu.unstable_update() - }, [submenuState.visible]) - - return ( - - - - - {!submenuState.visible ? ( - - ) : ( - - )} - - - - ) - } -) - -export default React.memo(BaseMenu) diff --git a/packages/villain-react/src/components/menu/item.js b/packages/villain-react/src/components/menu/item.js deleted file mode 100644 index 19abceea..00000000 --- a/packages/villain-react/src/components/menu/item.js +++ /dev/null @@ -1,47 +0,0 @@ -import React from 'react' -import clsx from 'clsx' -import Icon from '@mdi/react' -import Localized from '@/components/localized' -import { MenuGroup } from 'reakit' -import { CustomItems } from '@/components/menu/custom' - -export const Item = React.memo( - React.forwardRef( - ({ id, itemType, content, children, openSubmenu, onClick, ...props }, ref) => { - const ContainerType = CustomItems[itemType] || CustomItems.item - - const handleClick = e => { - onClick && onClick(e) - // Close submenu - if (itemType === 'submenu') { - openSubmenu && openSubmenu(id) - } - } - - const itemClass = clsx( - itemType !== 'separator' && 'villain-menu__item', - itemType && `villain-menu__${itemType}` - ) - - return ( - - {content ? : children} - - ) - } - ) -) - -export const ItemList = React.memo( - ({ title, items, getProps, menuProps, getContent, closeSubmenu }) => { - return ( - - {items.map((item, index) => ( - - {getContent && getContent(item)} - - ))} - - ) - } -) diff --git a/packages/villain-react/src/components/options.js b/packages/villain-react/src/components/options.js deleted file mode 100644 index 5da12d8b..00000000 --- a/packages/villain-react/src/components/options.js +++ /dev/null @@ -1,19 +0,0 @@ -import React from 'react' -import { ReaderContext } from '@/context' - -// Renderless component to sync props with context state -const OptionsConsumer = React.memo(({ options }) => { - const context = React.useContext(ReaderContext) - // Update context state on props change - React.useEffect(() => { - Object.entries(options).map(([key, value]) => { - if (context[key] !== value) { - context.updateState({ [key]: value }) - } - }) - }, [options]) - // Nothing to render - return null -}) - -export default OptionsConsumer diff --git a/packages/villain-react/src/components/render.js b/packages/villain-react/src/components/render.js deleted file mode 100644 index ac9ece07..00000000 --- a/packages/villain-react/src/components/render.js +++ /dev/null @@ -1,383 +0,0 @@ -import clsx from 'clsx' -import React from 'react' -import OpenSeaDragon from 'openseadragon' -import OSDConfig from '@/osd.config' -import RenderError from '@/components/renderError' -import ToolbarConsumer from '@/components/toolbar' -import { ReaderContext } from '../context' -import { getKeyByValue, debounce } from '@/lib/utils' -import { getNestedFocus } from '@/hooks/use-focus' -import { memoizeZoomClamp, memoizeZoomPercent } from '@/lib/zoom-parser' -import { fullscreenElement, onFullscreenChange } from '@/lib/full-screen' - -// Icons -import { mdiImageBrokenVariant } from '@mdi/js' - -class CanvasRender extends React.Component { - static defaultProps = { - initialPage: 0, - } - - constructor(props) { - super(props) - this.viewer = null - this.browser = null - this.isScrolling = false - this.OSDContainer = React.createRef() - this.clearScrollingDelay = null - } - - // Get the max target zoom - getTargetZoom = (scale = 1) => { - let zooms = [] - const { viewport, world } = this.viewer - const count = world.getItemCount() - - for (let i = 0; i < count; i++) { - zooms[i] = world.getItemAt(i).imageToViewportZoom(scale) - } - - return Math.max(zooms) || zooms[0] - } - - updateZoomLimits = () => { - const { viewport } = this.viewer - const targetZoom = 0.9 - const realTargetZoom = this.getTargetZoom() - const imageBounds = this.viewer.world.getHomeBounds() - const viewportBounds = viewport.getBounds() - const imageAspect = imageBounds.width / imageBounds.height - const viewportAspect = viewportBounds.width / viewportBounds.height - const aspectFactor = imageAspect / viewportAspect - const zoomFactor = (aspectFactor >= 1 ? 1 : aspectFactor) * targetZoom - const zoom = zoomFactor / imageBounds.width - const minZoom = realTargetZoom <= zoom ? realTargetZoom : zoom - viewport.defaultZoomLevel = minZoom - viewport.minZoomLevel = minZoom - viewport.maxZoomLevel = realTargetZoom - } - - updateZoom = (scale = 1) => { - const { viewport } = this.viewer - const max = viewport.getMaxZoom() - const min = viewport.getMinZoom() - - if (scale) { - // Clamp zoom value - let zoom = memoizeZoomClamp(scale, max, min) - // Update - viewport.zoomTo(zoom, true) - viewport.ensureVisible(true) - } - } - - zoomIn = () => { - const { viewport } = this.viewer - const max = viewport.getMaxZoom() - const zoom = viewport.getZoom() - const currentZoom = memoizeZoomPercent(zoom, max) - this.updateZoom(currentZoom + 10) - } - - zoomOut = () => { - const { viewport } = this.viewer - const max = viewport.getMaxZoom() - const zoom = viewport.getZoom() - const currentZoom = memoizeZoomPercent(zoom, max) - this.updateZoom(currentZoom - 10) - } - - zoomToOriginalSize = () => { - const targetZoom = this.getTargetZoom() - this.viewer.viewport.zoomTo(targetZoom, null, true) - } - - handleError = error => { - const { updateCotextState } = this.props - this.viewer.close() - updateContextState({ renderError: true }) - // Debug error - console.error(error) - } - - handleFullscreenChange = () => { - const { updateContextState } = this.props - const fullscreen = fullscreenElement() !== null - updateContextState({ fullscreen }) - this.updateZoomLimits() - } - - handleZoom = ({ zoom }) => { - const { viewport } = this.viewer - const { updateContextState } = this.props - const min = viewport.getMinZoom() - const max = viewport.getMaxZoom() - const currentZoom = memoizeZoomPercent(zoom, max) - const canZoomIn = zoom < max && currentZoom < 100 - const canZoomOut = zoom > min - updateContextState({ currentZoom, canZoomIn, canZoomOut }) - } - - handleZoomOptimized = debounce(event => { - // Unable to update zoom on scroll inside this event handler: - // - Bad peformance from multiple context update state calls - // - Small delay for text updating noticeable. - if (!this.isScrolling) { - this.handleZoom(event) - } - }, 200) - - handleScrollOptimized = () => { - // Reset scrolling flag - this.isScrolling = true - // Clear our timeout throughout the scroll - window.clearTimeout(this.clearScrollingDelay) - // Set a timeout to run after scrolling ends - this.clearScrollingDelay = setTimeout(() => { - this.isScrolling = false - this.handleZoomOptimized({ zoom: this.viewer.viewport.getZoom() }) - }, 400) - } - - initOpenSeaDragon = () => { - const { id, container, pages, renderError, updateContextState } = this.props - - // Detect browser vendor - this.browser = getKeyByValue(OpenSeaDragon.BROWSERS, OpenSeaDragon.Browser.vendor) - - // Create viewer - this.viewer = OpenSeaDragon({ - element: this.OSDContainer.current, - tileSources: pages[0], - ...OSDConfig, - }) - - // Events handler - this.viewer.addHandler('open', () => { - this.renderLayout() - this.fitBounds() - - // Prevent unessesart context updates - if (renderError) { - updateContextState({ renderError: false }) - } - }) - - // Events handler - this.viewer.addHandler('resize', () => { - this.updateZoomLimits() - }) - - // Fallback to improve peformance on zoom upodates" - // Fix issue with animations and peformance, see: - // https://github.com/btzr-io/Villain/issues/66 - this.viewer.addHandler('zoom', this.handleZoomOptimized) - // Optimized scroll event - this.viewer.addHandler('canvas-scroll', this.handleScrollOptimized) - - this.viewer.addHandler('open-failed', this.handleError) - - onFullscreenChange(container, 'add', this.handleFullscreenChange) - } - - renderPage(index) { - const page = this.props.getPage(index) - page && this.viewer.open(page) - } - - renderCover() { - this.renderPage(0) - } - - fitBounds() { - const { viewport } = this.viewer - this.fitPages() - this.updateZoomLimits() - viewport.zoomTo(viewport.getMinZoom(), null, true) - } - - renderLayout() { - const { world } = this.viewer - const { mangaMode, bookMode } = this.props - const pos = new OpenSeaDragon.Point(0, 0) - const count = world.getItemCount() - - // Cache tile data - let bounds = null - // first page - let firstPage = null - let firstPageIndex = bookMode && mangaMode && count > 1 ? 1 : 0 - let firstPageBounds = null - // Next page - let nextPage = null - let nextPageBounds = null - let nextPageIndex = bookMode && mangaMode ? 0 : 1 - - if (count > 0) { - // Page view (single page) - firstPage = world.getItemAt(firstPageIndex) - firstPageBounds = firstPage.getBounds() - - // Book view ( two pages ) - if (count > 1) { - nextPage = world.getItemAt(nextPageIndex) - nextPageBounds = nextPage.getBounds() - - // Auto resize page to fit first page height - if (firstPageBounds.height > nextPageBounds.height) { - nextPage.setHeight(firstPageBounds.height, true) - // Recalculate bounds - nextPageBounds = nextPage.getBounds() - } - - // Auto resize page to fit next page height - if (nextPageBounds.height > firstPageBounds.height) { - firstPage.setHeight(nextPageBounds.height, true) - // Recalculate bounds - firstPageBounds = firstPage.getBounds() - } - } - - // Set position for first page - if (firstPage && firstPageBounds) { - firstPage.setPosition(pos, true) - pos.x += firstPageBounds.width - } - - // Set position for next page - if (nextPage && nextPageBounds) { - nextPage.setPosition(pos, true) - pos.x += nextPageBounds.width - } - } - } - - fitPagesLegacy() { - const { viewport, world } = this.viewer - const bounds = world.getHomeBounds() - viewport.fitBoundsWithConstraints(bounds, true) - } - - fitPages(orientation) { - const { viewport, world } = this.viewer - - if (!orientation) { - this.fitPagesLegacy() - } - - if (orientation === 'vertical') { - viewport.fitVertically(true) - } - - if (orientation === 'horizontal') { - viewport.fitHorizontally(true) - } - } - - componentDidMount() { - const { initialPage } = this.props - this.initOpenSeaDragon() - this.renderPage(initialPage) - } - - componentWillUnmount() { - const { container } = this.props - // Remove event listeners - onFullscreenChange(container, 'remove', this.handleFullscreenChange) - // Destroy OpenSeaDragon viewer - this.viewer.destroy() - this.viewer = null - } - - componentDidUpdate(prevProps) { - const { bookMode, mangaMode, totalPages, currentPage } = this.props - - // Page changed - if (currentPage !== prevProps.currentPage || bookMode !== prevProps.bookMode) { - // Render new valid page - if (currentPage >= 0 && currentPage < totalPages) { - this.renderPage(currentPage) - } - } - - // Page changed - if (bookMode !== prevProps.bookMode) { - if (bookMode) { - // Trigger re-render layout - this.renderLayout() - this.fitBounds() - } - } - - // Re-render layout when mangaMode and there and book mode is active - if (mangaMode !== prevProps.mangaMode && bookMode) { - this.renderLayout() - } - } - - render() { - const { id, container, renderError } = this.props - - return ( - - -
- {renderError && ( - - )} - - ) - } -} - -const CanvasRenderConsumer = React.memo(({ container }) => { - return ( - - {({ - // State - ready, - error, - hover, - pages, - bookMode, - mangaMode, - totalPages, - currentPage, - renderError, - allowFullScreen, - allowGlobalShortcuts, - // Actions - getPage, - updateState, - }) => { - const shouldRender = ready && !error - - return ( - shouldRender && ( - - ) - ) - }} - - ) -}) - -export default CanvasRenderConsumer diff --git a/packages/villain-react/src/components/renderError.js b/packages/villain-react/src/components/renderError.js deleted file mode 100644 index ce7698d2..00000000 --- a/packages/villain-react/src/components/renderError.js +++ /dev/null @@ -1,19 +0,0 @@ -import React from 'react' -import Icon from '@mdi/react' -import Localized from '@/components/localized' - -const Error = React.memo(props => { - const { icon, message } = props - return ( -
- -
-

- -

-
-
- ) -}) - -export default Error diff --git a/packages/villain-react/src/components/slider/handle.js b/packages/villain-react/src/components/slider/handle.js deleted file mode 100644 index 38890659..00000000 --- a/packages/villain-react/src/components/slider/handle.js +++ /dev/null @@ -1,112 +0,0 @@ -import React, { memo, useState, useEffect } from 'react' -import PropTypes from 'prop-types' -import Button from '@/components/toolbar/button' -import { animated, useSpring } from 'react-spring' - -const HandlerTooltip = memo(({ value, visible }) => { - const [shouldRender, setShouldRender] = useState(false) - - const [tooltipAnimatedProps, updateTooltipSpring, stopTooltipSpring] = useSpring( - () => ({ - delay: 0, - opacity: 1, - transform: 'scale(1)', - config: { clamp: true, velocity: 14, friction: 20 }, - }) - ) - - useEffect(() => { - updateTooltipSpring({ - delay: visible ? 200 : 800, - opacity: visible ? 1 : 0, - onRest: () => { - if (!visible) { - setShouldRender(false) - } - }, - onStart: () => { - if (visible) { - setShouldRender(true) - } - }, - transform: `scale(${visible ? 1 : 0})`, - }) - }, [visible]) - - return ( - shouldRender && ( - - {value} - - ) - ) -}) - -HandlerTooltip.propTypes = { - value: PropTypes.number, -} - -const Handle = ({ - domain: [min, max], - handle: { id, value, percent }, - isActive, - disabled, - getHandleProps, -}) => { - const [mouseOver, setMouseOver] = useState(false) - - const onMouseEnter = () => { - setMouseOver(true) - } - - const onMouseLeave = () => { - setMouseOver(false) - } - - const showTooltip = (mouseOver || isActive) && !disabled - - return ( - - ) -} - -Handle.propTypes = { - domain: PropTypes.array.isRequired, - handle: PropTypes.shape({ - id: PropTypes.string.isRequired, - value: PropTypes.number.isRequired, - percent: PropTypes.number.isRequired, - }).isRequired, - getHandleProps: PropTypes.func.isRequired, - isActive: PropTypes.bool.isRequired, - disabled: PropTypes.bool, -} - -export default memo(Handle) diff --git a/packages/villain-react/src/components/slider/index.js b/packages/villain-react/src/components/slider/index.js deleted file mode 100644 index f8bd9619..00000000 --- a/packages/villain-react/src/components/slider/index.js +++ /dev/null @@ -1,122 +0,0 @@ -import React, { useState, useEffect, memo } from 'react' -import { Slider, Rail, Handles, Tracks } from 'react-compound-slider' -import Handle from './handle' -import SliderRail from './sliderRail' - -const mainColor = '#FFF' - -const sliderStyle = { - position: 'absolute', - width: '100%', - height: 4, - display: 'flex', - alignItems: 'center', - borderRadius: '4px', - justifyContent: 'center', - zIndex: 99, -} - -const Track = memo(({ source, target, getTrackProps }) => { - return ( -
- ) -}) - -const BufferLoader = memo(({ bufferProgress, reversed }) => { - return ( -
- ) -}) - -const defaultValues = [1] - -const SliderUI = memo(({ max = 1, bufferProgress = 0, reversed, onChange, value }) => { - const [seeking, setSeeking] = useState(false) - const [values, setValue] = useState(defaultValues.slice()) - - const domain = [1, max] - - if (max == 1) return null - - const handleChange = values => { - setSeeking(false) - onChange(values[0] - 1) - } - - useEffect(() => { - if (!seeking) setValue([value + 1]) - }, [value]) - - return ( -
- setSeeking(true)} - onChange={handleChange} - reversed={reversed} - > - - {({ activeHandleID, getEventData, getRailProps }) => ( - - )} - - - - {({ handles, activeHandleID, getHandleProps }) => ( -
- {handles.map(handle => ( - - ))} -
- )} -
- - - {({ tracks, getTrackProps }) => ( -
- {tracks.map(({ id, source, target }) => ( - - ))} -
- )} -
-
- -
- ) -}) - -export default SliderUI diff --git a/packages/villain-react/src/components/slider/sliderRail.js b/packages/villain-react/src/components/slider/sliderRail.js deleted file mode 100644 index 2840a5e6..00000000 --- a/packages/villain-react/src/components/slider/sliderRail.js +++ /dev/null @@ -1,24 +0,0 @@ -import React, { memo } from 'react' -import PropTypes from 'prop-types' - -const railStyle = { - position: 'absolute', - margin: 0, - width: '100%', - height: '100%', - cursor: 'pointer', - borderRadius: '4px', - backgroundColor: 'var(--slider-bg)', - zIndex: -1, -} - -const SliderRail = memo(({ activeHandleID, getEventData, getRailProps }) => { - return
-}) - -SliderRail.propTypes = { - activeHandleID: PropTypes.string, - getEventData: PropTypes.func.isRequired, - getRailProps: PropTypes.func.isRequired, -} -export default SliderRail diff --git a/packages/villain-react/src/components/toolbar/button.js b/packages/villain-react/src/components/toolbar/button.js deleted file mode 100644 index edc8ff48..00000000 --- a/packages/villain-react/src/components/toolbar/button.js +++ /dev/null @@ -1,60 +0,0 @@ -import React from 'react' -import Icon from '@mdi/react' -import clsx from 'clsx' -import { Button } from 'reakit' -import Tooltip from '@/components/tooltip' - -const ToolbarButton = React.forwardRef( - ( - { - icon, - iconSize, - label, - title, - active, - tooltip, - onClick, - children, - typeClass, - tooltipPlacement, - ...otherProps - }, - ref - ) => { - const containerProps = { ref, ...otherProps } - const otherButtonProps = !tooltip ? containerProps : {} - - let elem = ( - - ) - - if (tooltip) { - elem = ( - - {elem} - - ) - } - - return elem - } -) - -export default React.memo(ToolbarButton) diff --git a/packages/villain-react/src/components/toolbar/controls/fullscreen.js b/packages/villain-react/src/components/toolbar/controls/fullscreen.js deleted file mode 100644 index 26ea6f0d..00000000 --- a/packages/villain-react/src/components/toolbar/controls/fullscreen.js +++ /dev/null @@ -1,40 +0,0 @@ -import React from 'react' -import Button from '@/components/toolbar/button' -import { ReaderContext } from '@/context' -import { mdiFullscreen, mdiFullscreenExit } from '@mdi/js' -import { toggleFullscreen } from '@/lib/full-screen' - -const FullscreenButton = React.memo(({ fullscreen, container, disabled }) => { - const handleToggleFullscreen = () => { - toggleFullscreen(container) - } - - return ( -
-
- ) - } -) - -const ToolbarConsumer = memo(props => { - // Local state is used instead of context for better peformance - const [hover, setHover] = useState(false) - const [focus, setFocus] = useState(false) - - const handleMouseOver = () => { - setHover(true) - } - - const handleMouseLeave = () => { - setHover(false) - } - - const handleFocus = () => { - setFocus(true) - } - - const handleBlur = () => { - setFocus(false) - } - - useEffect(() => { - props.container.addEventListener('blur', handleBlur, true) - props.container.addEventListener('focus', handleFocus, true) - props.container.addEventListener('mouseover', handleMouseOver) - props.container.addEventListener('mouseleave', handleMouseLeave) - return () => { - props.container.removeEventListener('blur', handleBlur, true) - props.container.removeEventListener('focus', handleFocus, true) - props.container.removeEventListener('mouseover', handleMouseOver) - props.container.removeEventListener('mouseleave', handleMouseLeave) - } - }, []) - - return ( - - {({ - // State - fullscreen, - renderError, - autoHideControls, - // Actions - togglePin, - }) => ( - - )} - - ) -}) - -export default ToolbarConsumer diff --git a/packages/villain-react/src/components/toolbar/settings.js b/packages/villain-react/src/components/toolbar/settings.js deleted file mode 100644 index 34ce0cf7..00000000 --- a/packages/villain-react/src/components/toolbar/settings.js +++ /dev/null @@ -1,124 +0,0 @@ -import React from 'react' -import Menu from '@/components/menu' -import Localized from '@/components/localized' -import Localize from '@/localize' -import Button from '@/components/toolbar/button' -import { ReaderContext } from '@/context' - -import getLanguageName from '@/lib/language-name' - -import Icon from '@mdi/react' - -import { - mdiCog, - mdiKeyboard, - mdiTranslate, - mdiBrightness4, - mdiPagePrevious, -} from '@mdi/js' - -const SettingsButton = React.memo( - React.forwardRef((props, ref) => ( - - ) -} diff --git a/packages/villain-web/src/components/footer.js b/packages/villain-web/src/components/footer.js deleted file mode 100644 index 65607e63..00000000 --- a/packages/villain-web/src/components/footer.js +++ /dev/null @@ -1,19 +0,0 @@ -import React from 'react' -import Icon from '@mdi/react' -import { mdiHeart } from '@mdi/js' - -export default function Footer() { - return ( -
- Made with{' '} - {' '} - for the web, no trackers, no ads! -
- ) -} diff --git a/packages/villain-web/src/components/githubCorner.js b/packages/villain-web/src/components/githubCorner.js deleted file mode 100644 index 99d37986..00000000 --- a/packages/villain-web/src/components/githubCorner.js +++ /dev/null @@ -1,25 +0,0 @@ -import React from 'react' - -export default function GithubCorner() { - return ( - - - - ) -} diff --git a/packages/villain-web/src/components/layout.js b/packages/villain-web/src/components/layout.js deleted file mode 100644 index 0b457ea2..00000000 --- a/packages/villain-web/src/components/layout.js +++ /dev/null @@ -1,15 +0,0 @@ -import React from 'react' -import Nav from '@/components/nav' -import Footer from '@/components/footer' - -function Layout({ children }) { - return ( - -