diff --git a/.babelrc b/.babelrc deleted file mode 100644 index 375c9eca..00000000 --- a/.babelrc +++ /dev/null @@ -1,19 +0,0 @@ -{ - "presets": ["react-native"], - "plugins": [ - "transform-object-rest-spread", - "react-hot-loader/babel", [ - "module-resolver", { - "root": ["./"], - "alias": { - "@views": "./src/views", - "@pages": "./src/views/pages", - "@core": "./src/core", - "@components": "./src/views/components", - "@styles": "./src/styles", - "@layouts": "./src/views/layouts", - "@config": "./config/" - } - }] - ] -} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000..dee2d47f --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,43 @@ +name: Publish + +on: + push: + branches: + - master + +jobs: + publish: + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [macos-latest] + + steps: + - name: Checkout git repo + uses: actions/checkout@v1 + + - name: Install Node, NPM and Yarn + uses: actions/setup-node@v1 + with: + node-version: 12.13.1 + + - name: Install dependencies + run: | + yarn install + + - name: Postinstall + run: | + yarn postinstall + + - name: Publish releases + uses: samuelmeuli/action-electron-builder@v1 + with: + # GitHub token, automatically provided to the action + # (No need to define this secret in the repo settings) + github_token: ${{ secrets.github_token }} + mac_certs: ${{ secrets.mac_certs }} + mac_certs_password: ${{ secrets.mac_certs_password }} + + - name: Show release/ + run: du -sh release/ && ls -l release/ diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..b51e3eaa --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,35 @@ +name: Test + +on: push + +jobs: + release: + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [macos-latest, windows-latest, ubuntu-latest] + + steps: + - name: Check out Git repository + uses: actions/checkout@v1 + + - name: Install Node.js, NPM and Yarn + uses: actions/setup-node@v1 + with: + node-version: 12.13.1 + + - name: yarn install + run: | + yarn install --frozen-lockfile --network-timeout 300000 + + - name: yarn test + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + yarn package + yarn lint + +# Failing beacuse virtual framebuffer not installed +# yarn build-e2e +# yarn test-e2e diff --git a/.gitignore b/.gitignore index eb446135..431813d2 100644 --- a/.gitignore +++ b/.gitignore @@ -43,5 +43,17 @@ dist coverage/ ios/main.jsbundle ios/main.jsbundle.meta -orbitdb -nodejs-assets/build-native-modules-MacOS-helper-script-* \ No newline at end of file +nodejs-assets/build-native-modules-MacOS-helper-script-* +nodejs-assets/nodejs-project/bundle.js.tmp* +builds/ + +# Electron packaged +release +src/background.prod.js +src/background.prod.js.map +src/main.prod.js +src/main.prod.js.map +src/renderer.prod.js +src/renderer.prod.js.map +dist +dll diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..28c34d2c --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +14.19.0 diff --git a/.yarnrc b/.yarnrc new file mode 100644 index 00000000..02b1010b --- /dev/null +++ b/.yarnrc @@ -0,0 +1 @@ +network-timeout 500000 diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index a313e858..00000000 --- a/Gruntfile.js +++ /dev/null @@ -1,157 +0,0 @@ -'use strict' - -var serveStatic = require('serve-static') - -var mountFolder = function (dir) { - return serveStatic(require('path').resolve(dir)) -} - -var webpackDistConfig = require('./config/webpack.dist.config.js') -var webpackDevConfig = require('./config/webpack.config.js') - -module.exports = function (grunt) { - // Let *load-grunt-tasks* require everything - require('load-grunt-tasks')(grunt) - - // Read configuration from package.json - var pkgConfig = grunt.file.readJSON('package.json') - - grunt.initConfig({ - 'pkg': pkgConfig, - - 'webpack': { - options: webpackDistConfig, - dist: { - cache: false - } - }, - - 'webpack-dev-server': { - options: { - hot: true, - port: 8000, - webpack: webpackDevConfig, - publicPath: '/assets/', - contentBase: './<%= pkg.src %>/', - historyApiFallback: { - index: 'index.web.html' - } - }, - - start: { - - } - }, - - 'connect': { - options: { - port: 8000 - }, - - dist: { - options: { - keepalive: true, - middleware: function () { - return [ - mountFolder(pkgConfig.dist) - ] - } - } - } - }, - - 'open': { - options: { - delay: 500 - }, - dev: { - path: 'http://localhost:<%= connect.options.port %>/' - }, - dist: { - path: 'http://localhost:<%= connect.options.port %>/' - } - }, - - 'karma': { - unit: { - configFile: 'karma.conf.js' - } - }, - - 'copy': { - dist: { - files: [ - { - flatten: true, - src: ['<%= pkg.src %>/index.web.html'], - dest: '<%= pkg.dist %>/index.html' - }, - { - flatten: true, - src: ['<%= pkg.src %>/favicon.ico'], - dest: '<%= pkg.dist %>/favicon.ico' - } - ] - } - }, - - 'clean': { - dist: { - options: { - force: true - }, - files: [{ - dot: true, - src: [ - '<%= pkg.dist %>' - ] - }] - } - }, - - 'exec': { - launch_electron: 'NODE_ENV=development electron electron.js --inspect', - launch_electron_dist: 'NODE_ENV=production electron electron.js' - }, - - 'concurrent': { - electron: { - tasks: ['webpack-dev-server', 'exec:launch_electron'], - options: { - logConcurrentOutput: true - } - }, - electron_dist: { - task: ['webpack', 'exec:launch_electron_dist'], - options: { - logConcurrentOutput: true - } - } - } - }) - - grunt.registerTask('serve-web', function (target) { - if (target === 'dist') { - return grunt.task.run(['build', 'open:dist', 'connect:dist']) - } - - grunt.task.run([ - 'open:dev', - 'webpack-dev-server' - ]) - }) - - grunt.registerTask('serve-electron', function (target) { - if (target === 'dist') { - return grunt.task.run(['webpack', 'exec:launch_electron_dist']) - } - - grunt.task.run([ - 'concurrent:electron' - ]) - }) - - grunt.registerTask('test', ['karma']) - grunt.registerTask('build', ['clean', 'copy', 'webpack']) - grunt.registerTask('default', []) -} diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..b442934b --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 + +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/NOTICE.md b/NOTICE.md index 8329ba9f..d8503890 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -1,4 +1,4 @@ -Much of this project adapted from Richard Park - [Soundcloud Redux](https://github.com/r-park/soundcloud-redux) +Much of this repo adapted from Richard Park - [Soundcloud Redux](https://github.com/r-park/soundcloud-redux) Copyright (c) 2016 Richard Park @@ -18,4 +18,4 @@ 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. \ No newline at end of file +SOFTWARE. diff --git a/README.md b/README.md index f223ef74..71d00649 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,86 @@ + + Record Logo + + # Record App [![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat)](https://github.com/RichardLitt/standard-readme) +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fmistakia%2Frecord-app.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fmistakia%2Frecord-app?ref=badge_shield) > Desktop, mobile and web app for Record. -A proof of concept distributed social & music application (library, sharing, discovery & curation) network built entirely on [IPFS](https://github.com/ipfs/js-ipfs). User data is stored via a [scuttlebot](http://scuttlebot.io/)-like immutable log via [IPFS-Log](https://github.com/orbitdb/ipfs-log) & [OrbitDB](https://github.com/orbitdb/orbit-db). +*Note: This repo is the React & React Native UI for [Record Node](https://github.com/mistakia/record-node).* + +Record is a proof of concept immutable distributed system for audio files. Built entirely on [IPFS](https://github.com/ipfs/js-ipfs), user data is stored in a [scuttlebot](http://scuttlebot.io/)-esque immutable log via [IPFS-Log](https://github.com/orbitdb/ipfs-log) & [OrbitDB](https://github.com/orbitdb/orbit-db). Bootstraping/peer discovery is done via [bitboot](https://github.com/tintfoundation/bitboot). + +At it's core, the application intends to be a media library management & playback system akin to [beets](https://github.com/beetbox/beets) with the ability to join various sources of music like [tomahawk player](https://github.com/tomahawk-player/tomahawk). By building everything on top of IPFS, it can become a connected network of libraries, opening the door to many other possibilities (i.e. soundcloud & musicbrainz), while still being entirely distributed and thus being able to function permanently. + +## Features +- Supports: mp3, mp4, m4a/aac, flac, wav, ogg, 3gpp, aiff +- Audio file tag support via [Music Metadata](https://github.com/Borewit/music-metadata) +- Audio fingerprinting via [Chromaprint](https://acoustid.org/chromaprint) +- Listening history w/ counter and timestamps +- Tagging system for organization +- Play / Shuffle search results & organizational tags +- Import files from the local file system +- Import from various web-based sources: Youtube, Soundcloud, Bandcamp, etc + - [Record Chrome extension](https://github.com/mistakia/record-chrome-extension) +- Content deduplication +- Play queue + +**Future Features** +- Metadata cleaning / import using: discogs, musicbrainz, last.fm, allmusic, beatport, streaming services, etc +- Media server (MPD, Sonos, Plex, Kodi, Emby) +- Audio and music analysis (Aubio, Essentia) +- Audio Scrobbling (last.fm, libre.fm, listenbrainz) +- Trustless timestamping / distributed copyrighting & distribution (OpenTimestamps, Nano, etc) + +[![Record v0.0.1-alpha](resources/images/screenshot.png)](https://youtu.be/1cmxiwPBv7A) -##### Record Node -This repo is a react & react native UI for [Record Node](https://github.com/mistakia/record-node). +## More Info +- Read the [wiki](https://bafybeidk4zev2jlw2jijtdyufo3itspx45k4ynq634x4rjm6ycjfdvxfrq.ipfs.infura-ipfs.io/) for a primer. +- Check out [the roadmap](https://github.com/mistakia/record-app/projects/1) to view planned features. + +
+ Installation & Usage (Development) ## Install ``` -npm install +yarn install ``` ## Usage ### Desktop (Electron) ``` -npm run start:electron +yarn start:electron ``` ### Mobile (React Native) -First, start react native packager with: +First, install packages needed by nodejs-mobile: +``` +yarn install:nodejs-mobile +``` + +Then, start react native packager with: ``` -npm run start +yarn start:rn ``` #### iOS ``` -npm run start:ios +yarn build:ios // or `yarn build:ios:dev` +yarn start:ios // or open & build with xcode `open ios/Record.xcodeproj/` ``` #### Android ``` -npm run start:android +yarn build:android +yarn start:android ``` +
## License MIT + + +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fmistakia%2Frecord-app.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fmistakia%2Frecord-app?ref=badge_large) diff --git a/android/app/build.gradle b/android/app/build.gradle index 4515bc10..36c5f610 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -137,8 +137,10 @@ android { } dependencies { + implementation project(':nodejs-mobile-react-native') + compile project(':react-native-vector-icons') compile project(':react-native-fs') - compile project(':nodejs-mobile-react-native') + compile project(':react-native-audio-polyfill') compile fileTree(dir: "libs", include: ["*.jar"]) compile "com.android.support:appcompat-v7:23.0.1" compile "com.facebook.react:react-native:+" // From node_modules diff --git a/android/app/src/main/assets/fonts/Entypo.ttf b/android/app/src/main/assets/fonts/Entypo.ttf new file mode 100644 index 00000000..1c8f5e91 Binary files /dev/null and b/android/app/src/main/assets/fonts/Entypo.ttf differ diff --git a/android/app/src/main/assets/fonts/EvilIcons.ttf b/android/app/src/main/assets/fonts/EvilIcons.ttf new file mode 100644 index 00000000..b270f985 Binary files /dev/null and b/android/app/src/main/assets/fonts/EvilIcons.ttf differ diff --git a/android/app/src/main/assets/fonts/Feather.ttf b/android/app/src/main/assets/fonts/Feather.ttf new file mode 100755 index 00000000..244854c5 Binary files /dev/null and b/android/app/src/main/assets/fonts/Feather.ttf differ diff --git a/android/app/src/main/assets/fonts/FontAwesome.ttf b/android/app/src/main/assets/fonts/FontAwesome.ttf new file mode 100644 index 00000000..35acda2f Binary files /dev/null and b/android/app/src/main/assets/fonts/FontAwesome.ttf differ diff --git a/android/app/src/main/assets/fonts/Foundation.ttf b/android/app/src/main/assets/fonts/Foundation.ttf new file mode 100644 index 00000000..6cce217d Binary files /dev/null and b/android/app/src/main/assets/fonts/Foundation.ttf differ diff --git a/android/app/src/main/assets/fonts/Ionicons.ttf b/android/app/src/main/assets/fonts/Ionicons.ttf new file mode 100644 index 00000000..307ad889 Binary files /dev/null and b/android/app/src/main/assets/fonts/Ionicons.ttf differ diff --git a/android/app/src/main/assets/fonts/MaterialCommunityIcons.ttf b/android/app/src/main/assets/fonts/MaterialCommunityIcons.ttf new file mode 100644 index 00000000..82524a0c Binary files /dev/null and b/android/app/src/main/assets/fonts/MaterialCommunityIcons.ttf differ diff --git a/android/app/src/main/assets/fonts/MaterialIcons.ttf b/android/app/src/main/assets/fonts/MaterialIcons.ttf new file mode 100644 index 00000000..7015564a Binary files /dev/null and b/android/app/src/main/assets/fonts/MaterialIcons.ttf differ diff --git a/android/app/src/main/assets/fonts/Octicons.ttf b/android/app/src/main/assets/fonts/Octicons.ttf new file mode 100644 index 00000000..09f5a96c Binary files /dev/null and b/android/app/src/main/assets/fonts/Octicons.ttf differ diff --git a/android/app/src/main/assets/fonts/SimpleLineIcons.ttf b/android/app/src/main/assets/fonts/SimpleLineIcons.ttf new file mode 100644 index 00000000..6ecb6868 Binary files /dev/null and b/android/app/src/main/assets/fonts/SimpleLineIcons.ttf differ diff --git a/android/app/src/main/assets/fonts/Zocial.ttf b/android/app/src/main/assets/fonts/Zocial.ttf new file mode 100644 index 00000000..e4ae46c6 Binary files /dev/null and b/android/app/src/main/assets/fonts/Zocial.ttf differ diff --git a/android/app/src/main/java/com/record/MainApplication.java b/android/app/src/main/java/com/record/MainApplication.java index 1221fbc5..a3e95e3a 100644 --- a/android/app/src/main/java/com/record/MainApplication.java +++ b/android/app/src/main/java/com/record/MainApplication.java @@ -3,8 +3,10 @@ import android.app.Application; import com.facebook.react.ReactApplication; -import com.rnfs.RNFSPackage; import com.janeasystems.rn_nodejs_mobile.RNNodeJsMobilePackage; +import com.oblador.vectoricons.VectorIconsPackage; +import com.rnfs.RNFSPackage; +import io.fata.polyfill.audio.RNAudioPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; @@ -25,8 +27,10 @@ public boolean getUseDeveloperSupport() { protected List getPackages() { return Arrays.asList( new MainReactPackage(), + new RNNodeJsMobilePackage(), + new VectorIconsPackage(), new RNFSPackage(), - new RNNodeJsMobilePackage() + new RNAudioPackage() ); } diff --git a/android/settings.gradle b/android/settings.gradle index 74b8f679..9a8042fa 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -1,7 +1,11 @@ rootProject.name = 'Record' -include ':react-native-fs' -project(':react-native-fs').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fs/android') include ':nodejs-mobile-react-native' project(':nodejs-mobile-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/nodejs-mobile-react-native/android') +include ':react-native-vector-icons' +project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') +include ':react-native-fs' +project(':react-native-fs').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fs/android') +include ':react-native-audio-polyfill' +project(':react-native-audio-polyfill').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-audio-polyfill/android') include ':app' diff --git a/babel.config.js b/babel.config.js new file mode 100644 index 00000000..99e8e275 --- /dev/null +++ b/babel.config.js @@ -0,0 +1,80 @@ +/* eslint global-require: off, import/no-extraneous-dependencies: off */ + +const developmentEnvironments = ['development', 'test'] + +const developmentPlugins = [] + +const productionPlugins = [ + require('babel-plugin-dev-expression'), + + // babel-preset-react-optimize + require('@babel/plugin-transform-react-constant-elements'), + require('@babel/plugin-transform-react-inline-elements'), + require('babel-plugin-transform-react-remove-prop-types') +] + +module.exports = api => { + // See docs about api at https://babeljs.io/docs/en/config-files#apicache + + const development = api.env(developmentEnvironments) + + return { + presets: [ + // @babel/preset-env will automatically target browserslist (package.json) targets + require('@babel/preset-env'), + [require('@babel/preset-react'), { development }] + ], + plugins: [ + require('@babel/plugin-proposal-object-rest-spread'), + + // aliases + [ + require('babel-plugin-module-resolver'), { + 'root': ['./'], + 'alias': { + '@views': './src/views', + '@pages': './src/views/pages', + '@core': './src/core', + '@components': './src/views/components', + '@styles': './src/styles', + '@layouts': './src/views/layouts' + } + } + ], + + // Stage 0 + // require('@babel/plugin-proposal-function-bind'), + + // Stage 1 + // require('@babel/plugin-proposal-export-default-from'), + // require('@babel/plugin-proposal-logical-assignment-operators'), + // [require('@babel/plugin-proposal-optional-chaining'), { loose: false }], + /* [ + * require('@babel/plugin-proposal-pipeline-operator'), + * { proposal: 'minimal' } + * ], */ + /* [ + * require('@babel/plugin-proposal-nullish-coalescing-operator'), + * { loose: false } + * ], */ + // require('@babel/plugin-proposal-do-expressions'), + + // Stage 2 + // [require('@babel/plugin-proposal-decorators'), { legacy: true }], + // require('@babel/plugin-proposal-function-sent'), + // require('@babel/plugin-proposal-export-namespace-from'), + // require('@babel/plugin-proposal-numeric-separator'), + // require('@babel/plugin-proposal-throw-expressions'), + + // Stage 3 + // require('@babel/plugin-syntax-dynamic-import'), + // require('@babel/plugin-syntax-import-meta'), + [require('@babel/plugin-proposal-private-property-in-object'), { loose: true }], + [require('@babel/plugin-proposal-private-methods'), { loose: true }], + [require('@babel/plugin-proposal-class-properties'), { loose: true }], + // require('@babel/plugin-proposal-json-strings'), + + ...(development ? developmentPlugins : productionPlugins) + ] + } +} diff --git a/config/project.config.js b/config/project.config.js deleted file mode 100644 index f638a272..00000000 --- a/config/project.config.js +++ /dev/null @@ -1,24 +0,0 @@ -const argv = require('yargs').argv -const path = require('path') - -const config = { - env: process.env.NODE_ENV || 'development', -} - -// ------------------------------------ -// Environment -// ------------------------------------ -// N.B.: globals added here must _also_ be added to .eslintrc -config.globals = { - 'process.env' : { - 'NODE_ENV' : JSON.stringify(config.env) - }, - 'NODE_ENV' : config.env, - '__DEV__' : config.env === 'development', - '__PROD__' : config.env === 'production', - '__TEST__' : config.env === 'test', - '__COVERAGE__' : !argv.watch && config.env === 'test', - '__BASENAME__' : JSON.stringify(process.env.BASENAME || '') -} - -module.exports = config diff --git a/config/webpack.config.js b/config/webpack.config.js deleted file mode 100644 index 023878e0..00000000 --- a/config/webpack.config.js +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Webpack development server configuration - */ - -'use strict'; -const path = require('path') -const nib = require('nib') -const webpack = require('webpack') -const project = require('./project.config') - -module.exports = { - output: { - filename: 'main.js', - publicPath: '/assets/' - }, - cache: false, - devtool: false, - entry: [ - 'react-hot-loader/patch', - 'webpack-dev-server/client?http://localhost:8000', - 'webpack/hot/only-dev-server', - 'whatwg-fetch', - 'babel-polyfill', - './src/index.js' - ], - stats: { - colors: true, - reasons: true - }, - plugins: [ - new webpack.DefinePlugin(project.globals), - new webpack.LoaderOptionsPlugin({ debug: true }), - new webpack.HotModuleReplacementPlugin() - ], - node: { - fs: 'empty', - net: 'empty', - tls: 'empty' - }, - module: { - rules: [{ - test: /\.js$/, - exclude: /node_modules/, - loader: 'babel-loader' - }, { - test: /\.(styl|css)$/, - use: [{ - loader: 'style-loader' - }, { - loader: 'css-loader', - }, { - loader: 'stylus-loader', - options: { - use: [nib()], - import: [ - '~nib/lib/nib/index.styl', - path.resolve(__dirname, '../src/styles/variables.styl') - ] - } - }] - }, { - test: /\.(png|jpg)$/, - loader: 'url-loader', - options: { - limit: 8192 - } - }] - } -}; diff --git a/config/webpack.dist.config.js b/config/webpack.dist.config.js deleted file mode 100644 index 24bd2fad..00000000 --- a/config/webpack.dist.config.js +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Webpack distribution configuration - * - * This file is set up for serving the distribution version. It will be compiled to dist/ by default - */ - -'use strict'; - -const webpack = require('webpack') -const project = require('./project.config') -const nib = require('nib') -const path = require('path') - -module.exports = { - output: { - publicPath: '/assets/', - path: path.resolve(__dirname, '../dist/assets/'), - filename: 'main.js' - }, - devtool: false, - entry: [ - 'whatwg-fetch', - 'babel-polyfill', - './src/index.js' - ], - stats: { - colors: true, - reasons: false - }, - plugins: [ - new webpack.DefinePlugin(project.globals), - new webpack.optimize.AggressiveMergingPlugin() - ], - module: { - loaders: [{ - test: /\.js$/, - exclude: /node_modules/, - loader: 'babel-loader' - }, { - test: /\.(styl|css)$/, - use: [{ - loader: 'style-loader' - }, { - loader: 'css-loader', - }, { - loader: 'stylus-loader', - options: { - use: [nib()], - import: [ - '~nib/lib/nib/index.styl', - path.resolve(__dirname, '../src/styles/variables.styl') - ] - } - }] - }, { - test: /\.(png|jpg)$/, - loader: 'url-loader?limit=8192' - }] - } -} diff --git a/configs/webpack.config.background.prod.babel.js b/configs/webpack.config.background.prod.babel.js new file mode 100644 index 00000000..baa9d6e4 --- /dev/null +++ b/configs/webpack.config.background.prod.babel.js @@ -0,0 +1,78 @@ +/** + * Webpack config for production electron main process + */ + +import fs from 'fs' +import path from 'path' +import webpack from 'webpack' +import merge from 'webpack-merge' +import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer' +import baseConfig from './webpack.config.base' +import CheckNodeEnv from '../internals/scripts/CheckNodeEnv' +import DeleteSourceMaps from '../internals/scripts/DeleteSourceMaps' + +CheckNodeEnv('production') +DeleteSourceMaps() + +export default merge.smart(baseConfig, { + devtool: 'source-map', + + mode: 'production', + + target: 'node', + + entry: [ + 'core-js', + 'regenerator-runtime/runtime', + './src/background.dev.js' + ], + + output: { + path: path.join(__dirname, '..'), + filename: './src/background.prod.js' + }, + + module: { + rules: [ + { + test: /\.node$/, + use: 'node-loader' + } + ] + }, + + // https://github.com/webpack/webpack/issues/7953 + /* resolve: { + * mainFields: ['module', 'main'] + * }, + */ + + optimization: { + minimize: false + }, + + plugins: [ + new BundleAnalyzerPlugin({ + analyzerMode: + process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled', + openAnalyzer: process.env.OPEN_ANALYZER === 'true' + }), + + new webpack.EnvironmentPlugin({ + NODE_ENV: 'production', + DEBUG_PROD: false, + START_MINIMIZED: false, + E2E_BUILD: false + }) + ], + + /** + * Disables webpack processing of __dirname and __filename. + * If you run the bundle in node.js it falls back to these values of node.js. + * https://github.com/webpack/webpack/issues/2010 + */ + node: { + __dirname: false, + __filename: false + } +}) diff --git a/configs/webpack.config.base.js b/configs/webpack.config.base.js new file mode 100644 index 00000000..571f9515 --- /dev/null +++ b/configs/webpack.config.base.js @@ -0,0 +1,89 @@ +/** + * Base webpack config used across other specific configs + */ + +import path from 'path' +import webpack from 'webpack' +import nib from 'nib' +import { dependencies as externals } from '../src/package.json' + +export default { + externals: [...Object.keys(externals || {}), 'vertx', 'electron', 'mssql', 'mssql/lib/base', 'mssql/package.json', 'mysql', 'mysql2', 'oracledb', 'pg', 'pg-query-stream', 'tedious'], + + module: { + rules: [ + { + test: /\.m?js$/, + use: { + loader: 'babel-loader', + options: { + cacheDirectory: true + } + } + }, { + test: /\.css$/, + + use: [{ + loader: 'style-loader' + }, { + loader: 'css-loader' + }] + }, { + test: /\.styl$/, + use: [{ + loader: 'style-loader' + }, { + loader: 'css-loader', + options: { + importLoaders: 1 + } + }, { + loader: 'stylus-loader', + options: { + stylusOptions: { + use: [nib()], + import: [ + 'nib', + path.resolve(__dirname, '../src/styles/variables.styl') + ], + includeCSS: true + } + } + }] + }, { + test: /\.(png|jpg)$/, + type: 'asset' + }, { // https://github.com/ashtuchkin/iconv-lite/issues/204#issuecomment-432048618 + test: /node_modules[\/\\](iconv-lite)[\/\\].+/, + resolve: { + aliasFields: ['main'] + } + } + ] + }, + + optimization: { + moduleIds: 'named' + }, + + output: { + path: path.join(__dirname, '..', 'src'), + // https://github.com/webpack/webpack/issues/1114 + libraryTarget: 'commonjs2' + }, + + /** + * Determine the array of extensions that should be used to resolve modules. + */ + resolve: { + mainFields: ['main', 'module'], + extensions: ['.js', '.json'], + modules: [path.join(__dirname, '..', 'src'), 'node_modules'] + }, + + plugins: [ + new webpack.EnvironmentPlugin({ + NODE_ENV: 'production' + }) + ] +} diff --git a/configs/webpack.config.main.prod.babel.js b/configs/webpack.config.main.prod.babel.js new file mode 100644 index 00000000..3025f488 --- /dev/null +++ b/configs/webpack.config.main.prod.babel.js @@ -0,0 +1,74 @@ +/** + * Webpack config for production electron main process + */ + +import path from 'path' +import webpack from 'webpack' +import merge from 'webpack-merge' +import baseConfig from './webpack.config.base' +import TerserPlugin from 'terser-webpack-plugin' +import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer' +import CheckNodeEnv from '../internals/scripts/CheckNodeEnv' +import DeleteSourceMaps from '../internals/scripts/DeleteSourceMaps' + +CheckNodeEnv('production') +DeleteSourceMaps() + +export default merge.smart(baseConfig, { + devtool: 'source-map', + + mode: 'production', + + target: 'electron-main', + + entry: './src/main.dev.js', + + output: { + path: path.join(__dirname, '..'), + filename: './src/main.prod.js' + }, + + optimization: { + minimizer: process.env.E2E_BUILD + ? [] + : [ + new TerserPlugin({ + parallel: true + }) + ] + }, + + plugins: [ + new BundleAnalyzerPlugin({ + analyzerMode: + process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled', + openAnalyzer: process.env.OPEN_ANALYZER === 'true' + }), + + /** + * Create global constants which can be configured at compile time. + * + * Useful for allowing different behaviour between development builds and + * release builds + * + * NODE_ENV should be production so that modules do not perform certain + * development checks + */ + new webpack.EnvironmentPlugin({ + NODE_ENV: 'production', + DEBUG_PROD: false, + START_MINIMIZED: false, + E2E_BUILD: false + }) + ], + + /** + * Disables webpack processing of __dirname and __filename. + * If you run the bundle in node.js it falls back to these values of node.js. + * https://github.com/webpack/webpack/issues/2010 + */ + node: { + __dirname: false, + __filename: false + } +}) diff --git a/configs/webpack.config.renderer.dev.babel.js b/configs/webpack.config.renderer.dev.babel.js new file mode 100644 index 00000000..05275ec3 --- /dev/null +++ b/configs/webpack.config.renderer.dev.babel.js @@ -0,0 +1,138 @@ +/** + * Build config for development electron renderer process that uses + * Hot-Module-Replacement + * + * https://webpack.js.org/concepts/hot-module-replacement/ + */ + +import path from 'path' +import fs from 'fs' +import webpack from 'webpack' +import chalk from 'chalk' +import merge from 'webpack-merge' +import { spawn, execSync } from 'child_process' +import baseConfig from './webpack.config.base' +import CheckNodeEnv from '../internals/scripts/CheckNodeEnv' +import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin' + +// When an ESLint server is running, we can't set the NODE_ENV so we'll check if it's +// at the dev webpack config is not accidentally run in a production environment +if (process.env.NODE_ENV === 'production') { + CheckNodeEnv('development') +} + +const port = process.env.PORT || 1212 +const publicPath = `http://localhost:${port}/dist` +const dll = path.join(__dirname, '..', 'dll') +const manifest = path.resolve(dll, 'renderer.json') +const requiredByDLLConfig = module.parent.filename.includes( + 'webpack.config.renderer.dev.dll' +) + +/** + * Warn if the DLL is not built + */ +if (!requiredByDLLConfig && !(fs.existsSync(dll) && fs.existsSync(manifest))) { + console.log( + chalk.black.bgYellow.bold( + 'The DLL files are missing. Sit back while we build them for you with "yarn build:dll"' + ) + ) + execSync('yarn build:dll') +} + +export default merge.smart(baseConfig, { + devtool: 'inline-source-map', + + mode: 'development', + + target: 'electron-renderer', + + entry: [ + 'core-js', + 'regenerator-runtime/runtime', + `webpack-dev-server/client?http://localhost:${port}/`, + 'webpack/hot/only-dev-server', + require.resolve('../src/index.js') + ], + + output: { + publicPath: `http://localhost:${port}/dist/`, + filename: 'renderer.dev.js' + }, + + plugins: [ + requiredByDLLConfig + ? null + : new webpack.DllReferencePlugin({ + context: path.join(__dirname, '..', 'dll'), + manifest: require(manifest), + sourceType: 'var' + }), + + new webpack.NoEmitOnErrorsPlugin(), + + /** + * Create global constants which can be configured at compile time. + * + * Useful for allowing different behaviour between development builds and + * release builds + * + * NODE_ENV should be production so that modules do not perform certain + * development checks + * + * By default, use 'development' as NODE_ENV. This can be overriden with + * 'staging', for example, by changing the ENV variables in the npm scripts + */ + new webpack.EnvironmentPlugin({ + NODE_ENV: 'development' + }), + + new webpack.LoaderOptionsPlugin({ + debug: true + }), + + new ReactRefreshWebpackPlugin() + ], + + node: { + __dirname: false, + __filename: false + }, + + infrastructureLogging: { + // TODO + }, + + watchOptions: { + aggregateTimeout: 300, + ignored: /node_modules/, + poll: 100 + }, + + devServer: { + port, + compress: true, + hot: true, + headers: { 'Access-Control-Allow-Origin': '*' }, + historyApiFallback: { + verbose: true, + disableDotRule: false + }, + static: { + publicPath: '/' + }, + onBeforeSetupMiddleware() { + if (process.env.START_HOT) { + console.log('Starting Main Process...'); + spawn('npm', ['run', 'start:electron:main'], { + shell: true, + env: process.env, + stdio: 'inherit', + }) + .on('close', (code) => process.exit(code)) + .on('error', (spawnError) => console.error(spawnError)); + } + } + } +}) diff --git a/configs/webpack.config.renderer.dev.dll.babel.js b/configs/webpack.config.renderer.dev.dll.babel.js new file mode 100644 index 00000000..a67178d8 --- /dev/null +++ b/configs/webpack.config.renderer.dev.dll.babel.js @@ -0,0 +1,74 @@ +/** + * Builds the DLL for development electron renderer process + */ + +import webpack from 'webpack' +import path from 'path' +import merge from 'webpack-merge' +import baseConfig from './webpack.config.base' +import { dependencies } from '../package.json' +import CheckNodeEnv from '../internals/scripts/CheckNodeEnv' + +CheckNodeEnv('development') + +const dist = path.join(__dirname, '..', 'dll') + +export default merge.smart(baseConfig, { + context: path.join(__dirname, '..'), + + devtool: 'eval', + + mode: 'development', + + target: 'electron-renderer', + + /** + * Use `module` from `webpack.config.renderer.dev.js` + */ + module: require('./webpack.config.renderer.dev.babel').default.module, + + externals: { + knex: 'commonjs knex' + }, + + entry: { + renderer: Object.keys(dependencies || {}) + }, + + output: { + library: 'renderer', + path: dist, + filename: '[name].dev.dll.js', + libraryTarget: 'var' + }, + + plugins: [ + new webpack.DllPlugin({ + path: path.join(dist, '[name].json'), + name: '[name]' + }), + + /** + * Create global constants which can be configured at compile time. + * + * Useful for allowing different behaviour between development builds and + * release builds + * + * NODE_ENV should be production so that modules do not perform certain + * development checks + */ + new webpack.EnvironmentPlugin({ + NODE_ENV: 'development' + }), + + new webpack.LoaderOptionsPlugin({ + debug: true, + options: { + context: path.join(__dirname, '..', 'src'), + output: { + path: path.join(__dirname, '..', 'dll') + } + } + }) + ] +}) diff --git a/configs/webpack.config.renderer.prod.babel.js b/configs/webpack.config.renderer.prod.babel.js new file mode 100644 index 00000000..11041637 --- /dev/null +++ b/configs/webpack.config.renderer.prod.babel.js @@ -0,0 +1,107 @@ +/** + * Build config for electron renderer process + */ + +import path from 'path' +import webpack from 'webpack' +import MiniCssExtractPlugin from 'mini-css-extract-plugin' +import OptimizeCSSAssetsPlugin from 'optimize-css-assets-webpack-plugin' +import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer' +import nib from 'nib' +import merge from 'webpack-merge' +import TerserPlugin from 'terser-webpack-plugin' +import baseConfig from './webpack.config.base' +import CheckNodeEnv from '../internals/scripts/CheckNodeEnv' +import DeleteSourceMaps from '../internals/scripts/DeleteSourceMaps' + +CheckNodeEnv('production') +DeleteSourceMaps() + +export default merge.smart(baseConfig, { + devtool: 'source-map', + + mode: 'production', + + target: 'electron-preload', + + entry: [ + 'core-js', + 'regenerator-runtime/runtime', + path.join(__dirname, '..', 'src/index.js') + ], + + output: { + path: path.join(__dirname, '..', 'src/dist'), + publicPath: './dist/', + filename: 'renderer.prod.js' + }, + + module: { + rules: [{ + test: /\.css$/, + use: [{ + loader: 'style-loader' + }, { + loader: 'css-loader', + }] + }, { + test: /\.styl$/, + use: [{ + loader: 'style-loader' + }, { + loader: 'css-loader', + }, { + loader: 'stylus-loader', + options: { + stylusOptions: { + use: [nib()], + import: [ + '~nib/lib/nib/index.styl', + path.resolve(__dirname, '../src/styles/variables.styl') + ] + } + } + }] + }, { + test: /\.(png|jpg)$/, + type: 'assets' + }] + }, + + optimization: { + minimizer: process.env.E2E_BUILD + ? [] + : [ + new TerserPlugin({ + parallel: true + }) + ] + }, + + plugins: [ + /** + * Create global constants which can be configured at compile time. + * + * Useful for allowing different behaviour between development builds and + * release builds + * + * NODE_ENV should be production so that modules do not perform certain + * development checks + */ + new webpack.EnvironmentPlugin({ + NODE_ENV: 'production', + DEBUG_PROD: false, + E2E_BUILD: false + }), + + /* new MiniCssExtractPlugin({ + * filename: 'style.css' + * }), + */ + new BundleAnalyzerPlugin({ + analyzerMode: + process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled', + openAnalyzer: process.env.OPEN_ANALYZER === 'true' + }) + ] +}) diff --git a/electron.js b/electron.js deleted file mode 100644 index 4598896f..00000000 --- a/electron.js +++ /dev/null @@ -1,176 +0,0 @@ -'use strict' - -const { default: installExtension, REDUX_DEVTOOLS } = require('electron-devtools-installer'); -const electron = require('electron') -const Logger = require('logplease') -const path = require('path') -const os = require('os') -const fs = require('fs') -const RecordNode = require('record-node') -const debug = require('debug') -const OrbitDB = require('orbit-db') -const IPFS = require('ipfs') - -const config = require('./config/project.config') - -debug.enable('repo,jsipfs:*,record:*,libp2p:*,bitswap:*') -Logger.setLogLevel(Logger.LogLevels.DEBUG) -let logger = Logger.create('record-electron', { color: Logger.Colors.Yellow }) - -process.on('uncaughtException', (err) => { - console.log(err) - process.exit() -}) - -// Module to control application life. -const app = electron.app - -// const userDataPath = app.getPath('userData') -// logger.info(`User Data: ${userDataPath}`) -const recorddir = path.resolve(os.homedir(), './.record') -if (!fs.existsSync(recorddir)) { fs.mkdirSync(recorddir) } - -// Module to create native browser window. -const BrowserWindow = electron.BrowserWindow - -const logToRenderer = (source, level, text) => { - if (mainWindow) - mainWindow.webContents.send('log', source, level, text) -} - -// Keep a global reference of the window object, if you don't, the window will -// be closed automatically when the JavaScript object is garbage collected. -let mainWindow - -function createWindow () { - // Create the browser window. - mainWindow = new BrowserWindow({ - minWidth: 600, - minHeight: 475, - maxWidth: 1000, - maxHeight: 800, - show: false - }) - - const indexUrl = config.globals.__DEV__ - ? 'http://localhost:8000/' - : 'file://' + __dirname + '/index.desktop.html' - - mainWindow.loadURL(indexUrl) - - // Open the DevTools. - mainWindow.webContents.openDevTools() - - // Emitted when the window is closed. - mainWindow.on('closed', () => { - // Dereference the window object, usually you would store windows - // in an array if your app supports multi windows, this is the time - // when you should delete the corresponding element. - mainWindow = null - - }) - - mainWindow.once('ready-to-show', () => { - mainWindow.show() - }) -} - -function clearData () { - const ses = mainWindow.webContents.session - ses.clearStorageData((err) => { - if (err) logger.error(err) - }) -} - -// This method will be called when Electron has finished -// initialization and is ready to create browser windows. -app.on('ready', () => { - installExtension(REDUX_DEVTOOLS.id) - .then((name) => logger.info(`Added Extension: ${name}`)) - .catch((err) => logger.error('An error occurred: ', err)); - - createWindow() - - try { - const ipfsConfig = { - init: { - bits: 1024 - }, - repo: path.resolve(recorddir, './ipfs'), - EXPERIMENTAL: { - dht: false, // TODO: BRICKS COMPUTER - relay: { - enabled: true, - hop: { - enabled: false, // TODO: CPU hungry on mobile - active: false - } - }, - pubsub: true - }, - config: { - Bootstrap: [], - Addresses: { - Swarm: [ - '/ip4/159.203.117.254/tcp/9090/ws/p2p-websocket-star' - ] - } - } - } - const ipfs = new IPFS(ipfsConfig) - ipfs.on('ready', async () => { - - mainWindow.webContents.send('ready') - mainWindow.webContents.on('did-finish-load', () => { - // TODO: check if ipfs status first - mainWindow.webContents.send('ready') - }) - - const orbitAddressPath = path.resolve(recorddir, 'address.txt') - const orbitAddress = fs.existsSync(orbitAddressPath) ? - fs.readFileSync(orbitAddressPath, 'utf8') : undefined - - logger.info(`Orbit Address: ${orbitAddress}`) - - const opts = { - orbitAddress: orbitAddress, - orbitPath: path.resolve(recorddir, './orbitdb'), - api: true - } - - const rn = new RecordNode(ipfs, OrbitDB, opts) - try { - await rn.loadLog() - fs.writeFileSync(orbitAddressPath, rn._log.address) - - rn.syncContacts() - } catch (e) { - console.log(e) - } - }) - } catch (err) { - logger.error(`Error starting node: ${err.toString()}`) - console.log(err) - } - - // Pass log messages to the renderer process - Logger.events.on('data', logToRenderer) - -}) - -// Quit when all windows are closed. -app.on('window-all-closed', function () { - // On OS X it is common for applications and their menu bar - // to stay active until the user quits explicitly with Cmd + Q - if (process.platform !== 'darwin') { - app.quit() - } -}) - -app.on('activate', function () { - // On OS X it's common to re-create a window in the app when the - // dock icon is clicked and there are no other windows open. - if (mainWindow === null) { - createWindow() - } -}) diff --git a/index.desktop.html b/index.desktop.html index 9e262f5a..a88642a5 100644 --- a/index.desktop.html +++ b/index.desktop.html @@ -1,12 +1,68 @@ - - - Record - - -
- - - + + + Record + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + diff --git a/index.web.html b/index.web.html index c5687556..937f6e79 100644 --- a/index.web.html +++ b/index.web.html @@ -1,21 +1,77 @@ - - - Record - - - - - - -
- - - - + + + Record + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + diff --git a/internals/scripts/BabelRegister.js b/internals/scripts/BabelRegister.js new file mode 100644 index 00000000..810a8e66 --- /dev/null +++ b/internals/scripts/BabelRegister.js @@ -0,0 +1,6 @@ +const path = require('path') + +require('@babel/register')({ + extensions: ['.es6', '.es', '.js'], + cwd: path.join(__dirname, '..', '..') +}) diff --git a/internals/scripts/CheckNativeDep.js b/internals/scripts/CheckNativeDep.js new file mode 100644 index 00000000..d2d41a76 --- /dev/null +++ b/internals/scripts/CheckNativeDep.js @@ -0,0 +1,49 @@ +import fs from 'fs' +import chalk from 'chalk' +import { execSync } from 'child_process' +import { dependencies } from '../../package.json' + +if (dependencies) { + const dependenciesKeys = Object.keys(dependencies) + const nativeDeps = fs + .readdirSync('node_modules') + .filter(folder => fs.existsSync(`node_modules/${folder}/binding.gyp`)) + try { + // Find the reason for why the dependency is installed. If it is installed + // because of a devDependency then that is okay. Warn when it is installed + // because of a dependency + const { dependencies: dependenciesObject } = JSON.parse( + execSync(`npm ls ${nativeDeps.join(' ')} --json`).toString() + ) + const rootDependencies = Object.keys(dependenciesObject) + const filteredRootDependencies = rootDependencies.filter(rootDependency => + dependenciesKeys.includes(rootDependency) + ) + if (filteredRootDependencies.length > 0) { + const plural = filteredRootDependencies.length > 1 + console.log(` + ${chalk.whiteBright.bgYellow.bold( + 'Webpack does not work with native dependencies.' + )} +${chalk.bold(filteredRootDependencies.join(', '))} ${ + plural ? 'are native dependencies' : 'is a native dependency' + } and should be installed inside of the "./src" folder. + First uninstall the packages from "./package.json": +${chalk.whiteBright.bgGreen.bold('yarn remove your-package')} + ${chalk.bold( + 'Then, instead of installing the package to the root "./package.json":' + )} +${chalk.whiteBright.bgRed.bold('yarn add your-package')} + ${chalk.bold('Install the package to "./src/package.json"')} +${chalk.whiteBright.bgGreen.bold('cd ./src && yarn add your-package')} + Read more about native dependencies at: +${chalk.bold( + 'https://github.com/electron-react-boilerplate/electron-react-boilerplate/wiki/Module-Structure----Two-package.json-Structure' +)} + `) + process.exit(1) + } + } catch (e) { + console.log('Native dependencies could not be checked') + } +} diff --git a/internals/scripts/CheckNodeEnv.js b/internals/scripts/CheckNodeEnv.js new file mode 100644 index 00000000..c5662324 --- /dev/null +++ b/internals/scripts/CheckNodeEnv.js @@ -0,0 +1,16 @@ +import chalk from 'chalk' + +export default function CheckNodeEnv(expectedEnv) { + if (!expectedEnv) { + throw new Error('"expectedEnv" not set') + } + + if (process.env.NODE_ENV !== expectedEnv) { + console.log( + chalk.whiteBright.bgRed.bold( + `"process.env.NODE_ENV" must be "${expectedEnv}" to use this webpack config` + ) + ); + process.exit(2) + } +} diff --git a/internals/scripts/DeleteSourceMaps.js b/internals/scripts/DeleteSourceMaps.js new file mode 100644 index 00000000..25172015 --- /dev/null +++ b/internals/scripts/DeleteSourceMaps.js @@ -0,0 +1,7 @@ +import path from 'path' +import rimraf from 'rimraf' + +export default function deleteSourceMaps() { + rimraf.sync(path.join(__dirname, '../../dist/*.js.map')) + rimraf.sync(path.join(__dirname, '../../src/*.js.map')) +} diff --git a/internals/scripts/ElectronRebuild.js b/internals/scripts/ElectronRebuild.js new file mode 100644 index 00000000..347f01ae --- /dev/null +++ b/internals/scripts/ElectronRebuild.js @@ -0,0 +1,22 @@ +import path from 'path' +import { execSync } from 'child_process' +import fs from 'fs' +import { dependencies } from '../../src/package.json' + +const nodeModulesPath = path.join(__dirname, '..', '..', 'src', 'node_modules') + +if ( + Object.keys(dependencies || {}).length > 0 && + fs.existsSync(nodeModulesPath) +) { + const electronRebuildCmd = + '../node_modules/.bin/electron-rebuild --parallel --force --types prod,dev,optional --module-dir .' + const cmd = + process.platform === 'win32' + ? electronRebuildCmd.replace(/\//g, '\\') + : electronRebuildCmd; + execSync(cmd, { + cwd: path.join(__dirname, '..', '..', 'src'), + stdio: 'inherit' + }) +} diff --git a/ios/Record.xcodeproj/project.pbxproj b/ios/Record.xcodeproj/project.pbxproj index f86567b5..1d7a6cd5 100644 --- a/ios/Record.xcodeproj/project.pbxproj +++ b/ios/Record.xcodeproj/project.pbxproj @@ -36,14 +36,28 @@ 2D02E4C81E0B4AEC006451C7 /* libRCTWebSocket-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */; }; 2D16E6881FA4F8E400B85C8A /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D16E6891FA4F8E400B85C8A /* libReact.a */; }; 2DCD954D1E0B4F2C00145EB5 /* RecordTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* RecordTests.m */; }; - 39B3D37ADFD7489BAD6EB717 /* libRNNodeJsMobile.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6162BD573EF84A479FC3A188 /* libRNNodeJsMobile.a */; }; + 4F571A52E7044A9A9D54A89F /* libRNNodeJsMobile.a in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E1CF91499D414FA01C8943 /* libRNNodeJsMobile.a */; }; + 596E9FB3F4034A47B4D22B94 /* Feather.ttf in Resources */ = {isa = PBXBuildFile; fileRef = F32E636344F7452EBB1C45EA /* Feather.ttf */; }; + 5A83EA2EF4B3450EA67DD421 /* Octicons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 8982F42AFA1F49F2BDDEB2C8 /* Octicons.ttf */; }; 5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */; }; + 6DADDAF1C3C9495B81260959 /* EvilIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 9095C0A66BE149199FE16A5F /* EvilIcons.ttf */; }; + 6E5BBFC2BC0D4F93BE8C3929 /* Foundation.ttf in Resources */ = {isa = PBXBuildFile; fileRef = F32FD65A30134A9F8B647D21 /* Foundation.ttf */; }; + 80B1704D2DB94505905514BA /* libRNVectorIcons.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 9BE87C948A6D477BAC13D99F /* libRNVectorIcons.a */; }; 832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 832341B51AAA6A8300B99B32 /* libRCTText.a */; }; 8CC8B3545F71477CA83015C8 /* NodeMobile.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 124EC05E131A44D4850F2BF6 /* NodeMobile.framework */; }; + A1AAF3BE8C944B9EB66BAB48 /* Ionicons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 18C93A84BE1B497D9F5BFF36 /* Ionicons.ttf */; }; ADBDB9381DFEBF1600ED6528 /* libRCTBlob.a in Frameworks */ = {isa = PBXBuildFile; fileRef = ADBDB9271DFEBF0700ED6528 /* libRCTBlob.a */; }; B522B19439D1447FB7565D2C /* nodejs-project in Resources */ = {isa = PBXBuildFile; fileRef = 1D2494BC39C34388B2973202 /* nodejs-project */; }; + BCF729E50F004A2D9E6FE886 /* SimpleLineIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = A0B6CD4FF46E48A69FCD0741 /* SimpleLineIcons.ttf */; }; + C4A37B44BF874CD0965FCF8E /* Entypo.ttf in Resources */ = {isa = PBXBuildFile; fileRef = C92111DD8DBD498F94C72687 /* Entypo.ttf */; }; + D3710D6416544243A3D3E4C3 /* Zocial.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 9FF89D62D2984EEC9B1D53D9 /* Zocial.ttf */; }; DA38831A77DA42318634B0B8 /* libRNFS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00222BC525FD4CD5ADC1609A /* libRNFS.a */; }; + EDA20E8287B44B5D92DFF238 /* FontAwesome.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 23F8EDCB2294447EA6D87E13 /* FontAwesome.ttf */; }; + EEADBB9221194EA0ADC9876D /* MaterialCommunityIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 80C71F656A4B438C9B1F8B2D /* MaterialCommunityIcons.ttf */; }; + F29E7278F4D24B5BA2C2DDFC /* MaterialIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 8D70DD7BE74A46E8B20B7DE5 /* MaterialIcons.ttf */; }; + FA0A930648274178AFB1E8B1 /* libRNAudio.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BEA1E45F7AFC4BCDAA697D3F /* libRNAudio.a */; }; FFC710E8206329B7003524B5 /* main.jsbundle in Resources */ = {isa = PBXBuildFile; fileRef = 008F07F21AC5B25A0029DE68 /* main.jsbundle */; }; + FFCCADC72295D92100843948 /* JavaScriptCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FFCCAD942295D92100843948 /* JavaScriptCore.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -215,20 +229,6 @@ remoteGlobalIDString = 3D3CD9321DE5FBEE00167DC4; remoteInfo = "cxxreact-tvOS"; }; - 3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 3D3CD90B1DE5FBD600167DC4; - remoteInfo = jschelpers; - }; - 3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 3D3CD9181DE5FBD800167DC4; - remoteInfo = "jschelpers-tvOS"; - }; 5E9157321DD0AC6500FF2AA8 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */; @@ -264,9 +264,51 @@ remoteGlobalIDString = 358F4ED71D1E81A9004DF814; remoteInfo = RCTBlob; }; - FF757C3420B36F630055D174 /* PBXContainerItemProxy */ = { + FF1F22B820ED49E300830BBF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 437C5D64C0F34573B899A66C /* RNVectorIcons.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 5DBEB1501B18CEA900B34395; + remoteInfo = RNVectorIcons; + }; + FFBB06F820D5ECA9006901B0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97457E848AD54409873D3FD4 /* RNAudio.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 19825A1E1BD4A89800EE0337; + remoteInfo = RNAudio; + }; + FFCCADBA2295D92100843948 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = EDEBC6D6214B3E7000DD5AC8; + remoteInfo = jsi; + }; + FFCCADBC2295D92100843948 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = EDEBC73B214B45A300DD5AC8; + remoteInfo = jsiexecutor; + }; + FFCCADBE2295D92100843948 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = ED296FB6214C9A0900B7C4FE; + remoteInfo = "jsi-tvOS"; + }; + FFCCADC02295D92100843948 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = ED296FEE214C9CF800B7C4FE; + remoteInfo = "jsiexecutor-tvOS"; + }; + FFCCAE122295F4B400843948 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 606EB20FA9A940B0B4A24B63 /* RNNodeJsMobile.xcodeproj */; + containerPortal = 7AA94215A3EE4C35AC5F6CC1 /* RNNodeJsMobile.xcodeproj */; proxyType = 2; remoteGlobalIDString = 134814201AA4EA6300B7C361; remoteInfo = RNNodeJsMobile; @@ -327,20 +369,6 @@ remoteGlobalIDString = 3D383D621EBD27B9005632C8; remoteInfo = "double-conversion-tvOS"; }; - FFE21ABB205D8877004F7897 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 9936F3131F5F2E4B0010BF04; - remoteInfo = privatedata; - }; - FFE21ABD205D8877004F7897 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 9936F32F1F5F2E5B0010BF04; - remoteInfo = "privatedata-tvOS"; - }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -379,18 +407,34 @@ 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Record/Info.plist; sourceTree = ""; }; 13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = Record/main.m; sourceTree = ""; }; 146833FF1AC3E56700842450 /* React.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = React.xcodeproj; path = "../node_modules/react-native/React/React.xcodeproj"; sourceTree = ""; }; + 18C93A84BE1B497D9F5BFF36 /* Ionicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Ionicons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Ionicons.ttf"; sourceTree = ""; }; 1D2494BC39C34388B2973202 /* nodejs-project */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = "nodejs-project"; path = "../nodejs-assets/nodejs-project"; sourceTree = ""; }; + 23F8EDCB2294447EA6D87E13 /* FontAwesome.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome.ttf"; sourceTree = ""; }; 2D02E47B1E0B4A5D006451C7 /* Record-tvOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Record-tvOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 2D02E4901E0B4A5D006451C7 /* Record-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Record-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; 2D16E6891FA4F8E400B85C8A /* libReact.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; path = libReact.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 437C5D64C0F34573B899A66C /* RNVectorIcons.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = RNVectorIcons.xcodeproj; path = "../node_modules/react-native-vector-icons/RNVectorIcons.xcodeproj"; sourceTree = ""; }; 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTAnimation.xcodeproj; path = "../node_modules/react-native/Libraries/NativeAnimation/RCTAnimation.xcodeproj"; sourceTree = ""; }; - 606EB20FA9A940B0B4A24B63 /* RNNodeJsMobile.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = RNNodeJsMobile.xcodeproj; path = "../node_modules/nodejs-mobile-react-native/ios/RNNodeJsMobile.xcodeproj"; sourceTree = ""; }; 615FC19D9B314671A382CD8A /* RNFS.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = RNFS.xcodeproj; path = "../node_modules/react-native-fs/RNFS.xcodeproj"; sourceTree = ""; }; - 6162BD573EF84A479FC3A188 /* libRNNodeJsMobile.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNNodeJsMobile.a; sourceTree = ""; }; 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTLinking.xcodeproj; path = "../node_modules/react-native/Libraries/LinkingIOS/RCTLinking.xcodeproj"; sourceTree = ""; }; + 7AA94215A3EE4C35AC5F6CC1 /* RNNodeJsMobile.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = RNNodeJsMobile.xcodeproj; path = "../node_modules/nodejs-mobile-react-native/ios/RNNodeJsMobile.xcodeproj"; sourceTree = ""; }; + 80C71F656A4B438C9B1F8B2D /* MaterialCommunityIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialCommunityIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf"; sourceTree = ""; }; 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTText.xcodeproj; path = "../node_modules/react-native/Libraries/Text/RCTText.xcodeproj"; sourceTree = ""; }; + 8982F42AFA1F49F2BDDEB2C8 /* Octicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Octicons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Octicons.ttf"; sourceTree = ""; }; + 8D70DD7BE74A46E8B20B7DE5 /* MaterialIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialIcons.ttf"; sourceTree = ""; }; + 9095C0A66BE149199FE16A5F /* EvilIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = EvilIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf"; sourceTree = ""; }; + 97457E848AD54409873D3FD4 /* RNAudio.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = RNAudio.xcodeproj; path = "../node_modules/react-native-audio-polyfill/RNAudio.xcodeproj"; sourceTree = ""; }; + 9BE87C948A6D477BAC13D99F /* libRNVectorIcons.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNVectorIcons.a; sourceTree = ""; }; 9DA5247712A84BBFA28C945A /* builtin_modules */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = builtin_modules; path = "../node_modules/nodejs-mobile-react-native/install/resources/nodejs-modules/builtin_modules"; sourceTree = ""; }; + 9FF89D62D2984EEC9B1D53D9 /* Zocial.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Zocial.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Zocial.ttf"; sourceTree = ""; }; + A0B6CD4FF46E48A69FCD0741 /* SimpleLineIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = SimpleLineIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/SimpleLineIcons.ttf"; sourceTree = ""; }; ADBDB91F1DFEBF0600ED6528 /* RCTBlob.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTBlob.xcodeproj; path = "../node_modules/react-native/Libraries/Blob/RCTBlob.xcodeproj"; sourceTree = ""; }; + BEA1E45F7AFC4BCDAA697D3F /* libRNAudio.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNAudio.a; sourceTree = ""; }; + C92111DD8DBD498F94C72687 /* Entypo.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Entypo.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Entypo.ttf"; sourceTree = ""; }; + F32E636344F7452EBB1C45EA /* Feather.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Feather.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Feather.ttf"; sourceTree = ""; }; + F32FD65A30134A9F8B647D21 /* Foundation.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Foundation.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Foundation.ttf"; sourceTree = ""; }; + F8E1CF91499D414FA01C8943 /* libRNNodeJsMobile.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNNodeJsMobile.a; sourceTree = ""; }; + FFCCAD942295D92100843948 /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -406,6 +450,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + FFCCADC72295D92100843948 /* JavaScriptCore.framework in Frameworks */, ADBDB9381DFEBF1600ED6528 /* libRCTBlob.a in Frameworks */, 5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */, 146834051AC3E58100842450 /* libReact.a in Frameworks */, @@ -419,9 +464,11 @@ 832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */, 00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */, 139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */, - 39B3D37ADFD7489BAD6EB717 /* libRNNodeJsMobile.a in Frameworks */, 8CC8B3545F71477CA83015C8 /* NodeMobile.framework in Frameworks */, DA38831A77DA42318634B0B8 /* libRNFS.a in Frameworks */, + FA0A930648274178AFB1E8B1 /* libRNAudio.a in Frameworks */, + 80B1704D2DB94505905514BA /* libRNVectorIcons.a in Frameworks */, + 4F571A52E7044A9A9D54A89F /* libRNNodeJsMobile.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -552,16 +599,16 @@ 3DAD3EA71DF850E9000B6D8A /* libyoga.a */, 3DAD3EA91DF850E9000B6D8A /* libcxxreact.a */, 3DAD3EAB1DF850E9000B6D8A /* libcxxreact.a */, - 3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */, - 3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */, FFE21AB0205D8877004F7897 /* libjsinspector.a */, FFE21AB2205D8877004F7897 /* libjsinspector-tvOS.a */, FFE21AB4205D8877004F7897 /* libthird-party.a */, FFE21AB6205D8877004F7897 /* libthird-party.a */, FFE21AB8205D8877004F7897 /* libdouble-conversion.a */, FFE21ABA205D8877004F7897 /* libdouble-conversion.a */, - FFE21ABC205D8877004F7897 /* libprivatedata.a */, - FFE21ABE205D8877004F7897 /* libprivatedata-tvOS.a */, + FFCCADBB2295D92100843948 /* libjsi.a */, + FFCCADBD2295D92100843948 /* libjsiexecutor.a */, + FFCCADBF2295D92100843948 /* libjsi-tvOS.a */, + FFCCADC12295D92100843948 /* libjsiexecutor-tvOS.a */, ); name = Products; sourceTree = ""; @@ -569,6 +616,7 @@ 2D16E6871FA4F8E400B85C8A /* Frameworks */ = { isa = PBXGroup; children = ( + FFCCAD942295D92100843948 /* JavaScriptCore.framework */, 2D16E6891FA4F8E400B85C8A /* libReact.a */, 124EC05E131A44D4850F2BF6 /* NodeMobile.framework */, ); @@ -608,8 +656,10 @@ 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */, 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */, 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */, - 606EB20FA9A940B0B4A24B63 /* RNNodeJsMobile.xcodeproj */, 615FC19D9B314671A382CD8A /* RNFS.xcodeproj */, + 97457E848AD54409873D3FD4 /* RNAudio.xcodeproj */, + 437C5D64C0F34573B899A66C /* RNVectorIcons.xcodeproj */, + 7AA94215A3EE4C35AC5F6CC1 /* RNNodeJsMobile.xcodeproj */, ); name = Libraries; sourceTree = ""; @@ -634,6 +684,7 @@ FFE21A89205D8876004F7897 /* Recovered References */, 1D2494BC39C34388B2973202 /* nodejs-project */, 9DA5247712A84BBFA28C945A /* builtin_modules */, + C488608583CB41719AA7E733 /* Resources */, ); indentWidth = 2; sourceTree = ""; @@ -660,10 +711,44 @@ name = Products; sourceTree = ""; }; - FF757C0C20B36F630055D174 /* Products */ = { + C488608583CB41719AA7E733 /* Resources */ = { + isa = PBXGroup; + children = ( + C92111DD8DBD498F94C72687 /* Entypo.ttf */, + 9095C0A66BE149199FE16A5F /* EvilIcons.ttf */, + F32E636344F7452EBB1C45EA /* Feather.ttf */, + 23F8EDCB2294447EA6D87E13 /* FontAwesome.ttf */, + F32FD65A30134A9F8B647D21 /* Foundation.ttf */, + 18C93A84BE1B497D9F5BFF36 /* Ionicons.ttf */, + 80C71F656A4B438C9B1F8B2D /* MaterialCommunityIcons.ttf */, + 8D70DD7BE74A46E8B20B7DE5 /* MaterialIcons.ttf */, + 8982F42AFA1F49F2BDDEB2C8 /* Octicons.ttf */, + A0B6CD4FF46E48A69FCD0741 /* SimpleLineIcons.ttf */, + 9FF89D62D2984EEC9B1D53D9 /* Zocial.ttf */, + ); + name = Resources; + sourceTree = ""; + }; + FF1F22B520ED49E300830BBF /* Products */ = { + isa = PBXGroup; + children = ( + FF1F22B920ED49E300830BBF /* libRNVectorIcons.a */, + ); + name = Products; + sourceTree = ""; + }; + FFBB06F520D5ECA9006901B0 /* Products */ = { isa = PBXGroup; children = ( - FF757C3520B36F630055D174 /* libRNNodeJsMobile.a */, + FFBB06F920D5ECA9006901B0 /* libRNAudio.a */, + ); + name = Products; + sourceTree = ""; + }; + FFCCAE0F2295F4B400843948 /* Products */ = { + isa = PBXGroup; + children = ( + FFCCAE132295F4B400843948 /* libRNNodeJsMobile.a */, ); name = Products; sourceTree = ""; @@ -680,8 +765,10 @@ FFE21A89205D8876004F7897 /* Recovered References */ = { isa = PBXGroup; children = ( - 6162BD573EF84A479FC3A188 /* libRNNodeJsMobile.a */, 00222BC525FD4CD5ADC1609A /* libRNFS.a */, + BEA1E45F7AFC4BCDAA697D3F /* libRNAudio.a */, + 9BE87C948A6D477BAC13D99F /* libRNVectorIcons.a */, + F8E1CF91499D414FA01C8943 /* libRNNodeJsMobile.a */, ); name = "Recovered References"; sourceTree = ""; @@ -716,8 +803,9 @@ 13B07F8E1A680F5B00A75B9A /* Resources */, 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, 7877A34B57F347DB9C67BCBB /* Embed Frameworks */, - 9FF87993AB774A1EA2ABDB57 /* Build NodeJS Mobile Native Modules */, - F05E84F1159740A896D0F1B6 /* Sign NodeJS Mobile Native Modules */, + 974A76B5CE1D4C9185A6D973 /* Build NodeJS Mobile Native Modules */, + 69A403A8C1E04A42BD81A5D3 /* Sign NodeJS Mobile Native Modules */, + 19D9929D1A0A4832968A42E5 /* Remove NodeJS Mobile Framework Simulator Strips */, ); buildRules = ( ); @@ -781,6 +869,11 @@ 13B07F861A680F5B00A75B9A = { DevelopmentTeam = 8PU8BA3SQD; ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.BackgroundModes = { + enabled = 1; + }; + }; }; 2D02E47A1E0B4A5D006451C7 = { CreatedOnToolsVersion = 8.2.1; @@ -798,6 +891,7 @@ developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( + English, en, Base, ); @@ -853,13 +947,21 @@ ProductGroup = 146834001AC3E56700842450 /* Products */; ProjectRef = 146833FF1AC3E56700842450 /* React.xcodeproj */; }, + { + ProductGroup = FFBB06F520D5ECA9006901B0 /* Products */; + ProjectRef = 97457E848AD54409873D3FD4 /* RNAudio.xcodeproj */; + }, { ProductGroup = FFD0F40B20B46B1F0081E8CA /* Products */; ProjectRef = 615FC19D9B314671A382CD8A /* RNFS.xcodeproj */; }, { - ProductGroup = FF757C0C20B36F630055D174 /* Products */; - ProjectRef = 606EB20FA9A940B0B4A24B63 /* RNNodeJsMobile.xcodeproj */; + ProductGroup = FFCCAE0F2295F4B400843948 /* Products */; + ProjectRef = 7AA94215A3EE4C35AC5F6CC1 /* RNNodeJsMobile.xcodeproj */; + }, + { + ProductGroup = FF1F22B520ED49E300830BBF /* Products */; + ProjectRef = 437C5D64C0F34573B899A66C /* RNVectorIcons.xcodeproj */; }, ); projectRoot = ""; @@ -1027,20 +1129,6 @@ remoteRef = 3DAD3EAA1DF850E9000B6D8A /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = libjschelpers.a; - remoteRef = 3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = libjschelpers.a; - remoteRef = 3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; 5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; @@ -1076,11 +1164,53 @@ remoteRef = ADBDB9261DFEBF0700ED6528 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - FF757C3520B36F630055D174 /* libRNNodeJsMobile.a */ = { + FF1F22B920ED49E300830BBF /* libRNVectorIcons.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRNVectorIcons.a; + remoteRef = FF1F22B820ED49E300830BBF /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + FFBB06F920D5ECA9006901B0 /* libRNAudio.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRNAudio.a; + remoteRef = FFBB06F820D5ECA9006901B0 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + FFCCADBB2295D92100843948 /* libjsi.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libjsi.a; + remoteRef = FFCCADBA2295D92100843948 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + FFCCADBD2295D92100843948 /* libjsiexecutor.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libjsiexecutor.a; + remoteRef = FFCCADBC2295D92100843948 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + FFCCADBF2295D92100843948 /* libjsi-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libjsi-tvOS.a"; + remoteRef = FFCCADBE2295D92100843948 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + FFCCADC12295D92100843948 /* libjsiexecutor-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libjsiexecutor-tvOS.a"; + remoteRef = FFCCADC02295D92100843948 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + FFCCAE132295F4B400843948 /* libRNNodeJsMobile.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRNNodeJsMobile.a; - remoteRef = FF757C3420B36F630055D174 /* PBXContainerItemProxy */; + remoteRef = FFCCAE122295F4B400843948 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; FFD0F41020B46B200081E8CA /* libRNFS.a */ = { @@ -1139,20 +1269,6 @@ remoteRef = FFE21AB9205D8877004F7897 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - FFE21ABC205D8877004F7897 /* libprivatedata.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = libprivatedata.a; - remoteRef = FFE21ABB205D8877004F7897 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - FFE21ABE205D8877004F7897 /* libprivatedata-tvOS.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = "libprivatedata-tvOS.a"; - remoteRef = FFE21ABD205D8877004F7897 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ @@ -1172,6 +1288,17 @@ FFC710E8206329B7003524B5 /* main.jsbundle in Resources */, B522B19439D1447FB7565D2C /* nodejs-project in Resources */, 086BFC5591C740E6B8800A16 /* builtin_modules in Resources */, + C4A37B44BF874CD0965FCF8E /* Entypo.ttf in Resources */, + 6DADDAF1C3C9495B81260959 /* EvilIcons.ttf in Resources */, + 596E9FB3F4034A47B4D22B94 /* Feather.ttf in Resources */, + EDA20E8287B44B5D92DFF238 /* FontAwesome.ttf in Resources */, + 6E5BBFC2BC0D4F93BE8C3929 /* Foundation.ttf in Resources */, + A1AAF3BE8C944B9EB66BAB48 /* Ionicons.ttf in Resources */, + EEADBB9221194EA0ADC9876D /* MaterialCommunityIcons.ttf in Resources */, + F29E7278F4D24B5BA2C2DDFC /* MaterialIcons.ttf in Resources */, + 5A83EA2EF4B3450EA67DD421 /* Octicons.ttf in Resources */, + BCF729E50F004A2D9E6FE886 /* SimpleLineIcons.ttf in Resources */, + D3710D6416544243A3D3E4C3 /* Zocial.ttf in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1205,7 +1332,21 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh"; + shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh\n"; + }; + 19D9929D1A0A4832968A42E5 /* Remove NodeJS Mobile Framework Simulator Strips */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Remove NodeJS Mobile Framework Simulator Strips"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\nset -e\nFRAMEWORK_BINARY_PATH=\"$TARGET_BUILD_DIR/$FRAMEWORKS_FOLDER_PATH/NodeMobile.framework/NodeMobile\"\nFRAMEWORK_STRIPPED_PATH=\"$FRAMEWORK_BINARY_PATH-strip\"\nif [ \"$PLATFORM_NAME\" != \"iphonesimulator\" ]; then\n if $(lipo \"$FRAMEWORK_BINARY_PATH\" -verify_arch \"x86_64\") ; then\n lipo -output \"$FRAMEWORK_STRIPPED_PATH\" -remove \"x86_64\" \"$FRAMEWORK_BINARY_PATH\"\n rm \"$FRAMEWORK_BINARY_PATH\"\n mv \"$FRAMEWORK_STRIPPED_PATH\" \"$FRAMEWORK_BINARY_PATH\"\n echo \"Removed simulator strip from NodeMobile.framework\"\n fi\nfi\n"; }; 2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */ = { isa = PBXShellScriptBuildPhase; @@ -1221,33 +1362,33 @@ shellPath = /bin/sh; shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh"; }; - 9FF87993AB774A1EA2ABDB57 /* Build NodeJS Mobile Native Modules */ = { + 69A403A8C1E04A42BD81A5D3 /* Sign NodeJS Mobile Native Modules */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Build NodeJS Mobile Native Modules"; + name = "Sign NodeJS Mobile Native Modules"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\nset -e\nif [ -z \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then\n# If build native modules preference is not set, look for it in the project's\n#nodejs-assets/BUILD_NATIVE_MODULES.txt file.\nNODEJS_ASSETS_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../nodejs-assets/ && pwd )\"\nPREFERENCE_FILE_PATH=\"$NODEJS_ASSETS_DIR/BUILD_NATIVE_MODULES.txt\"\nif [ -f \"$PREFERENCE_FILE_PATH\" ]; then\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=\"$(cat $PREFERENCE_FILE_PATH | xargs)\"\nelse\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=0\nfi\nfi\nif [ \"1\" != \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then exit 0; fi\n# Apply patches to the modules package.json\nPATCH_SCRIPT_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-react-native/scripts/ && pwd )\"\nNODEJS_PROJECT_MODULES_DIR=\"$( cd \"$CODESIGNING_FOLDER_PATH\" && cd nodejs-project/node_modules/ && pwd )\"\nnode \"$PATCH_SCRIPT_DIR\"/patch-package.js $NODEJS_PROJECT_MODULES_DIR\n# Get the nodejs-mobile-gyp location\nNODEJS_MOBILE_GYP_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-gyp/ && pwd )\"\nNODEJS_MOBILE_GYP_BIN_FILE=\"$NODEJS_MOBILE_GYP_DIR\"/bin/node-gyp.js\n# Rebuild modules with right environment\nNODEJS_HEADERS_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-react-native/ios/libnode/ && pwd )\"\npushd $CODESIGNING_FOLDER_PATH/nodejs-project/\nif [ \"$PLATFORM_NAME\" == \"iphoneos\" ]\nthen\n GYP_DEFINES=\"OS=ios\" npm_config_nodedir=\"$NODEJS_HEADERS_DIR\" npm_config_node_gyp=\"$NODEJS_MOBILE_GYP_BIN_FILE\" npm_config_platform=\"ios\" npm_config_node_engine=\"chakracore\" npm_config_arch=\"arm64\" npm --verbose rebuild --build-from-source\nelse\n GYP_DEFINES=\"OS=ios\" npm_config_nodedir=\"$NODEJS_HEADERS_DIR\" npm_config_node_gyp=\"$NODEJS_MOBILE_GYP_BIN_FILE\" npm_config_platform=\"ios\" npm_config_node_engine=\"chakracore\" npm_config_arch=\"x64\" npm --verbose rebuild --build-from-source\nfi\npopd\n"; + shellScript = "export NVM_DIR=\"$HOME/.nvm\"\n[ -s \"$NVM_DIR/nvm.sh\" ] && . \"$NVM_DIR/nvm.sh\" # This loads nvm\nset -e\nif [ -z \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then\n# If build native modules preference is not set, look for it in the project's\n#nodejs-assets/BUILD_NATIVE_MODULES.txt file.\nNODEJS_ASSETS_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../nodejs-assets/ && pwd )\"\nPREFERENCE_FILE_PATH=\"$NODEJS_ASSETS_DIR/BUILD_NATIVE_MODULES.txt\"\n if [ -f \"$PREFERENCE_FILE_PATH\" ]; then\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=\"$(cat $PREFERENCE_FILE_PATH | xargs)\"\n fi\nfi\nif [ -z \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then\n# If build native modules preference is not set, try to find .gyp files\n#to turn it on.\n gypfiles=($(find \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -type f -name \"*.gyp\"))\n if [ ${#gypfiles[@]} -gt 0 ]; then\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=1\n else\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=0\n fi\nfi\nif [ \"1\" != \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then exit 0; fi\n# Delete object files\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.o\" -type f -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.a\" -type f -delete\n# Create Info.plist for each framework built and loader override.\nPATCH_SCRIPT_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-react-native/scripts/ && pwd )\"\nNODEJS_PROJECT_DIR=\"$( cd \"$CODESIGNING_FOLDER_PATH\" && cd nodejs-project/ && pwd )\"\nnode \"$PATCH_SCRIPT_DIR\"/ios-create-plists-and-dlopen-override.js $NODEJS_PROJECT_DIR\n# Embed every resulting .framework in the application and delete them afterwards.\nembed_framework()\n{\n FRAMEWORK_NAME=\"$(basename \"$1\")\"\n cp -r \"$1\" \"$TARGET_BUILD_DIR/$FRAMEWORKS_FOLDER_PATH/\"\n\n /usr/bin/codesign --force --sign $EXPANDED_CODE_SIGN_IDENTITY --preserve-metadata=identifier,entitlements,flags --timestamp=none \"$TARGET_BUILD_DIR/$FRAMEWORKS_FOLDER_PATH/$FRAMEWORK_NAME\"\n}\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.framework\" -type d | while read frmwrk_path; do embed_framework \"$frmwrk_path\"; done\n\n#Delete gyp temporary .deps dependency folders from the project structure.\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -path \"*/.deps/*\" -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \".deps\" -type d -delete\n\n#Delete frameworks from their build paths\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -path \"*/*.framework/*\" -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.framework\" -type d -delete\n"; }; - F05E84F1159740A896D0F1B6 /* Sign NodeJS Mobile Native Modules */ = { + 974A76B5CE1D4C9185A6D973 /* Build NodeJS Mobile Native Modules */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Sign NodeJS Mobile Native Modules"; + name = "Build NodeJS Mobile Native Modules"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\nset -e\nif [ -z \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then\n# If build native modules preference is not set, look for it in the project's\n#nodejs-assets/BUILD_NATIVE_MODULES.txt file.\nNODEJS_ASSETS_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../nodejs-assets/ && pwd )\"\nPREFERENCE_FILE_PATH=\"$NODEJS_ASSETS_DIR/BUILD_NATIVE_MODULES.txt\"\nif [ -f \"$PREFERENCE_FILE_PATH\" ]; then\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=\"$(cat $PREFERENCE_FILE_PATH | xargs)\"\nelse\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=0\nfi\nfi\nif [ \"1\" != \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then exit 0; fi\n/usr/bin/codesign --force --sign $EXPANDED_CODE_SIGN_IDENTITY --preserve-metadata=identifier,entitlements,flags --timestamp=none $(find \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -type f -name \"*.node\")\n"; + shellScript = "export NVM_DIR=\"$HOME/.nvm\"\n[ -s \"$NVM_DIR/nvm.sh\" ] && . \"$NVM_DIR/nvm.sh\" # This loads nvm\nset -e\nif [ -z \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then\n# If build native modules preference is not set, look for it in the project's\n#nodejs-assets/BUILD_NATIVE_MODULES.txt file.\nNODEJS_ASSETS_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../nodejs-assets/ && pwd )\"\nPREFERENCE_FILE_PATH=\"$NODEJS_ASSETS_DIR/BUILD_NATIVE_MODULES.txt\"\n if [ -f \"$PREFERENCE_FILE_PATH\" ]; then\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=\"$(cat $PREFERENCE_FILE_PATH | xargs)\"\n fi\nfi\nif [ -z \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then\n# If build native modules preference is not set, try to find .gyp files\n#to turn it on.\n gypfiles=($(find \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -type f -name \"*.gyp\"))\n if [ ${#gypfiles[@]} -gt 0 ]; then\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=1\n else\n NODEJS_MOBILE_BUILD_NATIVE_MODULES=0\n fi\nfi\nif [ \"1\" != \"$NODEJS_MOBILE_BUILD_NATIVE_MODULES\" ]; then exit 0; fi\n# Delete object files that may already come from within the npm package.\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.o\" -type f -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.a\" -type f -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.node\" -type f -delete\n# Delete bundle contents that may be there from previous builds.\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -path \"*/*.node/*\" -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.node\" -type d -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -path \"*/*.framework/*\" -delete\nfind \"$CODESIGNING_FOLDER_PATH/nodejs-project/\" -name \"*.framework\" -type d -delete\n# Apply patches to the modules package.json\nif [ -d \"$CODESIGNING_FOLDER_PATH\"/nodejs-project/node_modules/ ]; then\n PATCH_SCRIPT_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-react-native/scripts/ && pwd )\"\n NODEJS_PROJECT_MODULES_DIR=\"$( cd \"$CODESIGNING_FOLDER_PATH\" && cd nodejs-project/node_modules/ && pwd )\"\n node \"$PATCH_SCRIPT_DIR\"/patch-package.js $NODEJS_PROJECT_MODULES_DIR\nfi\n# Get the nodejs-mobile-gyp location\nif [ -d \"$PROJECT_DIR/../node_modules/nodejs-mobile-gyp/\" ]; then\n NODEJS_MOBILE_GYP_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-gyp/ && pwd )\"\nelse\n NODEJS_MOBILE_GYP_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-react-native/node_modules/nodejs-mobile-gyp/ && pwd )\"\nfi\nNODEJS_MOBILE_GYP_BIN_FILE=\"$NODEJS_MOBILE_GYP_DIR\"/bin/node-gyp.js\n# Rebuild modules with right environment\nNODEJS_HEADERS_DIR=\"$( cd \"$PROJECT_DIR\" && cd ../node_modules/nodejs-mobile-react-native/ios/libnode/ && pwd )\"\npushd $CODESIGNING_FOLDER_PATH/nodejs-project/\nif [ \"$PLATFORM_NAME\" == \"iphoneos\" ]\nthen\n GYP_DEFINES=\"OS=ios\" npm_config_nodedir=\"$NODEJS_HEADERS_DIR\" npm_config_node_gyp=\"$NODEJS_MOBILE_GYP_BIN_FILE\" npm_config_platform=\"ios\" npm_config_format=\"make-ios\" npm_config_node_engine=\"chakracore\" npm_config_arch=\"arm64\" npm --verbose rebuild --build-from-source\nelse\n GYP_DEFINES=\"OS=ios\" npm_config_nodedir=\"$NODEJS_HEADERS_DIR\" npm_config_node_gyp=\"$NODEJS_MOBILE_GYP_BIN_FILE\" npm_config_platform=\"ios\" npm_config_format=\"make-ios\" npm_config_node_engine=\"chakracore\" npm_config_arch=\"x64\" npm --verbose rebuild --build-from-source\nfi\npopd\n"; }; /* End PBXShellScriptBuildPhase section */ @@ -1330,8 +1471,10 @@ ); HEADER_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", "$(SRCROOT)/../node_modules/react-native-fs/**", + "$(SRCROOT)/../node_modules/react-native-audio-polyfill/RNAudio", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", ); INFOPLIST_FILE = RecordTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.0; @@ -1362,8 +1505,10 @@ ); HEADER_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", "$(SRCROOT)/../node_modules/react-native-fs/**", + "$(SRCROOT)/../node_modules/react-native-audio-polyfill/RNAudio", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", ); INFOPLIST_FILE = RecordTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.0; @@ -1398,8 +1543,10 @@ ); HEADER_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", "$(SRCROOT)/../node_modules/react-native-fs/**", + "$(SRCROOT)/../node_modules/react-native-audio-polyfill/RNAudio", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", ); INFOPLIST_FILE = Record/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; @@ -1431,8 +1578,10 @@ ); HEADER_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", "$(SRCROOT)/../node_modules/react-native-fs/**", + "$(SRCROOT)/../node_modules/react-native-audio-polyfill/RNAudio", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", ); INFOPLIST_FILE = Record/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; @@ -1467,8 +1616,10 @@ GCC_NO_COMMON_BLOCKS = YES; HEADER_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", "$(SRCROOT)/../node_modules/react-native-fs/**", + "$(SRCROOT)/../node_modules/react-native-audio-polyfill/RNAudio", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", ); INFOPLIST_FILE = "Record-tvOS/Info.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; @@ -1507,8 +1658,10 @@ GCC_NO_COMMON_BLOCKS = YES; HEADER_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", "$(SRCROOT)/../node_modules/react-native-fs/**", + "$(SRCROOT)/../node_modules/react-native-audio-polyfill/RNAudio", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/nodejs-mobile-react-native/ios/**", ); INFOPLIST_FILE = "Record-tvOS/Info.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; diff --git a/ios/Record.xcodeproj/xcshareddata/xcschemes/Record.xcscheme b/ios/Record.xcodeproj/xcshareddata/xcschemes/Record.xcscheme index d5f76138..043949a7 100644 --- a/ios/Record.xcodeproj/xcshareddata/xcschemes/Record.xcscheme +++ b/ios/Record.xcodeproj/xcshareddata/xcschemes/Record.xcscheme @@ -85,6 +85,13 @@ ReferencedContainer = "container:Record.xcodeproj"> + + + + diff --git a/ios/record/AppDelegate.m b/ios/record/AppDelegate.m index 9051b08a..6ce131ff 100644 --- a/ios/record/AppDelegate.m +++ b/ios/record/AppDelegate.m @@ -25,7 +25,7 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( // Run from locally running dev server jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/src/index.ios.bundle?platform=ios&dev=true"]; #else - // Run on device with code coming from dev server on comp (change the IP to your comps IP) + // Run on device with code coming from dev server on comp jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"src/index.ios" fallbackResource:nil]; #endif #else diff --git a/ios/record/Info.plist b/ios/record/Info.plist index faf5281f..a84ed901 100644 --- a/ios/record/Info.plist +++ b/ios/record/Info.plist @@ -37,6 +37,25 @@ NSLocationWhenInUseUsageDescription + UIAppFonts + + Entypo.ttf + EvilIcons.ttf + Feather.ttf + FontAwesome.ttf + Foundation.ttf + Ionicons.ttf + MaterialCommunityIcons.ttf + MaterialIcons.ttf + Octicons.ttf + SimpleLineIcons.ttf + Zocial.ttf + + UIBackgroundModes + + audio + fetch + UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities diff --git a/nodejs-assets/nodejs-project/bundle.js b/nodejs-assets/nodejs-project/bundle.js index 3a9aca6e..18c046f3 100644 --- a/nodejs-assets/nodejs-project/bundle.js +++ b/nodejs-assets/nodejs-project/bundle.js @@ -1,144858 +1,225224 @@ (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i false // disable colors in log (fixes xcode issue) - -// Log Record / IPFS / OrbitDB -const logger = debug('main') -debug.enable('main,jsipfs:*,libp2p:*,bitswap:*') //libp2p:switch:dial,libp2p:switch:transport,libp2p:swarm:dialer') -Logger.setLogLevel(Logger.LogLevels.DEBUG) - -process.on('uncaughtException', (err) => { - console.log(err) -}) - -logger('starting') - -let rn = null -let ipfs = null -let started = false - -const init = (docsPath) => { - if (started) { - if (!ipfs) { - // shit - - return - } - - if (ipfs.state.state() === 'running') { - return rnBridge.channel.send(JSON.stringify({ action: 'ready' })) - } - - ipfs.on('ready', () => { - console.log('sending ready') - rnBridge.channel.send(JSON.stringify({ action: 'ready' })) - }) - return - } - - started = true - - const recorddir = path.resolve(docsPath, './record') - - if (!fs.existsSync(recorddir)) { fs.mkdirSync(recorddir) } - - logger(`Record Dir: ${recorddir}`) - - const ipfsConfig = { - init: { - bits: 1024 - }, - repo: path.resolve(recorddir, './ipfs'), - EXPERIMENTAL: { - dht: false, // TODO: BRICKS COMPUTER - relay: { - enabled: true, - hop: { - enabled: false, // TODO: CPU hungry on mobile - active: false - } - }, - pubsub: true - }, - config: { - Bootstrap: [], - Addresses: { - Swarm: [ - '/ip4/159.203.117.254/tcp/9090/ws/p2p-websocket-star' - ] - } - } - } - - try { - // Create the IPFS node instance - ipfs = new IPFS(ipfsConfig) - - // TODO: throttle ipfs attemptDials & incoming connections from same peer - - ipfs.on('ready', async () => { - const orbitAddressPath = path.resolve(recorddir, 'address.txt') - - const orbitAddress = fs.existsSync(orbitAddressPath) ? - fs.readFileSync(orbitAddressPath, 'utf8') : undefined - - logger(`Orbit Address: ${orbitAddress}`) - - const opts = { - orbitPath: path.resolve(recorddir, './orbitdb'), - orbitAddress: orbitAddress - } - - rn = new RecordNode(ipfs, OrbitDB, opts) - - try { - await rn.loadLog() - fs.writeFileSync(orbitAddressPath, rn._log.address) - } catch(e) { - console.log(e) - } - - rnBridge.channel.send(JSON.stringify({ action: 'ready' })) - - // TODO: syncContacts once dialing is complete - setTimeout(() => { - rn.syncContacts() - }, 30000) - - }) - - } catch(e) { - console.log(e) - } - - logger('initialized') - -} - -rnBridge.channel.on('message', async (message) => { - - const msg = JSON.parse(message) - logger(msg) - - let data - let log - - switch(msg.action) { - case 'init': - init(msg.data.docsPath) - break - - case 'suspend': - ipfs.stop() - break - - case 'resume': - ipfs.start((err) => { - if (err) { - console.log(err) - } - - logger('ipfs started') - }) - break - - case 'contacts:get': - if (!rn) { - return - } - - try { - log = await rn.loadLog(msg.data.logId) - data = log.contacts.all() - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - data - })) - } catch (e) { - console.log(e) - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - error: e.toString() - })) - } - break - - case 'contacts:add': - if (!rn) { - return - } - - try { - const { address, alias } = msg.data - log = await rn.loadLog(msg.data.logId) - data = await log.contacts.findOrCreate({ address, alias }) - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - data - })) - } catch (e) { - console.log(e) - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - error: e.toString() - })) - } - break - - case 'info:get': - if (!rn) { - return - } - - try { - data = await rn.info() - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - data - })) - } catch (e) { - console.log(e) - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - error: e.toString() - })) - } - break - - case 'tracks:get': - if (!rn) { - return - } - - try { - log = await rn.loadLog(msg.data.logId) - data = log.tracks.all() - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - data - })) - } catch(e) { - console.log(e) - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - error: e.toString() - })) - } - break - - case 'tracks:add': - if (!rn) { - return - } - - try { - const { title, url } = msg.data - log = await rn.loadLog(msg.data.logId) - data = await log.tracks.findOrCreate({ title, url }) - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - data - })) - } catch (e) { - console.log(e) - rnBridge.channel.send(JSON.stringify({ - action: msg.action, - error: e.toString() - })) - } - break - - default: - logger(`Invalid message action: ${msg.action}`) - } - -}) - -},{"debug":182,"fs":undefined,"ipfs":536,"logplease":938,"orbit-db":1078,"os":undefined,"path":undefined,"record-node":1244,"rn-bridge":undefined}],2:[function(require,module,exports){ -/*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var Negotiator = require('negotiator') -var mime = require('mime-types') - -/** - * Module exports. - * @public - */ +'use strict'; -module.exports = Accepts +var iconvLite = require('iconv-lite'); // Load Iconv from an external file to be able to disable Iconv for webpack +// Add /\/iconv-loader$/ to webpack.IgnorePlugin to ignore it -/** - * Create a new Accepts object for the given req. - * - * @param {object} req - * @public - */ -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) - } +var Iconv = require('./iconv-loader'); // Expose to the world - this.headers = req.headers - this.negotiator = new Negotiator(req) -} +module.exports.convert = convert; /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json" or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * this.types('html'); - * // => "html" - * - * // Accept: text/*, application/json - * this.types('html'); - * // => "html" - * this.types('text/html'); - * // => "text/html" - * this.types('json', 'text'); - * // => "json" - * this.types('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * this.types('image/png'); - * this.types('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * this.types(['html', 'json']); - * this.types('html', 'json'); - * // => "json" + * Convert encoding of an UTF-8 string or a buffer * - * @param {String|Array} types... - * @return {String|Array|Boolean} - * @public + * @param {String|Buffer} str String to be converted + * @param {String} to Encoding to be converted to + * @param {String} [from='UTF-8'] Encoding to be converted from + * @param {Boolean} useLite If set to ture, force to use iconvLite + * @return {Buffer} Encoded string */ -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_ - - // support flattened arguments - if (types && !Array.isArray(types)) { - types = new Array(arguments.length) - for (var i = 0; i < types.length; i++) { - types[i] = arguments[i] - } - } - - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() - } +function convert(str, to, from, useLite) { + from = checkEncoding(from || 'UTF-8'); + to = checkEncoding(to || 'UTF-8'); + str = str || ''; + var result; - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] + if (from !== 'UTF-8' && typeof str === 'string') { + str = new Buffer(str, 'binary'); } - var mimes = types.map(extToMime) - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) - var first = accepts[0] - - return first - ? types[mimes.indexOf(first)] - : false -} - -/** - * Return accepted encodings or best fit based on `encodings`. - * - * Given `Accept-Encoding: gzip, deflate` - * an array sorted by quality is returned: - * - * ['gzip', 'deflate'] - * - * @param {String|Array} encodings... - * @return {String|Array} - * @public - */ - -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_ + if (from === to) { + if (typeof str === 'string') { + result = new Buffer(str); + } else { + result = str; + } + } else if (Iconv && !useLite) { + try { + result = convertIconv(str, to, from); + } catch (E) { + console.error(E); - // support flattened arguments - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length) - for (var i = 0; i < encodings.length; i++) { - encodings[i] = arguments[i] + try { + result = convertIconvLite(str, to, from); + } catch (E) { + console.error(E); + result = str; + } + } + } else { + try { + result = convertIconvLite(str, to, from); + } catch (E) { + console.error(E); + result = str; } } - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() + if (typeof result === 'string') { + result = new Buffer(result, 'utf-8'); } - return this.negotiator.encodings(encodings)[0] || false + return result; } - /** - * Return accepted charsets or best fit based on `charsets`. - * - * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` - * an array sorted by quality is returned: + * Convert encoding of a string with node-iconv (if available) * - * ['utf-8', 'utf-7', 'iso-8859-1'] - * - * @param {String|Array} charsets... - * @return {String|Array} - * @public + * @param {String|Buffer} str String to be converted + * @param {String} to Encoding to be converted to + * @param {String} [from='UTF-8'] Encoding to be converted from + * @return {Buffer} Encoded string */ -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_ - - // support flattened arguments - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length) - for (var i = 0; i < charsets.length; i++) { - charsets[i] = arguments[i] - } - } - - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() - } - return this.negotiator.charsets(charsets)[0] || false +function convertIconv(str, to, from) { + var response, iconv; + iconv = new Iconv(from, to + '//TRANSLIT//IGNORE'); + response = iconv.convert(str); + return response.slice(0, response.length); } - /** - * Return accepted languages or best fit based on `langs`. - * - * Given `Accept-Language: en;q=0.8, es, pt` - * an array sorted by quality is returned: - * - * ['es', 'pt', 'en'] + * Convert encoding of astring with iconv-lite * - * @param {String|Array} langs... - * @return {Array|String} - * @public + * @param {String|Buffer} str String to be converted + * @param {String} to Encoding to be converted to + * @param {String} [from='UTF-8'] Encoding to be converted from + * @return {Buffer} Encoded string */ -Accepts.prototype.lang = -Accepts.prototype.langs = -Accepts.prototype.language = -Accepts.prototype.languages = function (languages_) { - var languages = languages_ - - // support flattened arguments - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length) - for (var i = 0; i < languages.length; i++) { - languages[i] = arguments[i] - } - } - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() +function convertIconvLite(str, to, from) { + if (to === 'UTF-8') { + return iconvLite.decode(str, from); + } else if (from === 'UTF-8') { + return iconvLite.encode(str, to); + } else { + return iconvLite.encode(iconvLite.decode(str, from), to); } - - return this.negotiator.languages(languages)[0] || false } - /** - * Convert extnames to mime. + * Converts charset name if needed * - * @param {String} type - * @return {String} - * @private + * @param {String} name Character set + * @return {String} Character set name */ -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type -} - -/** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private - */ -function validMime (type) { - return typeof type === 'string' +function checkEncoding(name) { + return (name || '').toString().trim().replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1').replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1').replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1').replace(/^ks_c_5601\-1987$/i, 'CP949').replace(/^us[\-_]?ascii$/i, 'ASCII').toUpperCase(); } -},{"mime-types":952,"negotiator":1002}],3:[function(require,module,exports){ -module.exports = after - -function after(count, callback, err_cb) { - var bail = false - err_cb = err_cb || noop - proxy.count = count - - return (count === 0) ? callback() : proxy +},{"./iconv-loader":2,"iconv-lite":22}],2:[function(require,module,exports){ +'use strict'; - function proxy(err, result) { - if (proxy.count <= 0) { - throw new Error('after called too many times') - } - --proxy.count +var iconv_package; +var Iconv; - // after first error, rest are passed to err_cb - if (err) { - bail = true - callback(err) - // future error callbacks will go to error handler - callback = err_cb - } else if (proxy.count === 0 && !bail) { - callback(null, result) - } - } +try { + // this is to fool browserify so it doesn't try (in vain) to install iconv. + iconv_package = 'iconv'; + Iconv = require(iconv_package).Iconv; +} catch (E) {// node-iconv not present } -function noop() {} - -},{}],4:[function(require,module,exports){ -'use strict' - -/** - * Expose `arrayFlatten`. - */ -module.exports = arrayFlatten +module.exports = Iconv; -/** - * Recursive flatten function with depth. - * - * @param {Array} array - * @param {Array} result - * @param {Number} depth - * @return {Array} - */ -function flattenWithDepth (array, result, depth) { - for (var i = 0; i < array.length; i++) { - var value = array[i] +},{}],3:[function(require,module,exports){ +"use strict"; - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) - } - } +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - return result -} +var Buffer = require("safer-buffer").Buffer; // Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. -/** - * Recursive flatten function. Omitting depth is slightly faster. - * - * @param {Array} array - * @param {Array} result - * @return {Array} - */ -function flattenForever (array, result) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) - } - } +exports._dbcs = DBCSCodec; +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; - return result -} +for (var i = 0; i < 0x100; i++) { + UNASSIGNED_NODE[i] = UNASSIGNED; +} // Class DBCSCodec reads and initializes mapping tables. -/** - * Flatten an array, with the ability to define a depth. - * - * @param {Array} array - * @param {Number} depth - * @return {Array} - */ -function arrayFlatten (array, depth) { - if (depth == null) { - return flattenForever(array, []) - } - return flattenWithDepth(array, [], depth) -} +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) throw new Error("DBCS codec is called without the data."); + if (!codecOptions.table) throw new Error("Encoding '" + this.encodingName + "' has no data."); // Load tables. -},{}],5:[function(require,module,exports){ -'use strict'; + var mappingTable = codecOptions.table(); // Decode tables: MBCS -> Unicode. + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. -const asn1 = exports; + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. -asn1.bignum = require('bn.js'); + this.decodeTableSeq = []; // Actual mapping tables consist of chunks. Use them to fill up decode tables. -asn1.define = require('./asn1/api').define; -asn1.base = require('./asn1/base'); -asn1.constants = require('./asn1/constants'); -asn1.decoders = require('./asn1/decoders'); -asn1.encoders = require('./asn1/encoders'); + for (var i = 0; i < mappingTable.length; i++) { + this._addDecodeChunk(mappingTable[i]); + } -},{"./asn1/api":6,"./asn1/base":8,"./asn1/constants":12,"./asn1/decoders":14,"./asn1/encoders":17,"bn.js":125}],6:[function(require,module,exports){ -'use strict'; + this.defaultCharUnicode = iconv.defaultCharUnicode; // Encode tables: Unicode -> DBCS. + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. -const asn1 = require('../asn1'); -const inherits = require('inherits'); + this.encodeTable = []; // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. -const api = exports; + this.encodeTableSeq = []; // Some chars can be decoded, but need not be encoded. -api.define = function define(name, body) { - return new Entity(name, body); -}; + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') skipEncodeChars[val] = true;else for (var j = val.from; j <= val.to; j++) { + skipEncodeChars[j] = true; + } + } // Use decode trie to recursively fill out encode tables. -function Entity(name, body) { - this.name = name; - this.body = body; + this._fillEncodeTable(0, 0, skipEncodeChars); // Add more encoding pairs when needed. - this.decoders = {}; - this.encoders = {}; -} -Entity.prototype._createNamed = function createNamed(base) { - let named; - try { - named = require('vm').runInThisContext( - '(function ' + this.name + '(entity) {\n' + - ' this._initNamed(entity);\n' + - '})' - ); - } catch (e) { - named = function (entity) { - this._initNamed(entity); - }; + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) { + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } } - inherits(named, base); - named.prototype._initNamed = function initnamed(entity) { - base.call(this, entity); - }; - return new named(this); -}; - -Entity.prototype._getDecoder = function _getDecoder(enc) { - enc = enc || 'der'; - // Lazily create decoder - if (!this.decoders.hasOwnProperty(enc)) - this.decoders[enc] = this._createNamed(asn1.decoders[enc]); - return this.decoders[enc]; -}; + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); // Load & create GB18030 tables when needed. -Entity.prototype.decode = function decode(data, enc, options) { - return this._getDecoder(enc).decode(data, options); -}; + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + // Add GB18030 decode tables. -Entity.prototype._getEncoder = function _getEncoder(enc) { - enc = enc || 'der'; - // Lazily create encoder - if (!this.encoders.hasOwnProperty(enc)) - this.encoders[enc] = this._createNamed(asn1.encoders[enc]); - return this.encoders[enc]; -}; + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); -Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { - return this._getEncoder(enc).encode(data, reporter); -}; + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; -},{"../asn1":5,"inherits":401,"vm":undefined}],7:[function(require,module,exports){ -'use strict'; + for (var j = 0x30; j <= 0x39; j++) { + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + } -const inherits = require('inherits'); -const Reporter = require('../base').Reporter; -const Buffer = require('buffer').Buffer; + for (var i = 0x81; i <= 0xFE; i++) { + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + } -function DecoderBuffer(base, options) { - Reporter.call(this, options); - if (!Buffer.isBuffer(base)) { - this.error('Input not Buffer'); - return; + for (var i = 0x30; i <= 0x39; i++) { + fourthByteNode[i] = GB18030_CODE; + } } - - this.base = base; - this.offset = 0; - this.length = base.length; } -inherits(DecoderBuffer, Reporter); -exports.DecoderBuffer = DecoderBuffer; - -DecoderBuffer.prototype.save = function save() { - return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; -}; - -DecoderBuffer.prototype.restore = function restore(save) { - // Return skipped data - const res = new DecoderBuffer(this.base); - res.offset = save.offset; - res.length = this.offset; - - this.offset = save.offset; - Reporter.prototype.restore.call(this, save.reporter); - - return res; -}; - -DecoderBuffer.prototype.isEmpty = function isEmpty() { - return this.offset === this.length; -}; - -DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { - if (this.offset + 1 <= this.length) - return this.base.readUInt8(this.offset++, true); - else - return this.error(fail || 'DecoderBuffer overrun'); -}; - -DecoderBuffer.prototype.skip = function skip(bytes, fail) { - if (!(this.offset + bytes <= this.length)) - return this.error(fail || 'DecoderBuffer overrun'); - const res = new DecoderBuffer(this.base); - - // Share reporter state - res._reporterState = this._reporterState; - - res.offset = this.offset; - res.length = this.offset + bytes; - this.offset += bytes; - return res; -}; +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; // Decoder helpers -DecoderBuffer.prototype.raw = function raw(save) { - return this.base.slice(save ? save.offset : this.offset, this.length); -}; +DBCSCodec.prototype._getDecodeTrieNode = function (addr) { + var bytes = []; -function EncoderBuffer(value, reporter) { - if (Array.isArray(value)) { - this.length = 0; - this.value = value.map(function(item) { - if (!(item instanceof EncoderBuffer)) - item = new EncoderBuffer(item, reporter); - this.length += item.length; - return item; - }, this); - } else if (typeof value === 'number') { - if (!(0 <= value && value <= 0xff)) - return reporter.error('non-byte EncoderBuffer value'); - this.value = value; - this.length = 1; - } else if (typeof value === 'string') { - this.value = value; - this.length = Buffer.byteLength(value); - } else if (Buffer.isBuffer(value)) { - this.value = value; - this.length = value.length; - } else { - return reporter.error('Unsupported type: ' + typeof value); + for (; addr > 0; addr >>= 8) { + bytes.push(addr & 0xFF); } -} -exports.EncoderBuffer = EncoderBuffer; -EncoderBuffer.prototype.join = function join(out, offset) { - if (!out) - out = new Buffer(this.length); - if (!offset) - offset = 0; + if (bytes.length == 0) bytes.push(0); + var node = this.decodeTables[0]; - if (this.length === 0) - return out; + for (var i = bytes.length - 1; i > 0; i--) { + // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; - if (Array.isArray(this.value)) { - this.value.forEach(function(item) { - item.join(out, offset); - offset += item.length; - }); - } else { - if (typeof this.value === 'number') - out[offset] = this.value; - else if (typeof this.value === 'string') - out.write(this.value, offset); - else if (Buffer.isBuffer(this.value)) - this.value.copy(out, offset); - offset += this.length; + if (val == UNASSIGNED) { + // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } else if (val <= NODE_START) { + // Existing node. + node = this.decodeTables[NODE_START - val]; + } else throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); } - return out; + return node; }; -},{"../base":8,"buffer":undefined,"inherits":401}],8:[function(require,module,exports){ -'use strict'; - -const base = exports; - -base.Reporter = require('./reporter').Reporter; -base.DecoderBuffer = require('./buffer').DecoderBuffer; -base.EncoderBuffer = require('./buffer').EncoderBuffer; -base.Node = require('./node'); - -},{"./buffer":7,"./node":9,"./reporter":10}],9:[function(require,module,exports){ -'use strict'; +DBCSCodec.prototype._addDecodeChunk = function (chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); // Choose the decoding node where we'll write our chars. -const Reporter = require('../base').Reporter; -const EncoderBuffer = require('../base').EncoderBuffer; -const DecoderBuffer = require('../base').DecoderBuffer; -const assert = require('minimalistic-assert'); + var writeTable = this._getDecodeTrieNode(curAddr); -// Supported tags -const tags = [ - 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', - 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', - 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', - 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' -]; + curAddr = curAddr & 0xFF; // Write all other elements of the chunk to the table. -// Public methods list -const methods = [ - 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', - 'any', 'contains' -].concat(tags); + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; -// Overrided methods list -const overrided = [ - '_peekTag', '_decodeTag', '_use', - '_decodeStr', '_decodeObjid', '_decodeTime', - '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + if (typeof part === "string") { + // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); - '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', - '_encodeNull', '_encodeInt', '_encodeBool' -]; + if (0xD800 <= code && code < 0xDC00) { + // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);else throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } else if (0x0FF0 < code && code <= 0x0FFF) { + // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; -function Node(enc, parent) { - const state = {}; - this._baseState = state; + for (var m = 0; m < len; m++) { + seq.push(part.charCodeAt(l++)); + } // Simple variation: don't support surrogates or subsequences in seq. - state.enc = enc; - state.parent = parent || null; - state.children = null; + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } else writeTable[curAddr++] = code; // Basic char - // State - state.tag = null; - state.args = null; - state.reverseArgs = null; - state.choice = null; - state.optional = false; - state.any = false; - state.obj = false; - state.use = null; - state.useDecoder = null; - state.key = null; - state['default'] = null; - state.explicit = null; - state.implicit = null; - state.contains = null; + } + } else if (typeof part === "number") { + // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; - // Should create new instance on each method - if (!state.parent) { - state.children = []; - this._wrap(); + for (var l = 0; l < part; l++) { + writeTable[curAddr++] = charCode++; + } + } else throw new Error("Incorrect type '" + _typeof(part) + "' given in " + this.encodingName + " at chunk " + chunk[0]); } -} -module.exports = Node; - -const stateProps = [ - 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', - 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', - 'implicit', 'contains' -]; -Node.prototype.clone = function clone() { - const state = this._baseState; - const cstate = {}; - stateProps.forEach(function(prop) { - cstate[prop] = state[prop]; - }); - const res = new this.constructor(cstate.parent); - res._baseState = cstate; - return res; -}; + if (curAddr > 0xFF) throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +}; // Encoder helpers -Node.prototype._wrap = function wrap() { - const state = this._baseState; - methods.forEach(function(method) { - this[method] = function _wrappedMethod() { - const clone = new this.constructor(this); - state.children.push(clone); - return clone[method].apply(clone, arguments); - }; - }, this); -}; -Node.prototype._init = function init(body) { - const state = this._baseState; +DBCSCodec.prototype._getEncodeBucket = function (uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. - assert(state.parent === null); - body.call(this); + if (this.encodeTable[high] === undefined) this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - // Filter children - state.children = state.children.filter(function(child) { - return child._baseState.parent === this; - }, this); - assert.equal(state.children.length, 1, 'Root node can have only one child'); + return this.encodeTable[high]; }; -Node.prototype._useArgs = function useArgs(args) { - const state = this._baseState; - - // Filter children and args - const children = args.filter(function(arg) { - return arg instanceof this.constructor; - }, this); - args = args.filter(function(arg) { - return !(arg instanceof this.constructor); - }, this); - - if (children.length !== 0) { - assert(state.children === null); - state.children = children; +DBCSCodec.prototype._setEncodeChar = function (uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); - // Replace parent to maintain backward link - children.forEach(function(child) { - child._baseState.parent = this; - }, this); - } - if (args.length !== 0) { - assert(state.args === null); - state.args = args; - state.reverseArgs = args.map(function(arg) { - if (typeof arg !== 'object' || arg.constructor !== Object) - return arg; - - const res = {}; - Object.keys(arg).forEach(function(key) { - if (key == (key | 0)) - key |= 0; - const value = arg[key]; - res[value] = key; - }); - return res; - }); - } + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) this.encodeTableSeq[SEQ_START - bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) bucket[low] = dbcsCode; }; -// -// Overrided methods -// - -overrided.forEach(function(method) { - Node.prototype[method] = function _overrided() { - const state = this._baseState; - throw new Error(method + ' not implemented for encoding: ' + state.enc); - }; -}); - -// -// Public methods -// - -tags.forEach(function(tag) { - Node.prototype[tag] = function _tagMethod() { - const state = this._baseState; - const args = Array.prototype.slice.call(arguments); - - assert(state.tag === null); - state.tag = tag; - - this._useArgs(args); - - return this; - }; -}); - -Node.prototype.use = function use(item) { - assert(item); - const state = this._baseState; +DBCSCodec.prototype._setEncodeSequence = function (seq, dbcsCode) { + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; - assert(state.use === null); - state.use = item; + var bucket = this._getEncodeBucket(uCode); - return this; -}; + var low = uCode & 0xFF; + var node; -Node.prototype.optional = function optional() { - const state = this._baseState; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START - bucket[low]]; + } else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - state.optional = true; + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } // Traverse the character tree, allocating new nodes as needed. - return this; -}; -Node.prototype.def = function def(val) { - const state = this._baseState; + for (var j = 1; j < seq.length - 1; j++) { + var oldVal = node[uCode]; + if (_typeof(oldVal) === 'object') node = oldVal;else { + node = node[uCode] = {}; + if (oldVal !== undefined) node[DEF_CHAR] = oldVal; + } + } // Set the leaf to given dbcsCode. - assert(state['default'] === null); - state['default'] = val; - state.optional = true; - return this; + uCode = seq[seq.length - 1]; + node[uCode] = dbcsCode; }; -Node.prototype.explicit = function explicit(num) { - const state = this._baseState; +DBCSCodec.prototype._fillEncodeTable = function (nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; - assert(state.explicit === null && state.implicit === null); - state.explicit = num; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) continue; + if (uCode >= 0) this._setEncodeChar(uCode, mbCode);else if (uCode <= NODE_START) this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);else if (uCode <= SEQ_START) this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +}; // == Encoder ================================================================== - return this; -}; -Node.prototype.implicit = function implicit(num) { - const state = this._baseState; +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; // Static data + + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function (str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, + nextChar = -1, + i = 0, + j = 0; - assert(state.explicit === null && state.implicit === null); - state.implicit = num; + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } else { + var uCode = nextChar; + nextChar = -1; + } // 1. Handle surrogates. - return this; -}; -Node.prototype.obj = function obj() { - const state = this._baseState; - const args = Array.prototype.slice.call(arguments); + if (0xD800 <= uCode && uCode < 0xE000) { + // Char is one of surrogates. + if (uCode < 0xDC00) { + // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; // Double lead surrogate found. - state.obj = true; + uCode = UNASSIGNED; + } + } else { + // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + } + } else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; + uCode = UNASSIGNED; // Write an error, then current char. - if (args.length !== 0) - this._useArgs(args); + leadSurrogate = -1; + } // 2. Convert uCode character. - return this; -}; -Node.prototype.key = function key(newKey) { - const state = this._baseState; + var dbcsCode = UNASSIGNED; - assert(state.key === null); - state.key = newKey; + if (seqObj !== undefined && uCode != UNASSIGNED) { + // We are in the middle of the sequence + var resCode = seqObj[uCode]; - return this; -}; + if (_typeof(resCode) === 'object') { + // Sequence continues. + seqObj = resCode; + continue; + } else if (typeof resCode == 'number') { + // Sequence finished. Write it. + dbcsCode = resCode; + } else if (resCode == undefined) { + // Current character is not part of the sequence. + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + + nextChar = uCode; // Current character will be written too in the next iteration. + } else {// TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } -Node.prototype.any = function any() { - const state = this._baseState; + seqObj = undefined; + } else if (uCode >= 0) { + // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) dbcsCode = subtable[uCode & 0xFF]; - state.any = true; + if (dbcsCode <= SEQ_START) { + // Sequence start + seqObj = this.encodeTableSeq[SEQ_START - dbcsCode]; + continue; + } - return this; -}; + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); -Node.prototype.choice = function choice(obj) { - const state = this._baseState; + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); + dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); + dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); + dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } // 3. Write dbcsCode character. - assert(state.choice === null); - state.choice = obj; - this._useArgs(Object.keys(obj).map(function(key) { - return obj[key]; - })); - return this; -}; + if (dbcsCode === UNASSIGNED) dbcsCode = this.defaultCharSingleByte; -Node.prototype.contains = function contains(item) { - const state = this._baseState; + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte - assert(state.use === null); - state.contains = item; + newBuf[j++] = dbcsCode & 0xFF; // low byte + } else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = dbcsCode >> 8 & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } - return this; + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); }; -// -// Decoding -// - -Node.prototype._decode = function decode(input, options) { - const state = this._baseState; - - // Decode root node - if (state.parent === null) - return input.wrapResult(state.children[0]._decode(input, options)); +DBCSEncoder.prototype.end = function () { + if (this.leadSurrogate === -1 && this.seqObj === undefined) return; // All clean. Most often case. - let result = state['default']; - let present = true; + var newBuf = Buffer.alloc(10), + j = 0; - let prevKey = null; - if (state.key !== null) - prevKey = input.enterKey(state.key); + if (this.seqObj) { + // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; - // Check if tag is there - if (state.optional) { - let tag = null; - if (state.explicit !== null) - tag = state.explicit; - else if (state.implicit !== null) - tag = state.implicit; - else if (state.tag !== null) - tag = state.tag; + if (dbcsCode !== undefined) { + // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } else { + newBuf[j++] = dbcsCode >> 8; // high byte - if (tag === null && !state.any) { - // Trial and Error - const save = input.save(); - try { - if (state.choice === null) - this._decodeGeneric(state.tag, input, options); - else - this._decodeChoice(input, options); - present = true; - } catch (e) { - present = false; + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else {// See todo above. } - input.restore(save); - } else { - present = this._peekTag(input, tag, state.any); - if (input.isError(present)) - return present; - } + this.seqObj = undefined; } - // Push object on stack - let prevObj; - if (state.obj && present) - prevObj = input.enterObject(); - - if (present) { - // Unwrap explicit values - if (state.explicit !== null) { - const explicit = this._decodeTag(input, state.explicit); - if (input.isError(explicit)) - return explicit; - input = explicit; - } - - const start = input.offset; + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } - // Unwrap implicit and normal values - if (state.use === null && state.choice === null) { - let save; - if (state.any) - save = input.save(); - const body = this._decodeTag( - input, - state.implicit !== null ? state.implicit : state.tag, - state.any - ); - if (input.isError(body)) - return body; + return newBuf.slice(0, j); +}; // Export for testing - if (state.any) - result = input.raw(save); - else - input = body; - } - if (options && options.track && state.tag !== null) - options.track(input.path(), start, input.length, 'tagged'); +DBCSEncoder.prototype.findIdx = findIdx; // == Decoder ================================================================== - if (options && options.track && state.tag !== null) - options.track(input.path(), input.offset, input.length, 'content'); +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); // Static data + + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function (buf) { + var newBuf = Buffer.alloc(buf.length * 2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, + prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, + // idx of the start of current parsed sequence. + uCode; + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = i >= 0 ? buf[i] : prevBuf[i + prevBufOffset]; // Lookup in current trie node. + + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) {// Normal character, just use it. + } else if (uCode === UNASSIGNED) { + // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + + uCode = this.defaultCharUnicode.charCodeAt(0); + } else if (uCode === GB18030_CODE) { + var curSeq = seqStart >= 0 ? buf.slice(seqStart, i + 1) : prevBuf.slice(seqStart + prevBufOffset, i + 1 + prevBufOffset); + var ptr = (curSeq[0] - 0x81) * 12600 + (curSeq[1] - 0x30) * 1260 + (curSeq[2] - 0x81) * 10 + (curSeq[3] - 0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } else if (uCode <= NODE_START) { + // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } else if (uCode <= SEQ_START) { + // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; - // Select proper method for tag - if (state.any) { - // no-op - } else if (state.choice === null) { - result = this._decodeGeneric(state.tag, input, options); - } else { - result = this._decodeChoice(input, options); - } + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } - if (input.isError(result)) - return result; + uCode = seq[seq.length - 1]; + } else throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); // Write the character to buffer, handling higher planes using surrogate pair. - // Decode children - if (!state.any && state.choice === null && state.children !== null) { - state.children.forEach(function decodeChildren(child) { - // NOTE: We are ignoring errors here, to let parser continue with other - // parts of encoded data - child._decode(input, options); - }); - } - // Decode contained/encoded by schema, only in bit or octet strings - if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { - const data = new DecoderBuffer(result); - result = this._getUse(state.contains, input._reporterState.obj) - ._decode(data, options); + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + uCode = 0xDC00 + uCode % 0x400; } - } - - // Pop object - if (state.obj && present) - result = input.leaveObject(prevObj); - // Set key - if (state.key !== null && (result !== null || present === true)) - input.leaveKey(prevKey, state.key, result); - else if (prevKey !== null) - input.exitKey(prevKey); + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; // Reset trie node. - return result; -}; - -Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { - const state = this._baseState; - - if (tag === 'seq' || tag === 'set') - return null; - if (tag === 'seqof' || tag === 'setof') - return this._decodeList(input, tag, state.args[0], options); - else if (/str$/.test(tag)) - return this._decodeStr(input, tag, options); - else if (tag === 'objid' && state.args) - return this._decodeObjid(input, state.args[0], state.args[1], options); - else if (tag === 'objid') - return this._decodeObjid(input, null, null, options); - else if (tag === 'gentime' || tag === 'utctime') - return this._decodeTime(input, tag, options); - else if (tag === 'null_') - return this._decodeNull(input, options); - else if (tag === 'bool') - return this._decodeBool(input, options); - else if (tag === 'objDesc') - return this._decodeStr(input, tag, options); - else if (tag === 'int' || tag === 'enum') - return this._decodeInt(input, state.args && state.args[0], options); - - if (state.use !== null) { - return this._getUse(state.use, input._reporterState.obj) - ._decode(input, options); - } else { - return input.error('unknown tag: ' + tag); + nodeIdx = 0; + seqStart = i + 1; } -}; - -Node.prototype._getUse = function _getUse(entity, obj) { - const state = this._baseState; - // Create altered use decoder if implicit is set - state.useDecoder = this._use(entity, obj); - assert(state.useDecoder._baseState.parent === null); - state.useDecoder = state.useDecoder._baseState.children[0]; - if (state.implicit !== state.useDecoder._baseState.implicit) { - state.useDecoder = state.useDecoder.clone(); - state.useDecoder._baseState.implicit = state.implicit; - } - return state.useDecoder; + this.nodeIdx = nodeIdx; + this.prevBuf = seqStart >= 0 ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); }; -Node.prototype._decodeChoice = function decodeChoice(input, options) { - const state = this._baseState; - let result = null; - let match = false; - - Object.keys(state.choice).some(function(key) { - const save = input.save(); - const node = state.choice[key]; - try { - const value = node._decode(input, options); - if (input.isError(value)) - return false; +DBCSDecoder.prototype.end = function () { + var ret = ''; // Try to parse all remaining chars. - result = { type: key, value: value }; - match = true; - } catch (e) { - input.restore(save); - return false; - } - return true; - }, this); + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); // Parse remaining as usual. - if (!match) - return input.error('Choice not matched'); + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) ret += this.write(buf); + } - return result; -}; + this.nodeIdx = 0; + return ret; +}; // Binary search for GB18030. Returns largest i such that table[i] <= val. -// -// Encoding -// -Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { - return new EncoderBuffer(data, this.reporter); -}; +function findIdx(table, val) { + if (table[0] > val) return -1; + var l = 0, + r = table.length; -Node.prototype._encode = function encode(data, reporter, parent) { - const state = this._baseState; - if (state['default'] !== null && state['default'] === data) - return; + while (l < r - 1) { + // always table[l] <= val < table[r] + var mid = l + Math.floor((r - l + 1) / 2); + if (table[mid] <= val) l = mid;else r = mid; + } - const result = this._encodeValue(data, reporter, parent); - if (result === undefined) - return; + return l; +} - if (this._skipDefault(result, reporter, parent)) - return; +},{"safer-buffer":24}],4:[function(require,module,exports){ +"use strict"; // Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. - return result; +module.exports = { + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + 'shiftjis': { + type: '_dbcs', + table: function table() { + return require('./tables/shiftjis.json'); + }, + encodeAdd: { + "\xA5": 0x5C, + "\u203E": 0x7E + }, + encodeSkipVals: [{ + from: 0xED40, + to: 0xF940 + }] + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + 'eucjp': { + type: '_dbcs', + table: function table() { + return require('./tables/eucjp.json'); + }, + encodeAdd: { + "\xA5": 0x5C, + "\u203E": 0x7E + } + }, + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function table() { + return require('./tables/cp936.json'); + } + }, + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function table() { + return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')); + } + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function table() { + return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')); + }, + gb18030: function gb18030() { + return require('./tables/gb18030-ranges.json'); + }, + encodeSkipVals: [0x80], + encodeAdd: { + '€': 0xA2E3 + } + }, + 'chinese': 'gb18030', + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function table() { + return require('./tables/cp949.json'); + } + }, + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function table() { + return require('./tables/cp950.json'); + } + }, + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function table() { + return require('./tables/cp950.json').concat(require('./tables/big5-added.json')); + }, + encodeSkipVals: [0xa2cc] + }, + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs' }; -Node.prototype._encodeValue = function encode(data, reporter, parent) { - const state = this._baseState; - - // Decode root node - if (state.parent === null) - return state.children[0]._encode(data, reporter || new Reporter()); +},{"./tables/big5-added.json":10,"./tables/cp936.json":11,"./tables/cp949.json":12,"./tables/cp950.json":13,"./tables/eucjp.json":14,"./tables/gb18030-ranges.json":15,"./tables/gbk-added.json":16,"./tables/shiftjis.json":17}],5:[function(require,module,exports){ +"use strict"; // Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. - let result = null; +var modules = [require("./internal"), require("./utf16"), require("./utf7"), require("./sbcs-codec"), require("./sbcs-data"), require("./sbcs-data-generated"), require("./dbcs-codec"), require("./dbcs-data")]; // Put all encoding/alias/codec definitions to single object and export it. - // Set reporter to share it with a child class - this.reporter = reporter; +for (var i = 0; i < modules.length; i++) { + var _module = modules[i]; - // Check if data is there - if (state.optional && data === undefined) { - if (state['default'] !== null) - data = state['default']; - else - return; + for (var enc in _module) { + if (Object.prototype.hasOwnProperty.call(_module, enc)) exports[enc] = _module[enc]; } +} - // Encode children first - let content = null; - let primitive = false; - if (state.any) { - // Anything that was given is translated to buffer - result = this._createEncoderBuffer(data); - } else if (state.choice) { - result = this._encodeChoice(data, reporter); - } else if (state.contains) { - content = this._getUse(state.contains, parent)._encode(data, reporter); - primitive = true; - } else if (state.children) { - content = state.children.map(function(child) { - if (child._baseState.tag === 'null_') - return child._encode(null, reporter, data); - - if (child._baseState.key === null) - return reporter.error('Child should have a key'); - const prevKey = reporter.enterKey(child._baseState.key); - - if (typeof data !== 'object') - return reporter.error('Child expected, but input is not object'); - - const res = child._encode(data[child._baseState.key], reporter, data); - reporter.leaveKey(prevKey); +},{"./dbcs-codec":3,"./dbcs-data":4,"./internal":6,"./sbcs-codec":7,"./sbcs-data":9,"./sbcs-data-generated":8,"./utf16":18,"./utf7":19}],6:[function(require,module,exports){ +"use strict"; - return res; - }, this).filter(function(child) { - return child; - }); - content = this._createEncoderBuffer(content); - } else { - if (state.tag === 'seqof' || state.tag === 'setof') { - // TODO(indutny): this should be thrown on DSL level - if (!(state.args && state.args.length === 1)) - return reporter.error('Too many args for : ' + state.tag); +var Buffer = require("safer-buffer").Buffer; // Export Node.js internal encodings. - if (!Array.isArray(data)) - return reporter.error('seqof/setof, but data is not Array'); - const child = this.clone(); - child._baseState.implicit = null; - content = this._createEncoderBuffer(data.map(function(item) { - const state = this._baseState; +module.exports = { + // Encodings + utf8: { + type: "_internal", + bomAware: true + }, + cesu8: { + type: "_internal", + bomAware: true + }, + unicode11utf8: "utf8", + ucs2: { + type: "_internal", + bomAware: true + }, + utf16le: "ucs2", + binary: { + type: "_internal" + }, + base64: { + type: "_internal" + }, + hex: { + type: "_internal" + }, + // Codec. + _internal: InternalCodec +}; //------------------------------------------------------------------------------ - return this._getUse(state.args[0], data)._encode(item, reporter); - }, child)); - } else if (state.use !== null) { - result = this._getUse(state.use, parent)._encode(data, reporter); - } else { - content = this._encodePrimitive(state.tag, data); - primitive = true; - } - } +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + if (this.enc === "base64") this.encoder = InternalEncoderBase64;else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. - // Encode data itself - if (!state.any && state.choice === null) { - const tag = state.implicit !== null ? state.implicit : state.tag; - const cls = state.implicit === null ? 'universal' : 'context'; + this.encoder = InternalEncoderCesu8; // Add decoder for versions of Node not supporting CESU-8 - if (tag === null) { - if (state.use === null) - reporter.error('Tag could be omitted only for .use()'); - } else { - if (state.use === null) - result = this._encodeComposite(tag, primitive, cls, content); + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; } } +} - // Wrap in explicit - if (state.explicit !== null) - result = this._encodeComposite(state.explicit, false, 'context', result); - - return result; -}; - -Node.prototype._encodeChoice = function encodeChoice(data, reporter) { - const state = this._baseState; - - const node = state.choice[data.type]; - if (!node) { - assert( - false, - data.type + ' not found in ' + - JSON.stringify(Object.keys(state.choice))); - } - return node._encode(data.value, reporter); -}; - -Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { - const state = this._baseState; - - if (/str$/.test(tag)) - return this._encodeStr(data, tag); - else if (tag === 'objid' && state.args) - return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); - else if (tag === 'objid') - return this._encodeObjid(data, null, null); - else if (tag === 'gentime' || tag === 'utctime') - return this._encodeTime(data, tag); - else if (tag === 'null_') - return this._encodeNull(); - else if (tag === 'int' || tag === 'enum') - return this._encodeInt(data, state.args && state.reverseArgs[0]); - else if (tag === 'bool') - return this._encodeBool(data); - else if (tag === 'objDesc') - return this._encodeStr(data, tag); - else - throw new Error('Unsupported tag: ' + tag); -}; - -Node.prototype._isNumstr = function isNumstr(str) { - return /^[0-9 ]*$/.test(str); -}; - -Node.prototype._isPrintstr = function isPrintstr(str) { - return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); -}; +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; //------------------------------------------------------------------------------ +// We use node.js internal decoder. Its signature is the same as ours. -},{"../base":8,"minimalistic-assert":955}],10:[function(require,module,exports){ -'use strict'; +var StringDecoder = require('string_decoder').StringDecoder; -const inherits = require('inherits'); +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function () {}; -function Reporter(options) { - this._reporterState = { - obj: null, - path: [], - options: options || {}, - errors: [] - }; +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); } -exports.Reporter = Reporter; - -Reporter.prototype.isError = function isError(obj) { - return obj instanceof ReporterError; -}; - -Reporter.prototype.save = function save() { - const state = this._reporterState; - - return { obj: state.obj, pathLen: state.path.length }; -}; -Reporter.prototype.restore = function restore(data) { - const state = this._reporterState; +InternalDecoder.prototype = StringDecoder.prototype; //------------------------------------------------------------------------------ +// Encoder is mostly trivial - state.obj = data.obj; - state.path = state.path.slice(0, data.pathLen); -}; +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} -Reporter.prototype.enterKey = function enterKey(key) { - return this._reporterState.path.push(key); +InternalEncoder.prototype.write = function (str) { + return Buffer.from(str, this.enc); }; -Reporter.prototype.exitKey = function exitKey(index) { - const state = this._reporterState; - - state.path = state.path.slice(0, index - 1); -}; +InternalEncoder.prototype.end = function () {}; //------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. -Reporter.prototype.leaveKey = function leaveKey(index, key, value) { - const state = this._reporterState; - this.exitKey(index); - if (state.obj !== null) - state.obj[key] = value; -}; +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} -Reporter.prototype.path = function path() { - return this._reporterState.path.join('/'); +InternalEncoderBase64.prototype.write = function (str) { + str = this.prevStr + str; + var completeQuads = str.length - str.length % 4; + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + return Buffer.from(str, "base64"); }; -Reporter.prototype.enterObject = function enterObject() { - const state = this._reporterState; +InternalEncoderBase64.prototype.end = function () { + return Buffer.from(this.prevStr, "base64"); +}; //------------------------------------------------------------------------------ +// CESU-8 encoder is also special. - const prev = state.obj; - state.obj = {}; - return prev; -}; -Reporter.prototype.leaveObject = function leaveObject(prev) { - const state = this._reporterState; +function InternalEncoderCesu8(options, codec) {} - const now = state.obj; - state.obj = prev; - return now; -}; +InternalEncoderCesu8.prototype.write = function (str) { + var buf = Buffer.alloc(str.length * 3), + bufIdx = 0; -Reporter.prototype.error = function error(msg) { - let err; - const state = this._reporterState; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). - const inherited = msg instanceof ReporterError; - if (inherited) { - err = msg; - } else { - err = new ReporterError(state.path.map(function(elem) { - return '[' + JSON.stringify(elem) + ']'; - }).join(''), msg.message || msg, msg.stack); + if (charCode < 0x80) buf[bufIdx++] = charCode;else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } else { + // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + (charCode >>> 6 & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } } - if (!state.options.partial) - throw err; - - if (!inherited) - state.errors.push(err); - - return err; + return buf.slice(0, bufIdx); }; -Reporter.prototype.wrapResult = function wrapResult(result) { - const state = this._reporterState; - if (!state.options.partial) - return result; +InternalEncoderCesu8.prototype.end = function () {}; //------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ - return { - result: this.isError(result) ? null : result, - errors: state.errors - }; -}; -function ReporterError(path, msg) { - this.path = path; - this.rethrow(msg); +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; } -inherits(ReporterError, Error); -ReporterError.prototype.rethrow = function rethrow(msg) { - this.message = msg + ' at: ' + (this.path || '(shallow)'); - if (Error.captureStackTrace) - Error.captureStackTrace(this, ReporterError); +InternalDecoderCesu8.prototype.write = function (buf) { + var acc = this.acc, + contBytes = this.contBytes, + accBytes = this.accBytes, + res = ''; - if (!this.stack) { - try { - // IE only adds stack when thrown - throw new Error(this.message); - } catch (e) { - this.stack = e.stack; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + + if ((curByte & 0xC0) !== 0x80) { + // Leading byte + if (contBytes > 0) { + // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { + // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { + // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; + accBytes = 1; + } else if (curByte < 0xF0) { + // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; + accBytes = 1; + } else { + // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { + // Continuation byte + if (contBytes > 0) { + // We're waiting for it. + acc = acc << 6 | curByte & 0x3f; + contBytes--; + accBytes++; + + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) res += this.defaultCharUnicode;else if (accBytes === 3 && acc < 0x800) res += this.defaultCharUnicode;else // Actually add character. + res += String.fromCharCode(acc); + } + } else { + // Unexpected continuation byte + res += this.defaultCharUnicode; + } } } - return this; -}; - -},{"inherits":401}],11:[function(require,module,exports){ -'use strict'; - -const constants = require('../constants'); - -exports.tagClass = { - 0: 'universal', - 1: 'application', - 2: 'context', - 3: 'private' -}; -exports.tagClassByName = constants._reverse(exports.tagClass); - -exports.tag = { - 0x00: 'end', - 0x01: 'bool', - 0x02: 'int', - 0x03: 'bitstr', - 0x04: 'octstr', - 0x05: 'null_', - 0x06: 'objid', - 0x07: 'objDesc', - 0x08: 'external', - 0x09: 'real', - 0x0a: 'enum', - 0x0b: 'embed', - 0x0c: 'utf8str', - 0x0d: 'relativeOid', - 0x10: 'seq', - 0x11: 'set', - 0x12: 'numstr', - 0x13: 'printstr', - 0x14: 't61str', - 0x15: 'videostr', - 0x16: 'ia5str', - 0x17: 'utctime', - 0x18: 'gentime', - 0x19: 'graphstr', - 0x1a: 'iso646str', - 0x1b: 'genstr', - 0x1c: 'unistr', - 0x1d: 'charstr', - 0x1e: 'bmpstr' -}; -exports.tagByName = constants._reverse(exports.tag); - -},{"../constants":12}],12:[function(require,module,exports){ -'use strict'; - -const constants = exports; - -// Helper -constants._reverse = function reverse(map) { - const res = {}; - - Object.keys(map).forEach(function(key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) - key = key | 0; - - const value = map[key]; - res[value] = key; - }); + this.acc = acc; + this.contBytes = contBytes; + this.accBytes = accBytes; return res; }; -constants.der = require('./der'); - -},{"./der":11}],13:[function(require,module,exports){ -'use strict'; - -const inherits = require('inherits'); - -const asn1 = require('../../asn1'); -const base = asn1.base; -const bignum = asn1.bignum; - -// Import DER constants -const der = asn1.constants.der; - -function DERDecoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -} -module.exports = DERDecoder; - -DERDecoder.prototype.decode = function decode(data, options) { - if (!(data instanceof base.DecoderBuffer)) - data = new base.DecoderBuffer(data, options); - - return this.tree._decode(data, options); -}; - -// Tree methods - -function DERNode(parent) { - base.Node.call(this, 'der', parent); -} -inherits(DERNode, base.Node); - -DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { - if (buffer.isEmpty()) - return false; - - const state = buffer.save(); - const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - buffer.restore(state); - - return decodedTag.tag === tag || decodedTag.tagStr === tag || - (decodedTag.tagStr + 'of') === tag || any; +InternalDecoderCesu8.prototype.end = function () { + var res = 0; + if (this.contBytes > 0) res += this.defaultCharUnicode; + return res; }; -DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { - const decodedTag = derDecodeTag(buffer, - 'Failed to decode tag of "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - let len = derDecodeLen(buffer, - decodedTag.primitive, - 'Failed to get length of "' + tag + '"'); - - // Failure - if (buffer.isError(len)) - return len; - - if (!any && - decodedTag.tag !== tag && - decodedTag.tagStr !== tag && - decodedTag.tagStr + 'of' !== tag) { - return buffer.error('Failed to match tag: "' + tag + '"'); - } - - if (decodedTag.primitive || len !== null) - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); - - // Indefinite length... find END tag - const state = buffer.save(); - const res = this._skipUntilEnd( - buffer, - 'Failed to skip indefinite length body: "' + this.tag + '"'); - if (buffer.isError(res)) - return res; +},{"safer-buffer":24,"string_decoder":undefined}],7:[function(require,module,exports){ +"use strict"; - len = buffer.offset - state.offset; - buffer.restore(state); - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); -}; +var Buffer = require("safer-buffer").Buffer; // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). -DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { - for (;;) { - const tag = derDecodeTag(buffer, fail); - if (buffer.isError(tag)) - return tag; - const len = derDecodeLen(buffer, tag.primitive, fail); - if (buffer.isError(len)) - return len; - - let res; - if (tag.primitive || len !== null) - res = buffer.skip(len); - else - res = this._skipUntilEnd(buffer, fail); - - // Failure - if (buffer.isError(res)) - return res; - if (tag.tagStr === 'end') - break; - } -}; +exports._sbcs = SBCSCodec; -DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, - options) { - const result = []; - while (!buffer.isEmpty()) { - const possibleEnd = this._peekTag(buffer, 'end'); - if (buffer.isError(possibleEnd)) - return possibleEnd; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) throw new Error("SBCS codec is called without the data."); // Prepare char buffer for decoding. - const res = decoder.decode(buffer, 'der', options); - if (buffer.isError(res) && possibleEnd) - break; - result.push(res); - } - return result; -}; + if (!codecOptions.chars || codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256) throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)"); -DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { - if (tag === 'bitstr') { - const unused = buffer.readUInt8(); - if (buffer.isError(unused)) - return unused; - return { unused: unused, data: buffer.raw() }; - } else if (tag === 'bmpstr') { - const raw = buffer.raw(); - if (raw.length % 2 === 1) - return buffer.error('Decoding of string type: bmpstr length mismatch'); + if (codecOptions.chars.length === 128) { + var asciiString = ""; - let str = ''; - for (let i = 0; i < raw.length / 2; i++) { - str += String.fromCharCode(raw.readUInt16BE(i * 2)); - } - return str; - } else if (tag === 'numstr') { - const numstr = buffer.raw().toString('ascii'); - if (!this._isNumstr(numstr)) { - return buffer.error('Decoding of string type: ' + - 'numstr unsupported characters'); - } - return numstr; - } else if (tag === 'octstr') { - return buffer.raw(); - } else if (tag === 'objDesc') { - return buffer.raw(); - } else if (tag === 'printstr') { - const printstr = buffer.raw().toString('ascii'); - if (!this._isPrintstr(printstr)) { - return buffer.error('Decoding of string type: ' + - 'printstr unsupported characters'); + for (var i = 0; i < 128; i++) { + asciiString += String.fromCharCode(i); } - return printstr; - } else if (/str$/.test(tag)) { - return buffer.raw().toString(); - } else { - return buffer.error('Decoding of string type: ' + tag + ' unsupported'); - } -}; -DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { - let result; - const identifiers = []; - let ident = 0; - let subident = 0; - while (!buffer.isEmpty()) { - subident = buffer.readUInt8(); - ident <<= 7; - ident |= subident & 0x7f; - if ((subident & 0x80) === 0) { - identifiers.push(ident); - ident = 0; - } + codecOptions.chars = asciiString + codecOptions.chars; } - if (subident & 0x80) - identifiers.push(ident); - - const first = (identifiers[0] / 40) | 0; - const second = identifiers[0] % 40; - if (relative) - result = identifiers; - else - result = [first, second].concat(identifiers.slice(1)); - - if (values) { - let tmp = values[result.join(' ')]; - if (tmp === undefined) - tmp = values[result.join('.')]; - if (tmp !== undefined) - result = tmp; - } + this.decodeBuf = new Buffer.from(codecOptions.chars, 'ucs2'); // Encoding buffer. - return result; -}; + var encodeBuf = new Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); -DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { - const str = buffer.raw().toString(); - - let year; - let mon; - let day; - let hour; - let min; - let sec; - if (tag === 'gentime') { - year = str.slice(0, 4) | 0; - mon = str.slice(4, 6) | 0; - day = str.slice(6, 8) | 0; - hour = str.slice(8, 10) | 0; - min = str.slice(10, 12) | 0; - sec = str.slice(12, 14) | 0; - } else if (tag === 'utctime') { - year = str.slice(0, 2) | 0; - mon = str.slice(2, 4) | 0; - day = str.slice(4, 6) | 0; - hour = str.slice(6, 8) | 0; - min = str.slice(8, 10) | 0; - sec = str.slice(10, 12) | 0; - if (year < 70) - year = 2000 + year; - else - year = 1900 + year; - } else { - return buffer.error('Decoding ' + tag + ' time is not supported yet'); + for (var i = 0; i < codecOptions.chars.length; i++) { + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; } - return Date.UTC(year, mon - 1, day, hour, min, sec, 0); -}; - -DERNode.prototype._decodeNull = function decodeNull() { - return null; -}; + this.encodeBuf = encodeBuf; +} -DERNode.prototype._decodeBool = function decodeBool(buffer) { - const res = buffer.readUInt8(); - if (buffer.isError(res)) - return res; - else - return res !== 0; -}; +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; -DERNode.prototype._decodeInt = function decodeInt(buffer, values) { - // Bigint, return as it is (assume big endian) - const raw = buffer.raw(); - let res = new bignum(raw); +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} - if (values) - res = values[res.toString(10)] || res; +SBCSEncoder.prototype.write = function (str) { + var buf = Buffer.alloc(str.length); - return res; -}; + for (var i = 0; i < str.length; i++) { + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + } -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getDecoder('der').tree; + return buf; }; -// Utility methods - -function derDecodeTag(buf, fail) { - let tag = buf.readUInt8(fail); - if (buf.isError(tag)) - return tag; +SBCSEncoder.prototype.end = function () {}; - const cls = der.tagClass[tag >> 6]; - const primitive = (tag & 0x20) === 0; +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} - // Multi-octet tag - load - if ((tag & 0x1f) === 0x1f) { - let oct = tag; - tag = 0; - while ((oct & 0x80) === 0x80) { - oct = buf.readUInt8(fail); - if (buf.isError(oct)) - return oct; +SBCSDecoder.prototype.write = function (buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length * 2); + var idx1 = 0, + idx2 = 0; - tag <<= 7; - tag |= oct & 0x7f; - } - } else { - tag &= 0x1f; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i] * 2; + idx2 = i * 2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2 + 1] = decodeBuf[idx1 + 1]; } - const tagStr = der.tag[tag]; - - return { - cls: cls, - primitive: primitive, - tag: tag, - tagStr: tagStr - }; -} - -function derDecodeLen(buf, primitive, fail) { - let len = buf.readUInt8(fail); - if (buf.isError(len)) - return len; - // Indefinite form - if (!primitive && len === 0x80) - return null; + return newBuf.toString('ucs2'); +}; - // Definite form - if ((len & 0x80) === 0) { - // Short form - return len; - } +SBCSDecoder.prototype.end = function () {}; - // Long form - const num = len & 0x7f; - if (num > 4) - return buf.error('length octect is too long'); +},{"safer-buffer":24}],8:[function(require,module,exports){ +"use strict"; // Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. - len = 0; - for (let i = 0; i < num; i++) { - len <<= 8; - const j = buf.readUInt8(fail); - if (buf.isError(j)) - return j; - len |= j; - } - - return len; -} - -},{"../../asn1":5,"inherits":401}],14:[function(require,module,exports){ -'use strict'; - -const decoders = exports; - -decoders.der = require('./der'); -decoders.pem = require('./pem'); - -},{"./der":13,"./pem":15}],15:[function(require,module,exports){ -'use strict'; - -const inherits = require('inherits'); -const Buffer = require('buffer').Buffer; - -const DERDecoder = require('./der'); - -function PEMDecoder(entity) { - DERDecoder.call(this, entity); - this.enc = 'pem'; -} -inherits(PEMDecoder, DERDecoder); -module.exports = PEMDecoder; - -PEMDecoder.prototype.decode = function decode(data, options) { - const lines = data.toString().split(/[\r\n]+/g); - - const label = options.label.toUpperCase(); - - const re = /^-----(BEGIN|END) ([^-]+)-----$/; - let start = -1; - let end = -1; - for (let i = 0; i < lines.length; i++) { - const match = lines[i].match(re); - if (match === null) - continue; - - if (match[2] !== label) - continue; - - if (start === -1) { - if (match[1] !== 'BEGIN') - break; - start = i; - } else { - if (match[1] !== 'END') - break; - end = i; - break; - } - } - if (start === -1 || end === -1) - throw new Error('PEM section not found for: ' + label); - - const base64 = lines.slice(start + 1, end).join(''); - // Remove excessive symbols - base64.replace(/[^a-z0-9+/=]+/gi, ''); - - const input = new Buffer(base64, 'base64'); - return DERDecoder.prototype.decode.call(this, input, options); -}; - -},{"./der":13,"buffer":undefined,"inherits":401}],16:[function(require,module,exports){ -'use strict'; - -const inherits = require('inherits'); -const Buffer = require('buffer').Buffer; - -const asn1 = require('../../asn1'); -const base = asn1.base; - -// Import DER constants -const der = asn1.constants.der; - -function DEREncoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -} -module.exports = DEREncoder; - -DEREncoder.prototype.encode = function encode(data, reporter) { - return this.tree._encode(data, reporter).join(); -}; - -// Tree methods - -function DERNode(parent) { - base.Node.call(this, 'der', parent); -} -inherits(DERNode, base.Node); - -DERNode.prototype._encodeComposite = function encodeComposite(tag, - primitive, - cls, - content) { - const encodedTag = encodeTag(tag, primitive, cls, this.reporter); - - // Short form - if (content.length < 0x80) { - const header = new Buffer(2); - header[0] = encodedTag; - header[1] = content.length; - return this._createEncoderBuffer([ header, content ]); - } - - // Long form - // Count octets required to store length - let lenOctets = 1; - for (let i = content.length; i >= 0x100; i >>= 8) - lenOctets++; - - const header = new Buffer(1 + 1 + lenOctets); - header[0] = encodedTag; - header[1] = 0x80 | lenOctets; - - for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) - header[i] = j & 0xff; - - return this._createEncoderBuffer([ header, content ]); -}; - -DERNode.prototype._encodeStr = function encodeStr(str, tag) { - if (tag === 'bitstr') { - return this._createEncoderBuffer([ str.unused | 0, str.data ]); - } else if (tag === 'bmpstr') { - const buf = new Buffer(str.length * 2); - for (let i = 0; i < str.length; i++) { - buf.writeUInt16BE(str.charCodeAt(i), i * 2); - } - return this._createEncoderBuffer(buf); - } else if (tag === 'numstr') { - if (!this._isNumstr(str)) { - return this.reporter.error('Encoding of string type: numstr supports ' + - 'only digits and space'); - } - return this._createEncoderBuffer(str); - } else if (tag === 'printstr') { - if (!this._isPrintstr(str)) { - return this.reporter.error('Encoding of string type: printstr supports ' + - 'only latin upper and lower case letters, ' + - 'digits, space, apostrophe, left and rigth ' + - 'parenthesis, plus sign, comma, hyphen, ' + - 'dot, slash, colon, equal sign, ' + - 'question mark'); - } - return this._createEncoderBuffer(str); - } else if (/str$/.test(tag)) { - return this._createEncoderBuffer(str); - } else if (tag === 'objDesc') { - return this._createEncoderBuffer(str); - } else { - return this.reporter.error('Encoding of string type: ' + tag + - ' unsupported'); - } -}; - -DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { - if (typeof id === 'string') { - if (!values) - return this.reporter.error('string objid given, but no values map found'); - if (!values.hasOwnProperty(id)) - return this.reporter.error('objid not found in values map'); - id = values[id].split(/[\s.]+/g); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } else if (Array.isArray(id)) { - id = id.slice(); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } - - if (!Array.isArray(id)) { - return this.reporter.error('objid() should be either array or string, ' + - 'got: ' + JSON.stringify(id)); - } - - if (!relative) { - if (id[1] >= 40) - return this.reporter.error('Second objid identifier OOB'); - id.splice(0, 2, id[0] * 40 + id[1]); - } - - // Count number of octets - let size = 0; - for (let i = 0; i < id.length; i++) { - let ident = id[i]; - for (size++; ident >= 0x80; ident >>= 7) - size++; - } - - const objid = new Buffer(size); - let offset = objid.length - 1; - for (let i = id.length - 1; i >= 0; i--) { - let ident = id[i]; - objid[offset--] = ident & 0x7f; - while ((ident >>= 7) > 0) - objid[offset--] = 0x80 | (ident & 0x7f); - } - - return this._createEncoderBuffer(objid); -}; - -function two(num) { - if (num < 10) - return '0' + num; - else - return num; -} - -DERNode.prototype._encodeTime = function encodeTime(time, tag) { - let str; - const date = new Date(time); - - if (tag === 'gentime') { - str = [ - two(date.getUTCFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else if (tag === 'utctime') { - str = [ - two(date.getUTCFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else { - this.reporter.error('Encoding ' + tag + ' time is not supported yet'); - } - - return this._encodeStr(str, 'octstr'); -}; - -DERNode.prototype._encodeNull = function encodeNull() { - return this._createEncoderBuffer(''); -}; - -DERNode.prototype._encodeInt = function encodeInt(num, values) { - if (typeof num === 'string') { - if (!values) - return this.reporter.error('String int or enum given, but no values map'); - if (!values.hasOwnProperty(num)) { - return this.reporter.error('Values map doesn\'t contain: ' + - JSON.stringify(num)); - } - num = values[num]; - } - - // Bignum, assume big endian - if (typeof num !== 'number' && !Buffer.isBuffer(num)) { - const numArray = num.toArray(); - if (!num.sign && numArray[0] & 0x80) { - numArray.unshift(0); - } - num = new Buffer(numArray); - } - - if (Buffer.isBuffer(num)) { - let size = num.length; - if (num.length === 0) - size++; - - const out = new Buffer(size); - num.copy(out); - if (num.length === 0) - out[0] = 0; - return this._createEncoderBuffer(out); - } - - if (num < 0x80) - return this._createEncoderBuffer(num); - - if (num < 0x100) - return this._createEncoderBuffer([0, num]); - - let size = 1; - for (let i = num; i >= 0x100; i >>= 8) - size++; - - const out = new Array(size); - for (let i = out.length - 1; i >= 0; i--) { - out[i] = num & 0xff; - num >>= 8; - } - if(out[0] & 0x80) { - out.unshift(0); +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\0\x01\x02\x03\x04\x05\x06\x07\b\t\n\x0B\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !\"#$\u066A&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xB0\xB7\u2219\u221A\u2592\u2500\u2502\u253C\u2524\u252C\u251C\u2534\u2510\u250C\u2514\u2518\u03B2\u221E\u03C6\xB1\xBD\xBC\u2248\xAB\xBB\uFEF7\uFEF8\uFFFD\uFFFD\uFEFB\uFEFC\uFFFD\xA0\xAD\uFE82\xA3\xA4\uFE84\uFFFD\uFFFD\uFE8E\uFE8F\uFE95\uFE99\u060C\uFE9D\uFEA1\uFEA5\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFED1\u061B\uFEB1\uFEB5\uFEB9\u061F\xA2\uFE80\uFE81\uFE83\uFE85\uFECA\uFE8B\uFE8D\uFE91\uFE93\uFE97\uFE9B\uFE9F\uFEA3\uFEA7\uFEA9\uFEAB\uFEAD\uFEAF\uFEB3\uFEB7\uFEBB\uFEBF\uFEC1\uFEC5\uFECB\uFECF\xA6\xAC\xF7\xD7\uFEC9\u0640\uFED3\uFED7\uFEDB\uFEDF\uFEE3\uFEE7\uFEEB\uFEED\uFEEF\uFEF3\uFEBD\uFECC\uFECE\uFECD\uFEE1\uFE7D\u0651\uFEE5\uFEE9\uFEEC\uFEF0\uFEF2\uFED0\uFED5\uFEF5\uFEF6\uFEDD\uFED9\uFEF1\u25A0\uFFFD" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\0\xDA\u1EE4\x03\u1EEA\u1EEC\u1EEE\x07\b\t\n\x0B\f\r\x0E\x0F\x10\u1EE8\u1EF0\u1EF2\u1EF6\u1EF8\xDD\u1EF4\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xC0\u1EA2\xC3\xC1\u1EA0\u1EB6\u1EAC\xC8\u1EBA\u1EBC\xC9\u1EB8\u1EC6\xCC\u1EC8\u0128\xCD\u1ECA\xD2\u1ECE\xD5\xD3\u1ECC\u1ED8\u1EDC\u1EDE\u1EE0\u1EDA\u1EE2\xD9\u1EE6\u0168\xA0\u0102\xC2\xCA\xD4\u01A0\u01AF\u0110\u0103\xE2\xEA\xF4\u01A1\u01B0\u0111\u1EB0\u0300\u0309\u0303\u0301\u0323\xE0\u1EA3\xE3\xE1\u1EA1\u1EB2\u1EB1\u1EB3\u1EB5\u1EAF\u1EB4\u1EAE\u1EA6\u1EA8\u1EAA\u1EA4\u1EC0\u1EB7\u1EA7\u1EA9\u1EAB\u1EA5\u1EAD\xE8\u1EC2\u1EBB\u1EBD\xE9\u1EB9\u1EC1\u1EC3\u1EC5\u1EBF\u1EC7\xEC\u1EC9\u1EC4\u1EBE\u1ED2\u0129\xED\u1ECB\xF2\u1ED4\u1ECF\xF5\xF3\u1ECD\u1ED3\u1ED5\u1ED7\u1ED1\u1ED9\u1EDD\u1EDF\u1EE1\u1EDB\u1EE3\xF9\u1ED6\u1EE7\u0169\xFA\u1EE5\u1EEB\u1EED\u1EEF\u1EE9\u1EF1\u1EF3\u1EF7\u1EF9\xFD\u1EF5\u1ED0" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\0\x01\u1EB2\x03\x04\u1EB4\u1EAA\x07\b\t\n\x0B\f\r\x0E\x0F\x10\x11\x12\x13\u1EF6\x15\x16\x17\x18\u1EF8\x1A\x1B\x1C\x1D\u1EF4\x1F !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\u1EA0\u1EAE\u1EB0\u1EB6\u1EA4\u1EA6\u1EA8\u1EAC\u1EBC\u1EB8\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EE2\u1EDA\u1EDC\u1EDE\u1ECA\u1ECE\u1ECC\u1EC8\u1EE6\u0168\u1EE4\u1EF2\xD5\u1EAF\u1EB1\u1EB7\u1EA5\u1EA7\u1EA9\u1EAD\u1EBD\u1EB9\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1ED1\u1ED3\u1ED5\u1ED7\u1EE0\u01A0\u1ED9\u1EDD\u1EDF\u1ECB\u1EF0\u1EE8\u1EEA\u1EEC\u01A1\u1EDB\u01AF\xC0\xC1\xC2\xC3\u1EA2\u0102\u1EB3\u1EB5\xC8\xC9\xCA\u1EBA\xCC\xCD\u0128\u1EF3\u0110\u1EE9\xD2\xD3\xD4\u1EA1\u1EF7\u1EEB\u1EED\xD9\xDA\u1EF9\u1EF5\xDD\u1EE1\u01B0\xE0\xE1\xE2\xE3\u1EA3\u0103\u1EEF\u1EAB\xE8\xE9\xEA\u1EBB\xEC\xED\u0129\u1EC9\u0111\u1EF1\xF2\xF3\xF4\xF5\u1ECF\u1ECD\u1EE5\xF9\xFA\u0169\u1EE7\xFD\u1EE3\u1EEE" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\0\x01\x02\x03\x04\x05\x06\x07\b\t\n\x0B\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !\"#\xA5%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\0\x01\x02\x03\x04\x05\x06\x07\b\t\n\x0B\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\xA5]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" } - - return this._createEncoderBuffer(new Buffer(out)); -}; - -DERNode.prototype._encodeBool = function encodeBool(value) { - return this._createEncoderBuffer(value ? 0xff : 0); -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getEncoder('der').tree; -}; - -DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { - const state = this._baseState; - let i; - if (state['default'] === null) - return false; - - const data = dataBuffer.join(); - if (state.defaultBuffer === undefined) - state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); - - if (data.length !== state.defaultBuffer.length) - return false; - - for (i=0; i < data.length; i++) - if (data[i] !== state.defaultBuffer[i]) - return false; - - return true; }; -// Utility methods +},{}],9:[function(require,module,exports){ +"use strict"; // Manually added data to be used by sbcs codec in addition to generated one. -function encodeTag(tag, primitive, cls, reporter) { - let res; +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek": "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + "cp819": "iso88591", + "ibm819": "iso88591", + "cyrillic": "iso88595", + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + "greek": "iso88597", + "greek8": "iso88597", + "ecma118": "iso88597", + "elot928": "iso88597", + "hebrew": "iso88598", + "hebrew8": "iso88598", + "turkish": "iso88599", + "turkish8": "iso88599", + "thai": "iso885911", + "thai8": "iso885911", + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + "strk10482002": "rk1048", + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + "gb198880": "iso646cn", + "cn": "iso646cn", + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + "mac": "macintosh", + "csmacintosh": "macintosh" +}; + +},{}],10:[function(require,module,exports){ +module.exports=[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] - if (tag === 'seqof') - tag = 'seq'; - else if (tag === 'setof') - tag = 'set'; +},{}],11:[function(require,module,exports){ +module.exports=[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] - if (der.tagByName.hasOwnProperty(tag)) - res = der.tagByName[tag]; - else if (typeof tag === 'number' && (tag | 0) === tag) - res = tag; - else - return reporter.error('Unknown tag: ' + tag); +},{}],12:[function(require,module,exports){ +module.exports=[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆÐªĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] + +},{}],13:[function(require,module,exports){ +module.exports=[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] + +},{}],14:[function(require,module,exports){ +module.exports=[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] + +},{}],15:[function(require,module,exports){ +module.exports={"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} +},{}],16:[function(require,module,exports){ +module.exports=[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] + +},{}],17:[function(require,module,exports){ +module.exports=[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] - if (res >= 0x1f) - return reporter.error('Multi-octet tag encoding unsupported'); +},{}],18:[function(require,module,exports){ +"use strict"; - if (!primitive) - res |= 0x20; +var Buffer = require("safer-buffer").Buffer; // Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js +// == UTF16-BE codec. ========================================================== - res |= (der.tagClassByName[cls || 'universal'] << 6); - return res; -} +exports.utf16be = Utf16BECodec; -},{"../../asn1":5,"buffer":undefined,"inherits":401}],17:[function(require,module,exports){ -'use strict'; +function Utf16BECodec() {} -const encoders = exports; +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; // -- Encoding -encoders.der = require('./der'); -encoders.pem = require('./pem'); +function Utf16BEEncoder() {} -},{"./der":16,"./pem":18}],18:[function(require,module,exports){ -'use strict'; +Utf16BEEncoder.prototype.write = function (str) { + var buf = Buffer.from(str, 'ucs2'); -const inherits = require('inherits'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; + buf[i] = buf[i + 1]; + buf[i + 1] = tmp; + } -const DEREncoder = require('./der'); + return buf; +}; -function PEMEncoder(entity) { - DEREncoder.call(this, entity); - this.enc = 'pem'; +Utf16BEEncoder.prototype.end = function () {}; // -- Decoding + + +function Utf16BEDecoder() { + this.overflowByte = -1; } -inherits(PEMEncoder, DEREncoder); -module.exports = PEMEncoder; -PEMEncoder.prototype.encode = function encode(data, options) { - const buf = DEREncoder.prototype.encode.call(this, data); +Utf16BEDecoder.prototype.write = function (buf) { + if (buf.length == 0) return ''; + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, + j = 0; - const p = buf.toString('base64'); - const out = [ '-----BEGIN ' + options.label + '-----' ]; - for (let i = 0; i < p.length; i += 64) - out.push(p.slice(i, i + 64)); - out.push('-----END ' + options.label + '-----'); - return out.join('\n'); + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; + j = 2; + } + + for (; i < buf.length - 1; i += 2, j += 2) { + buf2[j] = buf[i + 1]; + buf2[j + 1] = buf[i]; + } + + this.overflowByte = i == buf.length - 1 ? buf[buf.length - 1] : -1; + return buf2.slice(0, j).toString('ucs2'); }; -},{"./der":16,"inherits":401}],19:[function(require,module,exports){ -'use strict'; +Utf16BEDecoder.prototype.end = function () {}; // == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). -function Queue(options) { - if (!(this instanceof Queue)) { - return new Queue(options); - } +exports.utf16 = Utf16Codec; + +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; // -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { options = options || {}; - this.concurrency = options.concurrency || Infinity; - this.pending = 0; - this.jobs = []; - this.cbs = []; - this._done = done.bind(this); + if (options.addBOM === undefined) options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); } -var arrayAddMethods = [ - 'push', - 'unshift', - 'splice' -]; +Utf16Encoder.prototype.write = function (str) { + return this.encoder.write(str); +}; -arrayAddMethods.forEach(function(method) { - Queue.prototype[method] = function() { - var methodResult = Array.prototype[method].apply(this.jobs, arguments); - this._run(); - return methodResult; - }; -}); +Utf16Encoder.prototype.end = function () { + return this.encoder.end(); +}; // -- Decoding -Object.defineProperty(Queue.prototype, 'length', { - get: function() { - return this.pending + this.jobs.length; - } -}); -Queue.prototype._run = function() { - if (this.pending === this.concurrency) { - return; - } - if (this.jobs.length) { - var job = this.jobs.shift(); - this.pending++; - job(this._done); - this._run(); - } +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + this.options = options || {}; + this.iconv = codec.iconv; +} - if (this.pending === 0) { - while (this.cbs.length !== 0) { - var cb = this.cbs.pop(); - process.nextTick(cb); - } +Utf16Decoder.prototype.write = function (buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; // We have enough bytes -> detect endianness. + + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; } + + return this.decoder.write(buf); }; -Queue.prototype.onDone = function(cb) { - if (typeof cb === 'function') { - this.cbs.push(cb); - this._run(); +Utf16Decoder.prototype.end = function () { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + var res = this.decoder.write(buf), + trail = this.decoder.end(); + return trail ? res + trail : res; } -}; -function done() { - this.pending--; - this._run(); -} + return this.decoder.end(); +}; -module.exports = Queue; +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; -},{}],20:[function(require,module,exports){ -'use strict'; + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be';else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le';else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, + asciiCharsBE = 0, + // Counts of chars in both positions + _len = Math.min(buf.length - buf.length % 2, 64); // Len is always even. -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = asyncify; -var _isObject = require('lodash/isObject'); + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i + 1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i + 1] === 0) asciiCharsLE++; + } -var _isObject2 = _interopRequireDefault(_isObject); + if (asciiCharsBE > asciiCharsLE) enc = 'utf-16be';else if (asciiCharsBE < asciiCharsLE) enc = 'utf-16le'; + } + } -var _initialParams = require('./internal/initialParams'); + return enc; +} -var _initialParams2 = _interopRequireDefault(_initialParams); +},{"safer-buffer":24}],19:[function(require,module,exports){ +"use strict"; -var _setImmediate = require('./internal/setImmediate'); +var Buffer = require("safer-buffer").Buffer; // UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 -var _setImmediate2 = _interopRequireDefault(_setImmediate); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return (0, _initialParams2.default)(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if ((0, _isObject2.default)(result) && typeof result.then === 'function') { - result.then(function (value) { - invokeCallback(callback, null, value); - }, function (err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; } -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - (0, _setImmediate2.default)(rethrow, e); - } -} +; +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; // -- Encoding -function rethrow(error) { - throw error; +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; } -module.exports = exports['default']; -},{"./internal/initialParams":40,"./internal/setImmediate":49,"lodash/isObject":931}],21:[function(require,module,exports){ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.async = global.async || {}))); -}(this, (function (exports) { 'use strict'; -function slice(arrayLike, start) { - start = start|0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for(var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; +Utf7Encoder.prototype.write = function (str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function (chunk) { + return "+" + (chunk === '+' ? '' : this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + "-"; + }.bind(this))); +}; + +Utf7Encoder.prototype.end = function () {}; // -- Decoding + + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; } -/** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -var apply = function(fn/*, ...args*/) { - var args = slice(arguments, 1); - return function(/*callArgs*/) { - var callArgs = slice(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; -var initialParams = function (fn) { - return function (/*...args, callback*/) { - var args = slice(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; +for (var i = 0; i < 256; i++) { + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); +} + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function (buf) { + var res = "", + lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { + // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + + lastI = i + 1; + inBase64 = true; + } + } else { + // We decode base64. + if (!base64Chars[buf[i]]) { + // Base64 ended. + if (i == lastI && buf[i] == minusChar) { + // "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + lastI = i + 1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + var canBeDecoded = b64str.length - b64str.length % 8; // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + + b64str = b64str.slice(0, canBeDecoded); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + return res; }; -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} +Utf7Decoder.prototype.end = function () { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + this.inBase64 = false; + this.base64Accum = ''; + return res; +}; // UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; -function fallback(fn) { - setTimeout(fn, 0); -} +exports.utf7imap = Utf7IMAPCodec; -function wrap(defer) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; } -var _defer; +; +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; // -- Encoding -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; } -var setImmediate$1 = wrap(_defer); +Utf7IMAPEncoder.prototype.write = function (str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length * 5 + 10), + bufIdx = 0; -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (isObject(result) && typeof result.then === 'function') { - result.then(function(value) { - invokeCallback(callback, null, value); - }, function(err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + + if (0x20 <= uChar && uChar <= 0x7E) { + // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; } - }); -} -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - setImmediate$1(rethrow, e); - } -} + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. -function rethrow(error) { - throw error; -} + inBase64 = false; + } -var supportsSymbol = typeof Symbol === 'function'; + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + } else { + // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; -} + inBase64 = true; + } -function applyEach$1(eachfn) { - return function(fns/*, ...args*/) { - var args = slice(arguments, 1); - var go = initialParams(function(args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - wrapAsync(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; } - }; -} + } + } + } -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + return buf.slice(0, bufIdx); +}; -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +Utf7IMAPEncoder.prototype.end = function () { + var buf = Buffer.alloc(10), + bufIdx = 0; -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } -/** Built-in value references. */ -var Symbol$1 = root.Symbol; + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. -/** Used for built-in method references. */ -var objectProto = Object.prototype; + this.inBase64 = false; + } -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + return buf.slice(0, bufIdx); +}; // -- Decoding -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} +Utf7IMAPDecoder.prototype.write = function (buf) { + var res = "", + lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { + // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + + lastI = i + 1; + inBase64 = true; + } } else { - delete value[symToStringTag$1]; + // We decode base64. + if (!base64IMAPChars[buf[i]]) { + // Base64 ended. + if (i == lastI && buf[i] == minusChar) { + // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + lastI = i + 1; + inBase64 = false; + base64Accum = ''; + } } } - return result; -} -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + var canBeDecoded = b64str.length - b64str.length % 8; // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} + b64str = b64str.slice(0, canBeDecoded); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } -/** `Object#toString` result references. */ -var nullTag = '[object Null]'; -var undefinedTag = '[object Undefined]'; + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + return res; +}; -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; +Utf7IMAPDecoder.prototype.end = function () { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + this.inBase64 = false; + this.base64Accum = ''; + return res; +}; -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; +},{"safer-buffer":24}],20:[function(require,module,exports){ +"use strict"; + +var BOMChar = "\uFEFF"; +exports.PrependBOM = PrependBOMWrapper; + +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function (str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); + + return this.encoder.write(str); +}; + +PrependBOMWrapper.prototype.end = function () { + return this.encoder.end(); +}; //------------------------------------------------------------------------------ + + +exports.StripBOM = StripBOMWrapper; + +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; } -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]'; -var funcTag = '[object Function]'; -var genTag = '[object GeneratorFunction]'; -var proxyTag = '[object Proxy]'; +StripBOMWrapper.prototype.write = function (buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) return res; -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') this.options.stripBOM(); } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + this.pass = true; + return res; +}; -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +StripBOMWrapper.prototype.end = function () { + return this.decoder.end(); +}; -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} +},{}],21:[function(require,module,exports){ +"use strict"; -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -var breakLoop = {}; +var Buffer = require("buffer").Buffer; // Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer +// == Extend Node primitives to use iconv-lite ================================= -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. -} -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } + + var nodeNativeEncodings = { + 'hex': true, + 'utf8': true, + 'utf-8': true, + 'ascii': true, + 'binary': true, + 'base64': true, + 'ucs2': true, + 'ucs-2': true, + 'utf16le': true, + 'utf-16le': true }; -} -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; + Buffer.isNativeEncoding = function (enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + }; // -- SlowBuffer ----------------------------------------------------------- -var getIterator = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); + var SlowBuffer = require('buffer').SlowBuffer; - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} + original.SlowBufferToString = SlowBuffer.prototype.toString; -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} + SlowBuffer.prototype.toString = function (encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; + if (Buffer.isNativeEncoding(encoding)) return original.SlowBufferToString.call(this, encoding, start, end); // Otherwise, use our decoding method. -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; -} + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + }; -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; + original.SlowBufferWrite = SlowBuffer.prototype.write; -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + SlowBuffer.prototype.write = function (string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { + // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + offset = +offset || 0; + var remaining = this.length - offset; -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; + if (!length) { + length = remaining; + } else { + length = +length; -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + if (length > remaining) { + length = remaining; + } + } -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; -} + encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + if (Buffer.isNativeEncoding(encoding)) return original.SlowBufferWrite.call(this, string, offset, length, encoding); + if (string.length > 0 && (length < 0 || offset < 0)) throw new RangeError('attempt to write beyond buffer bounds'); // Otherwise, use our encoding method. -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + }; // -- Buffer --------------------------------------------------------------- -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; + original.BufferIsEncoding = Buffer.isEncoding; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + Buffer.isEncoding = function (encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + }; -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse; + original.BufferByteLength = Buffer.byteLength; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; + Buffer.byteLength = SlowBuffer.byteLength = function (str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; + if (Buffer.isNativeEncoding(encoding)) return original.BufferByteLength.call(this, str, encoding); // Slow, I know, but we don't have a better way yet. -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; + return iconv.encode(str, encoding).length; + }; - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} + original.BufferToString = Buffer.prototype.toString; -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]'; -var arrayTag = '[object Array]'; -var boolTag = '[object Boolean]'; -var dateTag = '[object Date]'; -var errorTag = '[object Error]'; -var funcTag$1 = '[object Function]'; -var mapTag = '[object Map]'; -var numberTag = '[object Number]'; -var objectTag = '[object Object]'; -var regexpTag = '[object RegExp]'; -var setTag = '[object Set]'; -var stringTag = '[object String]'; -var weakMapTag = '[object WeakMap]'; + Buffer.prototype.toString = function (encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible -var arrayBufferTag = '[object ArrayBuffer]'; -var dataViewTag = '[object DataView]'; -var float32Tag = '[object Float32Array]'; -var float64Tag = '[object Float64Array]'; -var int8Tag = '[object Int8Array]'; -var int16Tag = '[object Int16Array]'; -var int32Tag = '[object Int32Array]'; -var uint8Tag = '[object Uint8Array]'; -var uint8ClampedTag = '[object Uint8ClampedArray]'; -var uint16Tag = '[object Uint16Array]'; -var uint32Tag = '[object Uint32Array]'; + if (Buffer.isNativeEncoding(encoding)) return original.BufferToString.call(this, encoding, start, end); // Otherwise, use our decoding method. -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + }; -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; -} + original.BufferWrite = Buffer.prototype.write; -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); + Buffer.prototype.write = function (string, offset, length, encoding) { + var _offset = offset, + _length = length, + _encoding = encoding; // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { + // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible + + if (Buffer.isNativeEncoding(encoding)) return original.BufferWrite.call(this, string, _offset, _length, _encoding); + offset = +offset || 0; + var remaining = this.length - offset; + + if (!length) { + length = remaining; + } else { + length = +length; + + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) throw new RangeError('attempt to write beyond buffer bounds'); // Otherwise, use our encoding method. + + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; // TODO: Set _charsWritten. + }; // -- Readable ------------------------------------------------------------- + + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + }; + + Readable.prototype.collect = iconv._collect; + } + }; // Remove iconv-lite Node primitive extensions. + + + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) return; + if (!original) throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called."); + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; }; -} +}; -/** Detect free variable `exports`. */ -var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; +},{"buffer":undefined,"stream":undefined}],22:[function(require,module,exports){ +"use strict"; // Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. -/** Detect free variable `module`. */ -var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; +var Buffer = require("safer-buffer").Buffer; -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports$1 && freeGlobal.process; +var bomHandling = require("./bom-handling"), + iconv = module.exports; // All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - if (types) { - return types; +iconv.encodings = null; // Characters emitted in case of error. + +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; // Public API. + +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + var res = encoder.write(str); + var trail = encoder.end(); + return trail && trail.length > 0 ? Buffer.concat([res, trail]) : res; +}; + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; } - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + } -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + var decoder = iconv.getDecoder(encoding, options); + var res = decoder.write(buf); + var trail = decoder.end(); + return trail ? res + trail : res; +}; -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +}; // Legacy aliases to convert functions -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; // Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; +iconv._codecDataCache = {}; - for (var key in value) { - if ((inherited || hasOwnProperty$1.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + + var enc = iconv._canonicalizeEncoding(encoding); // Traverse iconv.encodings to find actual codec. + + + var codecOptions = {}; + + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) return codec; + var codecDef = iconv.encodings[enc]; + + switch (_typeof(codecDef)) { + case "string": + // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": + // Alias with options. Can be layered. + for (var key in codecDef) { + codecOptions[key] = codecDef[key]; + } + + if (!codecOptions.encodingName) codecOptions.encodingName = enc; + enc = codecDef.type; + break; + + case "function": + // Codec itself. + if (!codecOptions.encodingName) codecOptions.encodingName = enc; // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + + codec = new codecDef(codecOptions, iconv); + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '" + enc + "')"); } } - return result; -} +}; -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; +iconv._canonicalizeEncoding = function (encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return ('' + encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +}; -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + if (codec.bomAware && options && options.addBOM) encoder = new bomHandling.PrependBOM(encoder, options); + return encoder; +}; - return value === proto; +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + if (codec.bomAware && !(options && options.stripBOM === false)) decoder = new bomHandling.StripBOM(decoder, options); + return decoder; +}; // Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. + + +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; + +if (nodeVer) { + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } // Load Node primitive extensions. + + + require("./extend-node")(iconv); } -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); +if ("Ā" != "\u0100") { + console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); +} + +},{"../encodings":5,"./bom-handling":20,"./extend-node":21,"./streams":23,"safer-buffer":24}],23:[function(require,module,exports){ +"use strict"; + +var Buffer = require("buffer").Buffer, + Transform = require("stream").Transform; // == Exports ================================================================== + + +module.exports = function (iconv) { + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + }; + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); }; + + iconv.supportsStreams = true; // Not published yet. + + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; // == Encoder stream ======================================================= + + +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + + Transform.call(this, options); } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { + value: IconvLiteEncoderStream + } +}); -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; +IconvLiteEncoderStream.prototype._transform = function (chunk, encoding, done) { + if (typeof chunk != 'string') return done(new Error("Iconv encoding stream needs strings as its input.")); -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } catch (e) { + done(e); + } +}; -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); +IconvLiteEncoderStream.prototype._flush = function (done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } catch (e) { + done(e); } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$3.call(object, key) && key != 'constructor') { - result.push(key); - } +}; + +IconvLiteEncoderStream.prototype.collect = function (cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function (chunk) { + chunks.push(chunk); + }); + this.on('end', function () { + cb(null, Buffer.concat(chunks)); + }); + return this; +}; // == Decoder stream ======================================================= + + +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { + value: IconvLiteDecoderStream } - return result; +}); + +IconvLiteDecoderStream.prototype._transform = function (chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) return done(new Error("Iconv decoding stream needs buffers as its input.")); + + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } catch (e) { + done(e); + } +}; + +IconvLiteDecoderStream.prototype._flush = function (done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } catch (e) { + done(e); + } +}; + +IconvLiteDecoderStream.prototype.collect = function (cb) { + var res = ''; + this.on('error', cb); + this.on('data', function (chunk) { + res += chunk; + }); + this.on('end', function () { + cb(null, res); + }); + return this; +}; + +},{"buffer":undefined,"stream":undefined}],24:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +'use strict'; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var buffer = require('buffer'); + +var Buffer = buffer.Buffer; +var safer = {}; +var key; + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue; + if (key === 'SlowBuffer' || key === 'Buffer') continue; + safer[key] = buffer[key]; } -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +var Safer = safer.Buffer = {}; + +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue; + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue; + Safer[key] = Buffer[key]; } -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; +safer.Buffer.prototype = Buffer.prototype; + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + _typeof(value)); } -} -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + _typeof(value)); } -} -function createObjectIterator(obj) { - var okeys = keys(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? {value: obj[key], key: key} : null; - }; + return Buffer(value, encodingOrOffset, length); + }; } -function iterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + _typeof(size)); } - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + + var buf = Buffer(size); + + if (!fill || fill.length === 0) { + buf.fill(0); + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + + return buf; + }; } -function onlyOnce(fn) { - return function() { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength; + } catch (e) {// we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } } -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = once(callback || noop); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = iterator(obj); - var done = false; - var running = 0; - var looping = false; +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + }; - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (value === breakLoop || (done && running <= 0)) { - done = true; - return callback(null); - } - else if (!looping) { - replenish(); - } - } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength; + } +} - function replenish () { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - looping = false; - } +module.exports = safer; - replenish(); - }; -} +},{"buffer":undefined}],25:[function(require,module,exports){ +"use strict"; -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); -} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback || noop); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } +console.log("Node version: ".concat(process.versions.node)); - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop) { - callback(null); - } - } +require('@babel/polyfill'); - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } +var rnBridge = require('rn-bridge'); //const os = require('os') + + +var fs = require('fs'); + +var path = require('path'); + +var debug = require('debug'); + +var Logger = require('logplease'); + +var RecordNode = require('record-node'); // Log Record / IPFS / OrbitDB + + +debug.useColors = function () { + return false; +}; // disable colors in log (fixes xcode issue) + + +var logger = debug('main'); +debug.enable('main,ipfs,ipfs:err,record:*'); //libp2p:switch:dial,libp2p:switch:transport,libp2p:swarm:dialer') + +Logger.setLogLevel(Logger.LogLevels.DEBUG); +process.on('uncaughtException', logger); +var docsPath = rnBridge.app.datadir(); +var recorddir = path.resolve(docsPath, './record'); + +if (!fs.existsSync(recorddir)) { + fs.mkdirSync(recorddir); } -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = doLimit(eachOfLimit, Infinity); +logger("Record Dir: ".concat(recorddir)); -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -var eachOf = function(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, wrapAsync(iteratee), callback); +var sendApp = function sendApp(action, data) { + rnBridge.channel.send(JSON.stringify({ + action: action, + data: data + })); }; -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(eachOf, obj, wrapAsync(iteratee), callback); - }; -} +var record; -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || noop; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); +try { + var orbitAddressPath = path.resolve(recorddir, 'address.txt'); + var orbitAddress = fs.existsSync(orbitAddressPath) ? fs.readFileSync(orbitAddressPath, 'utf8') : 'record'; + var opts = { + address: orbitAddress, + store: { + replicationConcurrency: 1 + }, + orbitdb: { + directory: path.resolve(recorddir, './orbitdb') + }, + bitboot: { + enabled: false + }, + api: true, + ipfs: { + init: { + // log: sendState, see https://github.com/ipfs/js-ipfs/issues/2170 + bits: 1024 + }, + repo: path.resolve(recorddir, './ipfs'), + config: { + Addresses: { + Swarm: ['/ip4/206.189.77.125/tcp/9090/ws/p2p-websocket-star/'] + } + }, + connectionManager: { + maxPeers: 10, + minPeers: 2, + pollInterval: 60000 // ms - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} + }, + libp2p: { + config: { + peerDiscovery: { + mdns: { + enabled: false + } + }, + relay: { + enabled: false + } + } + } + } + }; + logger('Starting Record & IPFS'); + record = new RecordNode(opts); + record.on('ipfs:state', function (state) { + return sendApp('ipfs:state', state); + }); + record.on('ready', + /*#__PURE__*/ + _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee() { + var log, _record, address, isReplicating; + + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return record.log.get(); + + case 3: + log = _context.sent; + logger("Orbit Address: ".concat(record._log.address)); + fs.writeFileSync(orbitAddressPath, record._log.address); + _context.next = 11; + break; -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -var map = doParallel(_asyncMap); + case 8: + _context.prev = 8; + _context.t0 = _context["catch"](0); + console.log(_context.t0); -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -var applyEach = applyEach$1(map); + case 11: + record.on('redux', function (data) { + return sendApp('redux', data); + }); + _record = record, address = _record.address, isReplicating = _record.isReplicating; + sendApp('ready', { + address: address, + isReplicating: isReplicating + }); + setTimeout(function () { + record.contacts.connect(); + }, 5000); -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); - }; + case 15: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 8]]); + }))); +} catch (e) { + logger(e); + sendApp('ipfs:state', 'failed'); +} + +rnBridge.channel.on('message', function (message) { + var msg = JSON.parse(message); + console.log(message); + + if (msg.action === 'init') { + if (record._ipfs.state.state() === 'running') { + var _record2 = record, + address = _record2.address, + isReplicating = _record2.isReplicating; + sendApp('ready', { + address: address, + isReplicating: isReplicating + }); + } else { + sendApp('ipfs:state', 'failed'); + /* record.on('ready' () => { + * const { address, isReplicating } = record + * sendApp('ready', { address, isReplicating }) + * }) */ + } + } +}); + +},{"@babel/polyfill":26,"debug":691,"fs":undefined,"logplease":2283,"path":undefined,"record-node":2752,"rn-bridge":undefined}],26:[function(require,module,exports){ +"use strict"; + +require("./noConflict"); + +var _global = _interopRequireDefault(require("core-js/library/fn/global")); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; } -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapLimit = doParallelLimit(_asyncMap); +if (_global["default"]._babelPolyfill && typeof console !== "undefined" && console.warn) { + console.warn("@babel/polyfill is loaded more than once on this page. This is probably not desirable/intended " + "and may have consequences if different versions of the polyfills are applied sequentially. " + "If you do need to load the polyfill more than once, use @babel/polyfill/noConflict " + "instead to bypass the warning."); +} -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapSeries = doLimit(mapLimit, 1); +_global["default"]._babelPolyfill = true; + +},{"./noConflict":27,"core-js/library/fn/global":325}],27:[function(require,module,exports){ +"use strict"; + +require("core-js/es6"); + +require("core-js/fn/array/includes"); + +require("core-js/fn/array/flat-map"); + +require("core-js/fn/string/pad-start"); + +require("core-js/fn/string/pad-end"); + +require("core-js/fn/string/trim-start"); + +require("core-js/fn/string/trim-end"); + +require("core-js/fn/symbol/async-iterator"); + +require("core-js/fn/object/get-own-property-descriptors"); + +require("core-js/fn/object/values"); +require("core-js/fn/object/entries"); + +require("core-js/fn/promise/finally"); + +require("core-js/web"); + +require("regenerator-runtime/runtime"); + +},{"core-js/es6":313,"core-js/fn/array/flat-map":314,"core-js/fn/array/includes":315,"core-js/fn/object/entries":316,"core-js/fn/object/get-own-property-descriptors":317,"core-js/fn/object/values":318,"core-js/fn/promise/finally":319,"core-js/fn/string/pad-end":320,"core-js/fn/string/pad-start":321,"core-js/fn/string/trim-end":322,"core-js/fn/string/trim-start":323,"core-js/fn/symbol/async-iterator":324,"core-js/web":616,"regenerator-runtime/runtime":2782}],28:[function(require,module,exports){ /** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. + * @author Toru Nagashima + * See LICENSE file in root directory for full license. */ -var applyEachSeries = applyEach$1(mapSeries); +'use strict'; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var eventTargetShim = require('event-target-shim'); /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal */ -function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } + +var AbortSignal = +/*#__PURE__*/ +function (_eventTargetShim$Even) { + _inherits(AbortSignal, _eventTargetShim$Even); + + /** + * AbortSignal cannot be constructed directly. + */ + function AbortSignal() { + var _this; + + _classCallCheck(this, AbortSignal); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(AbortSignal).call(this)); + throw new TypeError("AbortSignal cannot be constructed directly"); + return _this; } - return array; -} + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; + _createClass(AbortSignal, [{ + key: "aborted", + get: function get() { + var aborted = abortedFlags.get(this); + + if (typeof aborted !== "boolean") { + throw new TypeError("Expected 'this' to be an 'AbortSignal' object, but got ".concat(this === null ? "null" : _typeof(this))); } + + return aborted; } - return object; - }; -} + }]); -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); + return AbortSignal; +}(eventTargetShim.EventTarget); +eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. + * Create an AbortSignal object. */ -function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); -} +function createAbortSignal() { + var signal = Object.create(AbortSignal.prototype); + eventTargetShim.EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; +} /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. + * Abort a given signal. */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } + +function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; } - return -1; -} + abortedFlags.set(signal, true); + signal.dispatchEvent({ + type: "abort" + }); +} /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * Aborted flag for each instances. */ -function baseIsNaN(value) { - return value !== value; -} + +var abortedFlags = new WeakMap(); // Properties should be enumerable. + +Object.defineProperties(AbortSignal.prototype, { + aborted: { + enumerable: true + } +}); // `toString()` should return `"[object AbortSignal]"` + +if (typeof Symbol === "function" && _typeof(Symbol.toStringTag) === "symbol") { + Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal" + }); +} /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; - } + +var AbortController = +/*#__PURE__*/ +function () { + /** + * Initialize this controller. + */ + function AbortController() { + _classCallCheck(this, AbortController); + + signals.set(this, createAbortSignal()); } - return -1; -} + /** + * Returns the `AbortSignal` object associated with this object. + */ + + + _createClass(AbortController, [{ + key: "abort", + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + value: function abort() { + abortSignal(getSignal(this)); + } + }, { + key: "signal", + get: function get() { + return getSignal(this); + } + }]); + + return AbortController; +}(); /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. + * Associated signals. */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); -} + +var signals = new WeakMap(); /** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); - * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * console.log('err = ', err); - * console.log('results = ', results); - * }); + * Get the associated signal of a given controller. */ -var auto = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || noop); - var keys$$1 = keys(tasks); - var numTasks = keys$$1.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } - var results = {}; - var runningTasks = 0; - var hasError = false; +function getSignal(controller) { + var signal = signals.get(controller); - var listeners = Object.create(null); + if (signal == null) { + throw new TypeError("Expected 'this' to be an 'AbortController' object, but got ".concat(controller === null ? "null" : _typeof(controller))); + } - var readyTasks = []; + return signal; +} // Properties should be enumerable. - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; - baseForOwn(tasks, function (task, key) { - if (!isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } +Object.defineProperties(AbortController.prototype, { + signal: { + enumerable: true + }, + abort: { + enumerable: true + } +}); - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; +if (typeof Symbol === "function" && _typeof(Symbol.toStringTag) === "symbol") { + Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController" + }); +} - arrayEach(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); +exports.AbortController = AbortController; +exports.AbortSignal = AbortSignal; +exports["default"] = AbortController; +module.exports = AbortController; +module.exports.AbortController = module.exports["default"] = AbortController; +module.exports.AbortSignal = AbortSignal; - checkForDeadlocks(); - processQueue(); +},{"event-target-shim":803}],29:[function(require,module,exports){ +"use strict"; - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } +function AbstractChainedBatch(db) { + if (_typeof(db) !== 'object' || db === null) { + throw new TypeError('First argument must be an abstract-leveldown compliant store'); + } - } + this.db = db; + this._operations = []; + this._written = false; +} - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } +AbstractChainedBatch.prototype._checkWritten = function () { + if (this._written) { + throw new Error('write() already called on this batch'); + } +}; - taskListeners.push(fn); - } +AbstractChainedBatch.prototype.put = function (key, value) { + this._checkWritten(); - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - arrayEach(taskListeners, function (fn) { - fn(); - }); - processQueue(); - } + var err = this.db._checkKey(key) || this.db._checkValue(value); + if (err) throw err; + key = this.db._serializeKey(key); + value = this.db._serializeValue(value); - function runTask(key, task) { - if (hasError) return; + this._put(key, value); - var taskCallback = onlyOnce(function(err, result) { - runningTasks--; - if (arguments.length > 2) { - result = slice(arguments, 1); - } - if (err) { - var safeResults = {}; - baseForOwn(results, function(val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); + return this; +}; - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); +AbstractChainedBatch.prototype._put = function (key, value) { + this._operations.push({ + type: 'put', + key: key, + value: value + }); +}; - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } +AbstractChainedBatch.prototype.del = function (key) { + this._checkWritten(); - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - arrayEach(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } + var err = this.db._checkKey(key); - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } + if (err) throw err; + key = this.db._serializeKey(key); - function getDependents(taskName) { - var result = []; - baseForOwn(tasks, function (task, key) { - if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } + this._del(key); + + return this; }; -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); +AbstractChainedBatch.prototype._del = function (key) { + this._operations.push({ + type: 'del', + key: key + }); +}; - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} +AbstractChainedBatch.prototype.clear = function () { + this._checkWritten(); -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; + this._clear(); -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} + return this; +}; -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; +AbstractChainedBatch.prototype._clear = function () { + this._operations = []; +}; -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; -var symbolToString = symbolProto ? symbolProto.toString : undefined; +AbstractChainedBatch.prototype.write = function (options, callback) { + this._checkWritten(); -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; + if (typeof options === 'function') { + callback = options; } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; + + if (typeof callback !== 'function') { + throw new Error('write() requires a callback argument'); } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; + + if (_typeof(options) !== 'object' || options === null) { + options = {}; } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; + this._written = true; - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + this._write(options, callback); +}; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} +AbstractChainedBatch.prototype._write = function (options, callback) { + this.db._batch(this._operations, options, callback); +}; -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} +module.exports = AbstractChainedBatch; -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; +},{}],30:[function(require,module,exports){ +"use strict"; - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; +function AbstractIterator(db) { + if (_typeof(db) !== 'object' || db === null) { + throw new TypeError('First argument must be an abstract-leveldown compliant store'); + } - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; + this.db = db; + this._ended = false; + this._nexting = false; } -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} +AbstractIterator.prototype.next = function (callback) { + var self = this; -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff'; -var rsComboMarksRange = '\\u0300-\\u036f'; -var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange = '\\u20d0-\\u20ff'; -var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; -var rsVarRange = '\\ufe0e\\ufe0f'; + if (typeof callback !== 'function') { + throw new Error('next() requires a callback argument'); + } -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; + if (self._ended) { + process.nextTick(callback, new Error('cannot call next() after end()')); + return self; + } -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + if (self._nexting) { + process.nextTick(callback, new Error('cannot call next() before previous next() has completed')); + return self; + } -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} + self._nexting = true; -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff'; -var rsComboMarksRange$1 = '\\u0300-\\u036f'; -var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; -var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; -var rsVarRange$1 = '\\ufe0e\\ufe0f'; + self._next(function () { + self._nexting = false; + callback.apply(null, arguments); + }); -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']'; -var rsCombo = '[' + rsComboRange$1 + ']'; -var rsFitz = '\\ud83c[\\udffb-\\udfff]'; -var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; -var rsNonAstral = '[^' + rsAstralRange$1 + ']'; -var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; -var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; -var rsZWJ$1 = '\\u200d'; + return self; +}; -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?'; -var rsOptVar = '[' + rsVarRange$1 + ']?'; -var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; -var rsSeq = rsOptVar + reOptMod + rsOptJoin; -var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; +AbstractIterator.prototype._next = function (callback) { + process.nextTick(callback); +}; -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); +AbstractIterator.prototype.seek = function (target) { + if (this._ended) { + throw new Error('cannot call seek() after end()'); + } -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} + if (this._nexting) { + throw new Error('cannot call seek() before next() has completed'); + } -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} + target = this.db._serializeKey(target); -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} + this._seek(target); +}; -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +AbstractIterator.prototype._seek = function (target) {}; -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); +AbstractIterator.prototype.end = function (callback) { + if (typeof callback !== 'function') { + throw new Error('end() requires a callback argument'); } - if (!string || !(chars = baseToString(chars))) { - return string; + + if (this._ended) { + return process.nextTick(callback, new Error('end() already called on iterator')); } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - return castSlice(strSymbols, start, end).join(''); -} + this._ended = true; -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + this._end(callback); +}; -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg){ - return trim(arg.replace(FN_ARG, '')); - }); - return func; -} +AbstractIterator.prototype._end = function (callback) { + process.nextTick(callback); +}; -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; +module.exports = AbstractIterator; - baseForOwn(tasks, function (taskFn, key) { - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); - - if (isArray(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; - - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } +},{}],31:[function(require,module,exports){ +"use strict"; - // remove callback param - if (!fnIsAsync) params.pop(); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - newTasks[key] = params.concat(newTask); - } +var xtend = require('xtend'); - function newTask(results, taskCb) { - var newArgs = arrayMap(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - wrapAsync(taskFn).apply(null, newArgs); - } - }); +var AbstractIterator = require('./abstract-iterator'); - auto(newTasks, callback); -} +var AbstractChainedBatch = require('./abstract-chained-batch'); -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} +var hasOwnProperty = Object.prototype.hasOwnProperty; +var rangeOptions = 'start end gt gte lt lte'.split(' '); -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; +function AbstractLevelDOWN() { + this.status = 'new'; } -DLL.prototype.removeLink = function(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; +AbstractLevelDOWN.prototype.open = function (options, callback) { + var self = this; + var oldStatus = this.status; + if (typeof options === 'function') callback = options; - node.prev = node.next = null; - this.length -= 1; - return node; + if (typeof callback !== 'function') { + throw new Error('open() requires a callback argument'); + } + + if (_typeof(options) !== 'object' || options === null) options = {}; + options.createIfMissing = options.createIfMissing !== false; + options.errorIfExists = !!options.errorIfExists; + this.status = 'opening'; + + this._open(options, function (err) { + if (err) { + self.status = oldStatus; + return callback(err); + } + + self.status = 'open'; + callback(); + }); }; -DLL.prototype.empty = function () { - while(this.head) this.shift(); - return this; +AbstractLevelDOWN.prototype._open = function (options, callback) { + process.nextTick(callback); }; -DLL.prototype.insertAfter = function(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; +AbstractLevelDOWN.prototype.close = function (callback) { + var self = this; + var oldStatus = this.status; + + if (typeof callback !== 'function') { + throw new Error('close() requires a callback argument'); + } + + this.status = 'closing'; + + this._close(function (err) { + if (err) { + self.status = oldStatus; + return callback(err); + } + + self.status = 'closed'; + callback(); + }); }; -DLL.prototype.insertBefore = function(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; +AbstractLevelDOWN.prototype._close = function (callback) { + process.nextTick(callback); +}; + +AbstractLevelDOWN.prototype.get = function (key, options, callback) { + if (typeof options === 'function') callback = options; + + if (typeof callback !== 'function') { + throw new Error('get() requires a callback argument'); + } + + var err = this._checkKey(key); + + if (err) return process.nextTick(callback, err); + key = this._serializeKey(key); + if (_typeof(options) !== 'object' || options === null) options = {}; + options.asBuffer = options.asBuffer !== false; + + this._get(key, options, callback); }; -DLL.prototype.unshift = function(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); +AbstractLevelDOWN.prototype._get = function (key, options, callback) { + process.nextTick(function () { + callback(new Error('NotFound')); + }); }; -DLL.prototype.push = function(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); +AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { + if (typeof options === 'function') callback = options; + + if (typeof callback !== 'function') { + throw new Error('put() requires a callback argument'); + } + + var err = this._checkKey(key) || this._checkValue(value); + + if (err) return process.nextTick(callback, err); + key = this._serializeKey(key); + value = this._serializeValue(value); + if (_typeof(options) !== 'object' || options === null) options = {}; + + this._put(key, value, options, callback); }; -DLL.prototype.shift = function() { - return this.head && this.removeLink(this.head); +AbstractLevelDOWN.prototype._put = function (key, value, options, callback) { + process.nextTick(callback); }; -DLL.prototype.pop = function() { - return this.tail && this.removeLink(this.tail); +AbstractLevelDOWN.prototype.del = function (key, options, callback) { + if (typeof options === 'function') callback = options; + + if (typeof callback !== 'function') { + throw new Error('del() requires a callback argument'); + } + + var err = this._checkKey(key); + + if (err) return process.nextTick(callback, err); + key = this._serializeKey(key); + if (_typeof(options) !== 'object' || options === null) options = {}; + + this._del(key, options, callback); }; -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for(var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; +AbstractLevelDOWN.prototype._del = function (key, options, callback) { + process.nextTick(callback); }; -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while(!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; +AbstractLevelDOWN.prototype.batch = function (array, options, callback) { + if (!arguments.length) return this._chainedBatch(); + if (typeof options === 'function') callback = options; + if (typeof array === 'function') callback = array; + + if (typeof callback !== 'function') { + throw new Error('batch(array) requires a callback argument'); + } + + if (!Array.isArray(array)) { + return process.nextTick(callback, new Error('batch(array) requires an array argument')); + } + + if (array.length === 0) { + return process.nextTick(callback); + } + + if (_typeof(options) !== 'object' || options === null) options = {}; + var serialized = new Array(array.length); + + for (var i = 0; i < array.length; i++) { + if (_typeof(array[i]) !== 'object' || array[i] === null) { + return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`')); } - return this; -}; -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; + var e = xtend(array[i]); + + if (e.type !== 'put' && e.type !== 'del') { + return process.nextTick(callback, new Error("`type` must be 'put' or 'del'")); } - else if(concurrency === 0) { - throw new Error('Concurrency must not be zero'); + + var err = this._checkKey(e.key); + + if (err) return process.nextTick(callback, err); + e.key = this._serializeKey(e.key); + + if (e.type === 'put') { + var valueErr = this._checkValue(e.value); + + if (valueErr) return process.nextTick(callback, valueErr); + e.value = this._serializeValue(e.value); } - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; + serialized[i] = e; + } - var processingScheduled = false; - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } + this._batch(serialized, options, callback); +}; - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || noop - }; +AbstractLevelDOWN.prototype._batch = function (array, options, callback) { + process.nextTick(callback); +}; - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } +AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { + options = cleanRangeOptions(this, options); + options.reverse = !!options.reverse; + options.keys = options.keys !== false; + options.values = options.values !== false; + options.limit = 'limit' in options ? options.limit : -1; + options.keyAsBuffer = options.keyAsBuffer !== false; + options.valueAsBuffer = options.valueAsBuffer !== false; + return options; +}; - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(function() { - processingScheduled = false; - q.process(); - }); - } +function cleanRangeOptions(db, options) { + var result = {}; + + for (var k in options) { + if (!hasOwnProperty.call(options, k)) continue; + var opt = options[k]; + + if (isRangeOption(k)) { + // Note that we don't reject nullish and empty options here. While + // those types are invalid as keys, they are valid as range options. + opt = db._serializeKey(opt); } - function _next(tasks) { - return function(err){ - numRunning -= 1; + result[k] = opt; + } - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; + return result; +} - var index = baseIndexOf(workersList, task, 0); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } +function isRangeOption(k) { + return rangeOptions.indexOf(k) !== -1; +} - task.callback.apply(task, arguments); +AbstractLevelDOWN.prototype.iterator = function (options) { + if (_typeof(options) !== 'object' || options === null) options = {}; + options = this._setupIteratorOptions(options); + return this._iterator(options); +}; - if (err != null) { - q.error(err, task.data); - } - } +AbstractLevelDOWN.prototype._iterator = function (options) { + return new AbstractIterator(this); +}; - if (numRunning <= (q.concurrency - q.buffer) ) { - q.unsaturated(); - } +AbstractLevelDOWN.prototype._chainedBatch = function () { + return new AbstractChainedBatch(this); +}; - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } +AbstractLevelDOWN.prototype._serializeKey = function (key) { + return key; +}; - var isProcessing = false; - var q = { - _tasks: new DLL(), - concurrency: concurrency, - payload: payload, - saturated: noop, - unsaturated:noop, - buffer: concurrency / 4, - empty: noop, - drain: noop, - error: noop, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = noop; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } +AbstractLevelDOWN.prototype._serializeValue = function (value) { + return value; +}; - numRunning += 1; +AbstractLevelDOWN.prototype._checkKey = function (key) { + if (key === null || key === undefined) { + return new Error('key cannot be `null` or `undefined`'); + } else if (Buffer.isBuffer(key) && key.length === 0) { + return new Error('key cannot be an empty Buffer'); + } else if (key === '') { + return new Error('key cannot be an empty String'); + } else if (Array.isArray(key) && key.length === 0) { + return new Error('key cannot be an empty Array'); + } +}; - if (q._tasks.length === 0) { - q.empty(); - } +AbstractLevelDOWN.prototype._checkValue = function (value) { + if (value === null || value === undefined) { + return new Error('value cannot be `null` or `undefined`'); + } +}; - if (numRunning === q.concurrency) { - q.saturated(); - } +module.exports = AbstractLevelDOWN; - var cb = onlyOnce(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function() { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - return q; -} +},{"./abstract-chained-batch":29,"./abstract-iterator":30,"xtend":3010}],32:[function(require,module,exports){ +"use strict"; -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} payload - An `integer` for determining how many tasks - * should be process per round. This property can be changed after a `cargo` is - * created to alter the payload on-the-fly. - * @property {Function} push - Adds `task` to the `queue`. The callback is - * called once the `worker` has finished processing the task. Instead of a - * single task, an array of `tasks` can be submitted. The respective callback is - * used for every task in the list. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ +exports.AbstractLevelDOWN = require('./abstract-leveldown'); +exports.AbstractIterator = require('./abstract-iterator'); +exports.AbstractChainedBatch = require('./abstract-chained-batch'); -/** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i "html" * - * function mul3(n, callback) { - * setTimeout(function () { - * callback(null, n * 3); - * }, 10); - * } + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" * - * var add1mul3 = async.compose(mul3, add1); - * add1mul3(4, function (err, result) { - * // result now equals 15 - * }); + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public */ -var compose = function(/*...args*/) { - return seq.apply(null, slice(arguments).reverse()); -}; -var _concat = Array.prototype.concat; -/** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -var concatLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err /*, ...args*/) { - if (err) return callback(err); - return callback(null, slice(arguments, 1)); - }); - }, function(err, mapResults) { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = _concat.apply(result, mapResults[i]); - } - } +Accepts.prototype.type = Accepts.prototype.types = function (types_) { + var types = types_; // support flattened arguments - return callback(err, result); - }); -}; + if (types && !Array.isArray(types)) { + types = new Array(arguments.length); + + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i]; + } + } // no types, return all requested types + + if (!types || types.length === 0) { + return this.negotiator.mediaTypes(); + } // no accept header, return first given type + + + if (!this.headers.accept) { + return types[0]; + } + + var mimes = types.map(extToMime); + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)); + var first = accepts[0]; + return first ? types[mimes.indexOf(first)] : false; +}; /** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`s are called in parallel, and the - * results are concatenated as they return. There is no guarantee that the - * results array will be returned in the original order of `coll` passed to the - * `iteratee` function. + * Return accepted encodings or best fit based on `encodings`. * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @example + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories - * }); - */ -var concat = doLimit(concatLimit, Infinity); - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * ['gzip', 'deflate'] * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). + * @param {String|Array} encodings... + * @return {String|Array} + * @public */ -var concatSeries = doLimit(concatLimit, 1); + +Accepts.prototype.encoding = Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_; // support flattened arguments + + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length); + + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i]; + } + } // no encodings, return all requested encodings + + + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings(); + } + + return this.negotiator.encodings(encodings)[0] || false; +}; /** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example + * Return accepted charsets or best fit based on `charsets`. * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); + * ['utf-8', 'utf-7', 'iso-8859-1'] * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ -var constant = function(/*...values*/) { - var values = slice(arguments); - var args = [null].concat(values); - return function (/*...ignoredArgs, callback*/) { - var callback = arguments[arguments.length - 1]; - return callback.apply(this, args); - }; -}; + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + + +Accepts.prototype.charset = Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_; // support flattened arguments + + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length); + + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i]; + } + } // no charsets, return all requested charsets + + + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets(); + } + return this.negotiator.charsets(charsets)[0] || false; +}; /** - * This method returns the first argument it receives. + * Return accepted languages or best fit based on `langs`. * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: * - * var object = { 'a': 1 }; + * ['es', 'pt', 'en'] * - * console.log(_.identity(object) === object); - * // => true + * @param {String|Array} langs... + * @return {Array|String} + * @public */ -function identity(value) { - return value; -} -function _createTester(check, getResult) { - return function(eachfn, arr, iteratee, cb) { - cb = cb || noop; - var testPassed = false; - var testResult; - eachfn(arr, function(value, _, callback) { - iteratee(value, function(err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, breakLoop); - } else { - callback(); - } - }); - }, function(err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} -function _findGetResult(v, x) { - return x; -} +Accepts.prototype.lang = Accepts.prototype.langs = Accepts.prototype.language = Accepts.prototype.languages = function (languages_) { + var languages = languages_; // support flattened arguments -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length); - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -var detect = doParallel(_createTester(identity, _findGetResult)); + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i]; + } + } // no languages, return all requested languages + + + if (!languages || languages.length === 0) { + return this.negotiator.languages(); + } + return this.negotiator.languages(languages)[0] || false; +}; /** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. + * Convert extnames to mime. * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). + * @param {String} type + * @return {String} + * @private */ -var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); + +function extToMime(type) { + return type.indexOf('/') === -1 ? mime.lookup(type) : type; +} /** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * Check if mime is valid. * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). + * @param {String} type + * @return {String} + * @private */ -var detectSeries = doLimit(detectLimit, 1); -function consoleFunc(name) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - args.push(function (err/*, ...args*/) { - var args = slice(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - arrayEach(args, function (x) { - console[name](x); - }); - } - } - }); - wrapAsync(fn).apply(null, args); - }; + +function validMime(type) { + return typeof type === 'string'; } -/** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -var dir = consoleFunc('dir'); +},{"mime-types":2299,"negotiator":2452}],34:[function(require,module,exports){ +"use strict"; -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); +module.exports = after; - function next(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - args.push(check); - _test.apply(this, args); - } +function after(count, callback, err_cb) { + var bail = false; + err_cb = err_cb || noop; + proxy.count = count; + return count === 0 ? callback() : proxy; - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); + function proxy(err, result) { + if (proxy.count <= 0) { + throw new Error('after called too many times'); } - check(null, true); + --proxy.count; // after first error, rest are passed to err_cb + + if (err) { + bail = true; + callback(err); // future error callbacks will go to error handler + callback = err_cb; + } else if (proxy.count === 0 && !bail) { + callback(null, result); + } + } } +function noop() {} + +},{}],35:[function(require,module,exports){ +'use strict'; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var compileSchema = require('./compile'), + resolve = require('./compile/resolve'), + Cache = require('./cache'), + SchemaObject = require('./compile/schema_obj'), + stableStringify = require('fast-json-stable-stringify'), + formats = require('./compile/formats'), + rules = require('./compile/rules'), + $dataMetaSchema = require('./data'), + util = require('./compile/util'); + +module.exports = Ajv; +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; +Ajv.prototype.compileAsync = require('./compile/async'); + +var customKeyword = require('./keyword'); + +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = require('./compile/error_classes'); + +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; +var META_IGNORE_OPTIONS = ['removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults']; +var META_SUPPORT_DATA = ['/properties']; +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ + +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + this._cache = opts.cache || new Cache(); + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + if (opts.formats) addInitialFormats(this); + addDefaultMetaSchema(this); + if (_typeof(opts.meta) == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', { + metaSchema: { + type: 'boolean' + } + }); + addInitialSchemas(this); +} /** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). */ -function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} + +function validate(schemaKeyRef, data) { + var v; + + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + + v = schemaObj.validate || this._compile(schemaObj); + } + + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} /** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function */ -function doUntil(iteratee, test, callback) { - doWhilst(iteratee, function() { - return !test.apply(this, arguments); - }, callback); -} + +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + + return schemaObj.validate || this._compile(schemaObj); +} /** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining */ -function during(test, fn, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - function next(err) { - if (err) return callback(err); - _test(check); - } - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)) { + for (var i = 0; i < schema.length; i++) { + this.addSchema(schema[i], undefined, _skipValidation, _meta); } - _test(check); -} + return this; + } -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} + var id = this._getId(schema); + if (id !== undefined && typeof id != 'string') throw new Error('schema id must be string'); + key = resolve.normalizeId(key || id); + checkUnique(this, key); + this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true); + return this; +} /** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @this Ajv + * @param {Object} schema schema object + * @param {String} key optional schema key + * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema + * @return {Ajv} this for method chaining */ -function eachLimit(coll, iteratee, callback) { - eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} + +function addMetaSchema(schema, key, skipValidation) { + this.addSchema(schema, key, skipValidation, true); + return this; +} /** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * Validate schema + * @this Ajv + * @param {Object} schema schema to validate + * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid + * @return {Boolean} true if schema is valid */ -function eachLimit$1(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + + +function validateSchema(schema, throwOrLogError) { + var $schema = schema.$schema; + if ($schema !== undefined && typeof $schema != 'string') throw new Error('$schema must be a string'); + $schema = $schema || this._opts.defaultMeta || defaultMeta(this); + + if (!$schema) { + this.logger.warn('meta-schema not available'); + this.errors = null; + return true; + } + + var valid = this.validate($schema, schema); + + if (!valid && throwOrLogError) { + var message = 'schema is invalid: ' + this.errorsText(); + if (this._opts.validateSchema == 'log') this.logger.error(message);else throw new Error(message); + } + + return valid; } +function defaultMeta(self) { + var meta = self._opts.meta; + self._opts.defaultMeta = _typeof(meta) == 'object' ? self._getId(meta) || meta : self.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined; + return self._opts.defaultMeta; +} /** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * Get compiled schema from the instance by `key` or `ref`. + * @this Ajv + * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). */ -var eachSeries = doLimit(eachLimit$1, 1); -/** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ -function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return initialParams(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - setImmediate$1(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; + +function getSchema(keyRef) { + var schemaObj = _getSchemaObj(this, keyRef); + + switch (_typeof(schemaObj)) { + case 'object': + return schemaObj.validate || this._compile(schemaObj); + + case 'string': + return this.getSchema(schemaObj); + + case 'undefined': + return _getSchemaFragment(this, keyRef); + } +} + +function _getSchemaFragment(self, ref) { + var res = resolve.schema.call(self, { + schema: {} + }, ref); + + if (res) { + var schema = res.schema, + root = res.root, + baseId = res.baseId; + var v = compileSchema.call(self, schema, root, undefined, baseId); + self._fragments[ref] = new SchemaObject({ + ref: ref, + fragment: true, + schema: schema, + root: root, + baseId: baseId, + validate: v }); + return v; + } } -function notId(v) { - return !v; +function _getSchemaObj(self, keyRef) { + keyRef = resolve.normalizeId(keyRef); + return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; } - /** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @this Ajv + * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object + * @return {Ajv} this for method chaining */ -var every = doParallel(_createTester(notId, notId)); -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everyLimit = doParallelLimit(_createTester(notId, notId)); -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everySeries = doLimit(everyLimit, 1); +function removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + _removeAllSchemas(this, this._schemas, schemaKeyRef); -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; + _removeAllSchemas(this, this._refs, schemaKeyRef); + + return this; + } + + switch (_typeof(schemaKeyRef)) { + case 'undefined': + _removeAllSchemas(this, this._schemas); + + _removeAllSchemas(this, this._refs); + + this._cache.clear(); + + return this; + + case 'string': + var schemaObj = _getSchemaObj(this, schemaKeyRef); + + if (schemaObj) this._cache.del(schemaObj.cacheKey); + delete this._schemas[schemaKeyRef]; + delete this._refs[schemaKeyRef]; + return this; + + case 'object': + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; + + this._cache.del(cacheKey); + + var id = this._getId(schemaKeyRef); + + if (id) { + id = resolve.normalizeId(id); + delete this._schemas[id]; + delete this._refs[id]; + } + + } + + return this; } -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); +function _removeAllSchemas(self, schemas, regex) { + for (var keyRef in schemas) { + var schemaObj = schemas[keyRef]; + + if (!schemaObj.meta && (!regex || regex.test(keyRef))) { + self._cache.del(schemaObj.cacheKey); + + delete schemas[keyRef]; + } + } } +/* @this Ajv */ -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({index: index, value: x}); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, arrayMap(results.sort(function (a, b) { - return a.index - b.index; - }), baseProperty('value'))); - } - }); + +function _addSchema(schema, skipValidation, meta, shouldAddSchema) { + if (_typeof(schema) != 'object' && typeof schema != 'boolean') throw new Error('schema should be object or boolean'); + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schema) : schema; + + var cached = this._cache.get(cacheKey); + + if (cached) return cached; + shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; + var id = resolve.normalizeId(this._getId(schema)); + if (id && shouldAddSchema) checkUnique(this, id); + var willValidate = this._opts.validateSchema !== false && !skipValidation; + var recursiveMeta; + if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) this.validateSchema(schema, true); + var localRefs = resolve.ids.call(this, schema); + var schemaObj = new SchemaObject({ + id: id, + schema: schema, + localRefs: localRefs, + cacheKey: cacheKey, + meta: meta + }); + if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; + + this._cache.put(cacheKey, schemaObj); + + if (willValidate && recursiveMeta) this.validateSchema(schema, true); + return schemaObj; } +/* @this Ajv */ -function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, wrapAsync(iteratee), callback || noop); + +function _compile(schemaObj, root) { + if (schemaObj.compiling) { + schemaObj.validate = callValidate; + callValidate.schema = schemaObj.schema; + callValidate.errors = null; + callValidate.root = root ? root : callValidate; + if (schemaObj.schema.$async === true) callValidate.$async = true; + return callValidate; + } + + schemaObj.compiling = true; + var currentOpts; + + if (schemaObj.meta) { + currentOpts = this._opts; + this._opts = this._metaOpts; + } + + var v; + + try { + v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); + } catch (e) { + delete schemaObj.validate; + throw e; + } finally { + schemaObj.compiling = false; + if (schemaObj.meta) this._opts = currentOpts; + } + + schemaObj.validate = v; + schemaObj.refs = v.refs; + schemaObj.refVal = v.refVal; + schemaObj.root = v.root; + return v; + /* @this {*} - custom context, see passContext option */ + + function callValidate() { + /* jshint validthis: true */ + var _validate = schemaObj.validate; + + var result = _validate.apply(this, arguments); + + callValidate.errors = _validate.errors; + return result; + } } -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -var filter = doParallel(_filter); +function chooseGetId(opts) { + switch (opts.schemaId) { + case 'auto': + return _get$IdOrId; + + case 'id': + return _getId; + + default: + return _get$Id; + } +} +/* @this Ajv */ + +function _getId(schema) { + if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); + return schema.id; +} +/* @this Ajv */ + + +function _get$Id(schema) { + if (schema.id) this.logger.warn('schema id ignored', schema.id); + return schema.$id; +} + +function _get$IdOrId(schema) { + if (schema.$id && schema.id && schema.$id != schema.id) throw new Error('schema $id is different from id'); + return schema.$id || schema.id; +} /** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). + * Convert array of error message objects to string + * @this Ajv + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions */ -var filterLimit = doParallelLimit(_filter); + +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + var text = ''; + + for (var i = 0; i < errors.length; i++) { + var e = errors[i]; + if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; + } + + return text.slice(0, -separator.length); +} /** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) + * Add custom format + * @this Ajv + * @param {String} name format name + * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) + * @return {Ajv} this for method chaining */ -var filterSeries = doLimit(filterLimit, 1); -/** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ -function forever(fn, errback) { - var done = onlyOnce(errback || noop); - var task = wrapAsync(ensureAsync(fn)); +function addFormat(name, format) { + if (typeof format == 'string') format = new RegExp(format); + this._formats[name] = format; + return this; +} - function next(err) { - if (err) return done(err); - task(next); - } - next(); +function addDefaultMetaSchema(self) { + var $dataSchema; + + if (self._opts.$data) { + $dataSchema = require('./refs/data.json'); + self.addMetaSchema($dataSchema, $dataSchema.$id, true); + } + + if (self._opts.meta === false) return; + + var metaSchema = require('./refs/json-schema-draft-07.json'); + + if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); + self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); + self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; } -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupByLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err, key) { - if (err) return callback(err); - return callback(null, {key: key, val: val}); - }); - }, function(err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; +function addInitialSchemas(self) { + var optsSchemas = self._opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);else for (var key in optsSchemas) { + self.addSchema(optsSchemas[key], key); + } +} - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; +function addInitialFormats(self) { + for (var name in self._opts.formats) { + var format = self._opts.formats[name]; + self.addFormat(name, format); + } +} - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } +function checkUnique(self, id) { + if (self._schemas[id] || self._refs[id]) throw new Error('schema with key or id "' + id + '" already exists'); +} - return callback(err, result); - }); +function getMetaSchemaOptions(self) { + var metaOpts = util.copy(self._opts); + + for (var i = 0; i < META_IGNORE_OPTIONS.length; i++) { + delete metaOpts[META_IGNORE_OPTIONS[i]]; + } + + return metaOpts; +} + +function setLogger(self) { + var logger = self._opts.logger; + + if (logger === false) { + self.logger = { + log: noop, + warn: noop, + error: noop + }; + } else { + if (logger === undefined) logger = console; + if (!(_typeof(logger) == 'object' && logger.log && logger.warn && logger.error)) throw new Error('logger must implement log, warn and error methods'); + self.logger = logger; + } +} + +function noop() {} + +},{"./cache":36,"./compile":40,"./compile/async":37,"./compile/error_classes":38,"./compile/formats":39,"./compile/resolve":41,"./compile/rules":42,"./compile/schema_obj":43,"./compile/util":45,"./data":46,"./keyword":73,"./refs/data.json":74,"./refs/json-schema-draft-07.json":76,"fast-json-stable-stringify":824}],36:[function(require,module,exports){ +'use strict'; + +var Cache = module.exports = function Cache() { + this._cache = {}; }; -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -var groupBy = doLimit(groupByLimit, Infinity); +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupBySeries = doLimit(groupByLimit, 1); +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; +}; -/** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -var log = consoleFunc('log'); +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; + +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; +}; + +},{}],37:[function(require,module,exports){ +'use strict'; +var MissingRefError = require('./error_classes').MissingRef; + +module.exports = compileAsync; /** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. + * @return {Promise} promise that resolves with a validating function. */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback || noop); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - eachOfLimit(obj, limit, function(val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); + +function compileAsync(schema, meta, callback) { + /* eslint no-shadow: 0 */ + + /* global Promise */ + + /* jshint validthis: true */ + var self = this; + if (typeof this._opts.loadSchema != 'function') throw new Error('options.loadSchema should be a function'); + + if (typeof meta == 'function') { + callback = meta; + meta = undefined; + } + + var p = loadMetaSchemaOf(schema).then(function () { + var schemaObj = self._addSchema(schema, undefined, meta); + + return schemaObj.validate || _compileAsync(schemaObj); + }); + + if (callback) { + p.then(function (v) { + callback(null, v); + }, callback); + } + + return p; + + function loadMetaSchemaOf(sch) { + var $schema = sch.$schema; + return $schema && !self.getSchema($schema) ? compileAsync.call(self, { + $ref: $schema + }, true) : Promise.resolve(); + } + + function _compileAsync(schemaObj) { + try { + return self._compile(schemaObj); + } catch (e) { + if (e instanceof MissingRefError) return loadMissingSchema(e); + throw e; + } + + function loadMissingSchema(e) { + var ref = e.missingSchema; + if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); + var schemaPromise = self._loadingSchemas[ref]; + + if (!schemaPromise) { + schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); + schemaPromise.then(removePromise, removePromise); + } + + return schemaPromise.then(function (sch) { + if (!added(ref)) { + return loadMetaSchemaOf(sch).then(function () { + if (!added(ref)) self.addSchema(sch, ref, undefined, meta); + }); + } + }).then(function () { + return _compileAsync(schemaObj); + }); + + function removePromise() { + delete self._loadingSchemas[ref]; + } + + function added(ref) { + return self._refs[ref] || self._schemas[ref]; + } + } + } } -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ +},{"./error_classes":38}],38:[function(require,module,exports){ +'use strict'; -var mapValues = doLimit(mapValuesLimit, Infinity); +var resolve = require('./resolve'); -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -var mapValuesSeries = doLimit(mapValuesLimit, 1); +module.exports = { + Validation: errorSubclass(ValidationError), + MissingRef: errorSubclass(MissingRefError) +}; -function has(obj, key) { - return key in obj; +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; +} + +MissingRefError.message = function (baseId, ref) { + return 'can\'t resolve reference ' + ref + ' from id ' + baseId; +}; + +function MissingRefError(baseId, ref, message) { + this.message = message || MissingRefError.message(baseId, ref); + this.missingRef = resolve.url(baseId, ref); + this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); +} + +function errorSubclass(Subclass) { + Subclass.prototype = Object.create(Error.prototype); + Subclass.prototype.constructor = Subclass; + return Subclass; +} + +},{"./resolve":41}],39:[function(require,module,exports){ +'use strict'; + +var util = require('./util'); + +var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i; +var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i; +var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; // uri-template: https://tools.ietf.org/html/rfc6570 + +var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; // For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; + +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: hostname, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone); +} + +var DATE_TIME_SEPARATOR = /t|\s/i; + +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + +function hostname(str) { + // https://tools.ietf.org/html/rfc1034#section-3.5 + // https://tools.ietf.org/html/rfc1123#section-2 + return str.length <= 255 && HOSTNAME.test(str); +} + +var NOT_URI_FRAGMENT = /\/|:/; + +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + +var Z_ANCHOR = /[^\\]\\Z/; + +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } } +},{"./util":45}],40:[function(require,module,exports){ +'use strict'; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var resolve = require('./resolve'), + util = require('./util'), + errorClasses = require('./error_classes'), + stableStringify = require('fast-json-stable-stringify'); + +var validateGenerator = require('../dotjs/validate'); /** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); + * Functions below are used inside compiled validations function */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || identity; - var _fn = wrapAsync(fn); - var memoized = initialParams(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - setImmediate$1(function() { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function(/*args*/) { - var args = slice(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} + +var ucs2length = util.ucs2length; + +var equal = require('fast-deep-equal'); // this error is thrown by async schemas to return validation errors via exception + + +var ValidationError = errorClasses.Validation; +module.exports = compile; /** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTick`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function */ -var _defer$1; -if (hasNextTick) { - _defer$1 = process.nextTick; -} else if (hasSetImmediate) { - _defer$1 = setImmediate; -} else { - _defer$1 = fallback; -} +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ -var nextTick = wrap(_defer$1); + /* eslint no-shadow: 0 */ + var self = this, + opts = this._opts, + refVal = [undefined], + refs = {}, + patterns = [], + patternsHash = {}, + defaults = [], + defaultsHash = {}, + customRules = []; + root = root || { + schema: schema, + refVal: refVal, + refs: refs + }; + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return compilation.callValidate = callValidate; + var formats = this._formats; + var RULES = this.RULES; -function _parallel(eachfn, tasks, callback) { - callback = callback || noop; - var results = isArrayLike(tasks) ? [] : {}; + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; - eachfn(tasks, function (task, key, callback) { - wrapAsync(task)(function (err, result) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + /* @this {*} - custom context, see passContext option */ + + + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || _root && _root.schema == _schema; + if (_root.schema != root.schema) return compile.call(self, _schema, _root, localRefs, baseId); + var $async = _schema.$async === true; + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self }); -} + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode; + if (opts.processCode) sourceCode = opts.processCode(sourceCode); // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - _parallel(eachOf, tasks, callback); -} + var validate; -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit$1(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); -} + try { + var makeValidate = new Function('self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'equal', 'ucs2length', 'ValidationError', sourceCode); + validate = makeValidate(self, RULES, formats, root, refVal, defaults, customRules, equal, ucs2length, ValidationError); + refVal[0] = validate; + } catch (e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ -var queue$1 = function (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * The `unshift` method was removed. - */ -var priorityQueue = function(worker, concurrency) { - // Start with a normal queue - var q = queue$1(worker, concurrency); + return validate; + } - // Override push to accept second parameter representing priority - q.push = function(data, priority, callback) { - if (callback == null) callback = noop; - if (typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + + var _refVal, refCode; + + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function removeLocalRef(ref) { + delete refs[ref]; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return _typeof(refVal) == 'object' || typeof refVal == 'boolean' ? { + code: code, + schema: refVal, + inline: true + } : { + code: code, + $async: refVal && !!refVal.$async + }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + + return 'pattern' + index; + } + + function useDefault(value) { + switch (_typeof(value)) { + case 'boolean': + case 'number': + return '' + value; + + case 'string': + return util.toQuotedString(value); + + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; } - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; + return 'default' + index; + } + } - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function (keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + var validateSchema = rule.definition.validateSchema; + + if (validateSchema) { + var valid = validateSchema(schema); + + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message);else throw new Error(message); } - setImmediate$1(q.process); - }; + } + } - // Remove unshift function - delete q.unshift; + var compile = rule.definition.compile, + inline = rule.definition.inline, + macro = rule.definition.macro; + var validate; - return q; -}; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } + if (validate === undefined) throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + var index = customRules.length; + customRules[index] = validate; + return { + code: 'customRule' + index, + validate: validate + }; + } +} /** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) */ -function race(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } -} + +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { + index: index, + compiling: true + }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { + index: index, + compiling: false + }; +} /** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID */ -function reduceRight (array, memo, iteratee, callback) { - var reversed = slice(array).reverse(); - reduce(reversed, memo, iteratee, callback); -} + +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} /** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index */ -function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = slice(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); - return _fn.apply(this, args); - }); + +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i = 0; i < this._compilations.length; i++) { + var c = this._compilations[i]; + if (c.schema == schema && c.root == root && c.baseId == baseId) return i; + } + + return -1; } -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if (isArray(tasks)) { - results = arrayMap(tasks, reflect); - } else { - results = {}; - baseForOwn(tasks, function(task, key) { - results[key] = reflect.call(this, task); - }); - } - return results; +function patternCode(i, patterns) { + return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');'; } -function reject$1(eachfn, arr, iteratee, callback) { - _filter(eachfn, arr, function(value, cb) { - iteratee(value, function(err, v) { - cb(err, !v); - }); - }, callback); +function defaultCode(i) { + return 'var default' + i + ' = defaults[' + i + '];'; } -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -var reject = doParallel(reject$1); +function refValCode(i, refVal) { + return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];'; +} -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectLimit = doParallelLimit(reject$1); +function customRuleCode(i) { + return 'var customRule' + i + ' = customRules[' + i + '];'; +} + +function vars(arr, statement) { + if (!arr.length) return ''; + var code = ''; + for (var i = 0; i < arr.length; i++) { + code += statement(i, arr); + } + + return code; +} + +},{"../dotjs/validate":72,"./error_classes":38,"./resolve":41,"./util":45,"fast-deep-equal":823,"fast-json-stable-stringify":824}],41:[function(require,module,exports){ +'use strict'; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var URI = require('uri-js'), + equal = require('fast-deep-equal'), + util = require('./util'), + SchemaObject = require('./schema_obj'), + traverse = require('json-schema-traverse'); + +module.exports = resolve; +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; /** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). + * [resolve and compile the references ($ref)] + * @this Ajv + * @param {Function} compile reference to schema compilation funciton (localCompile) + * @param {Object} root object with information about the root schema for the current schema + * @param {String} ref reference to resolve + * @return {Object|Function} schema object (if the schema can be inlined) or validation function */ -var rejectSeries = doLimit(rejectLimit, 1); +function resolve(compile, root, ref) { + /* jshint validthis: true */ + var refVal = this._refs[ref]; + + if (typeof refVal == 'string') { + if (this._refs[refVal]) refVal = this._refs[refVal];else return resolve.call(this, compile, root, refVal); + } + + refVal = refVal || this._schemas[ref]; + + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal); + } + + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } + + if (schema instanceof SchemaObject) { + v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); + } else if (schema !== undefined) { + v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, undefined, baseId); + } + + return v; +} /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true + * Resolve schema, its root and baseId + * @this Ajv + * @param {Object} root root object with properties schema, refVal, refs + * @param {String} ref reference to resolve + * @return {Object} object with properties schema, root, baseId */ -function constant$1(value) { - return function() { - return value; - }; + + +function resolveSchema(root, ref) { + /* jshint validthis: true */ + var p = URI.parse(ref), + refPath = _getFullPath(p), + baseId = getFullPath(this._getId(root.schema)); + + if (Object.keys(root.schema).length === 0 || refPath !== baseId) { + var id = normalizeId(refPath); + var refVal = this._refs[id]; + + if (typeof refVal == 'string') { + return resolveRecursive.call(this, root, refVal, p); + } else if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + root = refVal; + } else { + refVal = this._schemas[id]; + + if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + if (id == normalizeId(ref)) return { + schema: refVal, + root: root, + baseId: baseId + }; + root = refVal; + } else { + return; + } + } + + if (!root.schema) return; + baseId = getFullPath(this._getId(root.schema)); + } + + return getJsonPointer.call(this, p, baseId, root.schema, root); } +/* @this Ajv */ -/** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; +function resolveRecursive(root, ref, parsedRef) { + /* jshint validthis: true */ + var res = resolveSchema.call(this, root, ref); - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; + if (res) { + var schema = res.schema; + var baseId = res.baseId; + root = res.root; - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); + var id = this._getId(schema); - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); + if (id) baseId = resolveUrl(baseId, id); + return getJsonPointer.call(this, parsedRef, baseId, schema, root); + } +} + +var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); +/* @this Ajv */ + +function getJsonPointer(parsedRef, baseId, schema, root) { + /* jshint validthis: true */ + parsedRef.fragment = parsedRef.fragment || ''; + if (parsedRef.fragment.slice(0, 1) != '/') return; + var parts = parsedRef.fragment.split('/'); + + for (var i = 1; i < parts.length; i++) { + var part = parts[i]; + + if (part) { + part = util.unescapeFragment(part); + schema = schema[part]; + if (schema === undefined) break; + var id; + + if (!PREVENT_SCOPE_CHANGE[part]) { + id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + + if (schema.$ref) { + var $ref = resolveUrl(baseId, schema.$ref); + var res = resolveSchema.call(this, root, $ref); + + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } } + } } + } - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || noop; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || noop; - } + if (schema !== undefined && schema !== root.schema) return { + schema: schema, + root: root, + baseId: baseId + }; +} - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } +var SIMPLE_INLINED = util.toHash(['type', 'format', 'pattern', 'maxLength', 'minLength', 'maxProperties', 'minProperties', 'maxItems', 'minItems', 'maximum', 'minimum', 'uniqueItems', 'multipleOf', 'required', 'enum']); - var _task = wrapAsync(task); +function inlineRef(schema, limit) { + if (limit === false) return false; + if (limit === undefined || limit === true) return checkNoRef(schema);else if (limit) return countKeys(schema) <= limit; +} - var attempt = 1; - function retryAttempt() { - _task(function(err) { - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); +function checkNoRef(schema) { + var item; + + if (Array.isArray(schema)) { + for (var i = 0; i < schema.length; i++) { + item = schema[i]; + if (_typeof(item) == 'object' && !checkNoRef(item)) return false; + } + } else { + for (var key in schema) { + if (key == '$ref') return false; + item = schema[key]; + if (_typeof(item) == 'object' && !checkNoRef(item)) return false; } + } - retryAttempt(); + return true; } -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ -var retryable = function (opts, task) { - if (!task) { - task = opts; - opts = null; +function countKeys(schema) { + var count = 0, + item; + + if (Array.isArray(schema)) { + for (var i = 0; i < schema.length; i++) { + item = schema[i]; + if (_typeof(item) == 'object') count += countKeys(item); + if (count == Infinity) return Infinity; } - var _task = wrapAsync(task); - return initialParams(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } + } else { + for (var key in schema) { + if (key == '$ref') return Infinity; - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); + if (SIMPLE_INLINED[key]) { + count++; + } else { + item = schema[key]; + if (_typeof(item) == 'object') count += countKeys(item) + 1; + if (count == Infinity) return Infinity; + } + } + } - }); -}; + return count; +} -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - _parallel(eachOfSeries, tasks, callback); +function getFullPath(id, normalize) { + if (normalize !== false) id = normalizeId(id); + var p = URI.parse(id); + return _getFullPath(p); } -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -var some = doParallel(_createTester(Boolean, identity)); +function _getFullPath(p) { + return URI.serialize(p).split('#')[0] + '#'; +} -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someLimit = doParallelLimit(_createTester(Boolean, identity)); +var TRAILING_SLASH_HASH = /#\/?$/; -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someSeries = doLimit(someLimit, 1); +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; +} -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); - * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); - * - * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback - * }); - */ -function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - map(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, {value: x, criteria: criteria}); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); - }); +function resolveUrl(baseId, id) { + id = normalizeId(id); + return URI.resolve(baseId, id); +} +/* @this Ajv */ - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; + +function resolveIds(schema) { + var schemaId = normalizeId(this._getId(schema)); + var baseIds = { + '': schemaId + }; + var fullPaths = { + '': getFullPath(schemaId, false) + }; + var localRefs = {}; + var self = this; + traverse(schema, { + allKeys: true + }, function (sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (jsonPtr === '') return; + + var id = self._getId(sch); + + var baseId = baseIds[parentJsonPtr]; + var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword; + if (keyIndex !== undefined) fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex)); + + if (typeof id == 'string') { + id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); + var refVal = self._refs[id]; + if (typeof refVal == 'string') refVal = self._refs[refVal]; + + if (refVal && refVal.schema) { + if (!equal(sch, refVal.schema)) throw new Error('id "' + id + '" resolves to more than one schema'); + } else if (id != normalizeId(fullPath)) { + if (id[0] == '#') { + if (localRefs[id] && !equal(sch, localRefs[id])) throw new Error('id "' + id + '" resolves to more than one schema'); + localRefs[id] = sch; + } else { + self._refs[id] = fullPath; + } + } } + + baseIds[jsonPtr] = baseId; + fullPaths[jsonPtr] = fullPath; + }); + return localRefs; } -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); +},{"./schema_obj":43,"./util":45,"fast-deep-equal":823,"json-schema-traverse":1509,"uri-js":2951}],42:[function(require,module,exports){ +'use strict'; - return initialParams(function (args, callback) { - var timedOut = false; - var timer; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } +var ruleModules = require('../dotjs'), + toHash = require('./util').toHash; - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } +module.exports = function rules() { + var RULES = [{ + type: 'number', + rules: [{ + 'maximum': ['exclusiveMaximum'] + }, { + 'minimum': ['exclusiveMinimum'] + }, 'multipleOf', 'format'] + }, { + type: 'string', + rules: ['maxLength', 'minLength', 'pattern', 'format'] + }, { + type: 'array', + rules: ['maxItems', 'minItems', 'items', 'contains', 'uniqueItems'] + }, { + type: 'object', + rules: ['maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', { + 'properties': ['additionalProperties', 'patternProperties'] + }] + }, { + rules: ['$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if'] + }]; + var ALL = ['type', '$comment']; + var KEYWORDS = ['$schema', '$id', 'id', '$data', '$async', 'title', 'description', 'default', 'definitions', 'examples', 'readOnly', 'writeOnly', 'contentMediaType', 'contentEncoding', 'additionalItems', 'then', 'else']; + var TYPES = ['number', 'integer', 'string', 'array', 'object', 'boolean', 'null']; + RULES.all = toHash(ALL); + RULES.types = toHash(TYPES); + RULES.forEach(function (group) { + group.rules = group.rules.map(function (keyword) { + var implKeywords; + + if (_typeof(keyword) == 'object') { + var key = Object.keys(keyword)[0]; + implKeywords = keyword[key]; + keyword = key; + implKeywords.forEach(function (k) { + ALL.push(k); + RULES.all[k] = true; }); + } - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); + ALL.push(keyword); + var rule = RULES.all[keyword] = { + keyword: keyword, + code: ruleModules[keyword], + "implements": implKeywords + }; + return rule; }); -} + RULES.all.$comment = { + keyword: '$comment', + code: ruleModules.$comment + }; + if (group.type) RULES.types[group.type] = group; + }); + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.custom = {}; + return RULES; +}; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeCeil = Math.ceil; -var nativeMax = Math.max; +},{"../dotjs":61,"./util":45}],43:[function(require,module,exports){ +'use strict'; -/** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ -function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); +var util = require('./util'); - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; -} +module.exports = SchemaObject; -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); +function SchemaObject(obj) { + util.copy(obj, this); } -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ -var times = doLimit(timeLimit, Infinity); +},{"./util":45}],44:[function(require,module,exports){ +'use strict'; // https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -var timesSeries = doLimit(timeLimit, 1); +module.exports = function ucs2length(str) { + var length = 0, + len = str.length, + pos = 0, + value; -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = isArray(coll) ? [] : {}; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + + if (value >= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate } - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); + } - eachOf(coll, function(v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function(err) { - callback(err, accumulator); - }); -} + return length; +}; -/** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || noop; - eachSeries(tasks, function(task, callback) { - wrapAsync(task)(function (err, res/*, ...args*/) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); -} +},{}],45:[function(require,module,exports){ +'use strict'; -/** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; -} +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: require('fast-deep-equal'), + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + cleanUpCode: cleanUpCode, + finalCleanUpCode: finalCleanUpCode, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + +function copy(o, to) { + to = to || {}; + + for (var key in o) { + to[key] = o[key]; + } + + return to; +} + +function checkDataType(dataType, data, negate) { + var EQUAL = negate ? ' !== ' : ' === ', + AND = negate ? ' || ' : ' && ', + OK = negate ? '!' : '', + NOT = negate ? '' : '!'; + + switch (dataType) { + case 'null': + return data + EQUAL + 'null'; + + case 'array': + return OK + 'Array.isArray(' + data + ')'; -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - if (!test()) return callback(null); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = slice(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} + case 'object': + return '(' + OK + data + AND + 'typeof ' + data + EQUAL + '"object"' + AND + NOT + 'Array.isArray(' + data + '))'; -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - whilst(function() { - return !test.apply(this, arguments); - }, iteratee, callback); -} + case 'integer': + return '(typeof ' + data + EQUAL + '"number"' + AND + NOT + '(' + data + ' % 1)' + AND + data + EQUAL + data + ')'; -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -var waterfall = function(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; + default: + return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - args.push(onlyOnce(next)); - task.apply(null, args); - } +function checkDataTypes(dataTypes, data) { + switch (dataTypes.length) { + case 1: + return checkDataType(dataTypes[0], data, true); - function next(err/*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask(slice(arguments, 1)); - } + default: + var code = ''; + var types = toHash(dataTypes); - nextTask([]); -}; + if (types.array && types.object) { + code = types["null"] ? '(' : '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types["null"]; + delete types.array; + delete types.object; + } -/** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ + if (types.number) delete types.integer; -/** - * Async is a utility module which provides straight-forward, powerful functions - * for working with asynchronous JavaScript. Although originally designed for - * use with [Node.js](http://nodejs.org) and installable via - * `npm install --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ + for (var t in types) { + code += (code ? ' && ' : '') + checkDataType(t, data, true); + } + return code; + } +} -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ +var COERCE_TO_TYPES = toHash(['string', 'number', 'integer', 'boolean', 'null']); -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; -/** - * A collection of `async` utility functions. - * @module Utils - */ + for (var i = 0; i < dataTypes.length; i++) { + var t = dataTypes[i]; + if (COERCE_TO_TYPES[t]) types[types.length] = t;else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t; + } -var index = { - apply: apply, - applyEach: applyEach, - applyEachSeries: applyEachSeries, - asyncify: asyncify, - auto: auto, - autoInject: autoInject, - cargo: cargo, - compose: compose, - concat: concat, - concatLimit: concatLimit, - concatSeries: concatSeries, - constant: constant, - detect: detect, - detectLimit: detectLimit, - detectSeries: detectSeries, - dir: dir, - doDuring: doDuring, - doUntil: doUntil, - doWhilst: doWhilst, - during: during, - each: eachLimit, - eachLimit: eachLimit$1, - eachOf: eachOf, - eachOfLimit: eachOfLimit, - eachOfSeries: eachOfSeries, - eachSeries: eachSeries, - ensureAsync: ensureAsync, - every: every, - everyLimit: everyLimit, - everySeries: everySeries, - filter: filter, - filterLimit: filterLimit, - filterSeries: filterSeries, - forever: forever, - groupBy: groupBy, - groupByLimit: groupByLimit, - groupBySeries: groupBySeries, - log: log, - map: map, - mapLimit: mapLimit, - mapSeries: mapSeries, - mapValues: mapValues, - mapValuesLimit: mapValuesLimit, - mapValuesSeries: mapValuesSeries, - memoize: memoize, - nextTick: nextTick, - parallel: parallelLimit, - parallelLimit: parallelLimit$1, - priorityQueue: priorityQueue, - queue: queue$1, - race: race, - reduce: reduce, - reduceRight: reduceRight, - reflect: reflect, - reflectAll: reflectAll, - reject: reject, - rejectLimit: rejectLimit, - rejectSeries: rejectSeries, - retry: retry, - retryable: retryable, - seq: seq, - series: series, - setImmediate: setImmediate$1, - some: some, - someLimit: someLimit, - someSeries: someSeries, - sortBy: sortBy, - timeout: timeout, - times: times, - timesLimit: timeLimit, - timesSeries: timesSeries, - transform: transform, - tryEach: tryEach, - unmemoize: unmemoize, - until: until, - waterfall: waterfall, - whilst: whilst, + if (types.length) return types; + } else if (COERCE_TO_TYPES[dataTypes]) { + return [dataTypes]; + } else if (optionCoerceTypes === 'array' && dataTypes === 'array') { + return ['array']; + } +} - // aliases - all: every, - allLimit: everyLimit, - allSeries: everySeries, - any: some, - anyLimit: someLimit, - anySeries: someSeries, - find: detect, - findLimit: detectLimit, - findSeries: detectSeries, - forEach: eachLimit, - forEachSeries: eachSeries, - forEachLimit: eachLimit$1, - forEachOf: eachOf, - forEachOfSeries: eachOfSeries, - forEachOfLimit: eachOfLimit, - inject: reduce, - foldl: reduce, - foldr: reduceRight, - select: filter, - selectLimit: filterLimit, - selectSeries: filterSeries, - wrapSync: asyncify -}; +function toHash(arr) { + var hash = {}; -exports['default'] = index; -exports.apply = apply; -exports.applyEach = applyEach; -exports.applyEachSeries = applyEachSeries; -exports.asyncify = asyncify; -exports.auto = auto; -exports.autoInject = autoInject; -exports.cargo = cargo; -exports.compose = compose; -exports.concat = concat; -exports.concatLimit = concatLimit; -exports.concatSeries = concatSeries; -exports.constant = constant; -exports.detect = detect; -exports.detectLimit = detectLimit; -exports.detectSeries = detectSeries; -exports.dir = dir; -exports.doDuring = doDuring; -exports.doUntil = doUntil; -exports.doWhilst = doWhilst; -exports.during = during; -exports.each = eachLimit; -exports.eachLimit = eachLimit$1; -exports.eachOf = eachOf; -exports.eachOfLimit = eachOfLimit; -exports.eachOfSeries = eachOfSeries; -exports.eachSeries = eachSeries; -exports.ensureAsync = ensureAsync; -exports.every = every; -exports.everyLimit = everyLimit; -exports.everySeries = everySeries; -exports.filter = filter; -exports.filterLimit = filterLimit; -exports.filterSeries = filterSeries; -exports.forever = forever; -exports.groupBy = groupBy; -exports.groupByLimit = groupByLimit; -exports.groupBySeries = groupBySeries; -exports.log = log; -exports.map = map; -exports.mapLimit = mapLimit; -exports.mapSeries = mapSeries; -exports.mapValues = mapValues; -exports.mapValuesLimit = mapValuesLimit; -exports.mapValuesSeries = mapValuesSeries; -exports.memoize = memoize; -exports.nextTick = nextTick; -exports.parallel = parallelLimit; -exports.parallelLimit = parallelLimit$1; -exports.priorityQueue = priorityQueue; -exports.queue = queue$1; -exports.race = race; -exports.reduce = reduce; -exports.reduceRight = reduceRight; -exports.reflect = reflect; -exports.reflectAll = reflectAll; -exports.reject = reject; -exports.rejectLimit = rejectLimit; -exports.rejectSeries = rejectSeries; -exports.retry = retry; -exports.retryable = retryable; -exports.seq = seq; -exports.series = series; -exports.setImmediate = setImmediate$1; -exports.some = some; -exports.someLimit = someLimit; -exports.someSeries = someSeries; -exports.sortBy = sortBy; -exports.timeout = timeout; -exports.times = times; -exports.timesLimit = timeLimit; -exports.timesSeries = timesSeries; -exports.transform = transform; -exports.tryEach = tryEach; -exports.unmemoize = unmemoize; -exports.until = until; -exports.waterfall = waterfall; -exports.whilst = whilst; -exports.all = every; -exports.allLimit = everyLimit; -exports.allSeries = everySeries; -exports.any = some; -exports.anyLimit = someLimit; -exports.anySeries = someSeries; -exports.find = detect; -exports.findLimit = detectLimit; -exports.findSeries = detectSeries; -exports.forEach = eachLimit; -exports.forEachSeries = eachSeries; -exports.forEachLimit = eachLimit$1; -exports.forEachOf = eachOf; -exports.forEachOfSeries = eachOfSeries; -exports.forEachOfLimit = eachOfLimit; -exports.inject = reduce; -exports.foldl = reduce; -exports.foldr = reduceRight; -exports.select = filter; -exports.selectLimit = filterLimit; -exports.selectSeries = filterSeries; -exports.wrapSync = asyncify; - -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); - -},{}],22:[function(require,module,exports){ -'use strict'; + for (var i = 0; i < arr.length; i++) { + hash[arr[i]] = true; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doUntil; + return hash; +} -var _doWhilst = require('./doWhilst'); +var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; +var SINGLE_QUOTE = /'|\\/g; -var _doWhilst2 = _interopRequireDefault(_doWhilst); +function getProperty(key) { + return typeof key == 'number' ? '[' + key + ']' : IDENTIFIER.test(key) ? '.' + key : "['" + escapeQuotes(key) + "']"; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function escapeQuotes(str) { + return str.replace(SINGLE_QUOTE, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\f/g, '\\f').replace(/\t/g, '\\t'); +} -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - (0, _doWhilst2.default)(iteratee, function () { - return !test.apply(this, arguments); - }, callback); +function varOccurences(str, dataVar) { + dataVar += '[^0-9]'; + var matches = str.match(new RegExp(dataVar, 'g')); + return matches ? matches.length : 0; } -module.exports = exports['default']; -},{"./doWhilst":23}],23:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doWhilst; +function varReplace(str, dataVar, expr) { + dataVar += '([^0-9])'; + expr = expr.replace(/\$/g, '$$$$'); + return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); +} -var _noop = require('lodash/noop'); +var EMPTY_ELSE = /else\s*{\s*}/g, + EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g, + EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g; -var _noop2 = _interopRequireDefault(_noop); +function cleanUpCode(out) { + return out.replace(EMPTY_ELSE, '').replace(EMPTY_IF_NO_ELSE, '').replace(EMPTY_IF_WITH_ELSE, 'if (!($1))'); +} -var _slice = require('./internal/slice'); +var ERRORS_REGEXP = /[^v.]errors/g, + REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g, + REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g, + RETURN_VALID = 'return errors === 0;', + RETURN_TRUE = 'validate.errors = null; return true;', + RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/, + RETURN_DATA_ASYNC = 'return data;', + ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g, + REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/; -var _slice2 = _interopRequireDefault(_slice); +function finalCleanUpCode(out, async) { + var matches = out.match(ERRORS_REGEXP); -var _onlyOnce = require('./internal/onlyOnce'); + if (matches && matches.length == 2) { + out = async ? out.replace(REMOVE_ERRORS_ASYNC, '').replace(RETURN_ASYNC, RETURN_DATA_ASYNC) : out.replace(REMOVE_ERRORS, '').replace(RETURN_VALID, RETURN_TRUE); + } -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + matches = out.match(ROOTDATA_REGEXP); + if (!matches || matches.length !== 3) return out; + return out.replace(REMOVE_ROOTDATA, ''); +} -var _wrapAsync = require('./internal/wrapAsync'); +function schemaHasRules(schema, rules) { + if (typeof schema == 'boolean') return !schema; -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + for (var key in schema) { + if (rules[key]) return true; + } +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function schemaHasRulesExcept(schema, rules, exceptKeyword) { + if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not'; -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - var args = (0, _slice2.default)(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); + for (var key in schema) { + if (key != exceptKeyword && rules[key]) return true; + } } -module.exports = exports['default']; -},{"./internal/onlyOnce":45,"./internal/slice":50,"./internal/wrapAsync":52,"lodash/noop":936}],24:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; +function schemaUnknownRules(schema, rules) { + if (typeof schema == 'boolean') return; -var _eachOf = require('./eachOf'); + for (var key in schema) { + if (!rules[key]) return key; + } +} -var _eachOf2 = _interopRequireDefault(_eachOf); +function toQuotedString(str) { + return '\'' + escapeQuotes(str) + '\''; +} -var _withoutIndex = require('./internal/withoutIndex'); +function getPathExpr(currentPath, expr, jsonPointers, isNumber) { + var path = jsonPointers // false by default + ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') : isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''; + return joinPaths(currentPath, path); +} -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); +function getPath(currentPath, prop, jsonPointers) { + var path = jsonPointers // false by default + ? toQuotedString('/' + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop)); + return joinPaths(currentPath, path); +} -var _wrapAsync = require('./internal/wrapAsync'); +var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; +var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); +function getData($data, lvl, paths) { + var up, jsonPointer, data, matches; + if ($data === '') return 'rootData'; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if ($data[0] == '/') { + if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); + jsonPointer = $data; + data = 'rootData'; + } else { + matches = $data.match(RELATIVE_JSON_POINTER); + if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); + up = +matches[1]; + jsonPointer = matches[2]; -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default']; -},{"./eachOf":26,"./internal/withoutIndex":51,"./internal/wrapAsync":52}],25:[function(require,module,exports){ -'use strict'; + if (jsonPointer == '#') { + if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + (lvl - up || ''); + if (!jsonPointer) return data; + } -var _eachOfLimit = require('./internal/eachOfLimit'); + var expr = data; + var segments = jsonPointer.split('/'); -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + for (var i = 0; i < segments.length; i++) { + var segment = segments[i]; -var _withoutIndex = require('./internal/withoutIndex'); + if (segment) { + data += getProperty(unescapeJsonPointer(segment)); + expr += ' && ' + data; + } + } -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + return expr; +} -var _wrapAsync = require('./internal/wrapAsync'); +function joinPaths(a, b) { + if (a == '""') return b; + return (a + ' + ' + b).replace(/' \+ '/g, ''); +} -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); +function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); +} -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +function escapeJsonPointer(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); } -module.exports = exports['default']; -},{"./internal/eachOfLimit":37,"./internal/withoutIndex":51,"./internal/wrapAsync":52}],26:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); +function unescapeJsonPointer(str) { + return str.replace(/~1/g, '/').replace(/~0/g, '~'); +} -exports.default = function (coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); -}; +},{"./ucs2length":44,"fast-deep-equal":823}],46:[function(require,module,exports){ +'use strict'; -var _isArrayLike = require('lodash/isArrayLike'); +var KEYWORDS = ['multipleOf', 'maximum', 'exclusiveMaximum', 'minimum', 'exclusiveMinimum', 'maxLength', 'minLength', 'pattern', 'additionalItems', 'maxItems', 'minItems', 'uniqueItems', 'maxProperties', 'minProperties', 'required', 'additionalProperties', 'enum', 'format', 'const']; -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); +module.exports = function (metaSchema, keywordsJsonPointers) { + for (var i = 0; i < keywordsJsonPointers.length; i++) { + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + var segments = keywordsJsonPointers[i].split('/'); + var keywords = metaSchema; + var j; -var _breakLoop = require('./internal/breakLoop'); + for (j = 1; j < segments.length; j++) { + keywords = keywords[segments[j]]; + } -var _breakLoop2 = _interopRequireDefault(_breakLoop); + for (j = 0; j < KEYWORDS.length; j++) { + var key = KEYWORDS[j]; + var schema = keywords[key]; -var _eachOfLimit = require('./eachOfLimit'); + if (schema) { + keywords[key] = { + anyOf: [schema, { + $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' + }] + }; + } + } + } -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + return metaSchema; +}; -var _doLimit = require('./internal/doLimit'); +},{}],47:[function(require,module,exports){ +'use strict'; -var _doLimit2 = _interopRequireDefault(_doLimit); +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -var _noop = require('lodash/noop'); + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; -var _noop2 = _interopRequireDefault(_noop); + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + $lvl + ' = ' + $schemaValueExcl + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + $exclusive + '; var ' + $exclType + ' = typeof ' + $schemaValueExcl + '; if (' + $exclType + ' != \'boolean\' && ' + $exclType + ' != \'undefined\' && ' + $exclType + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var _once = require('./internal/once'); + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; -var _once2 = _interopRequireDefault(_once); + if (it.opts.messages !== false) { + out += ' , message: \'' + $exclusiveKeyword + ' should be boolean\' '; + } -var _onlyOnce = require('./internal/onlyOnce'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + out += ' } '; + } else { + out += ' {} '; + } -var _wrapAsync = require('./internal/wrapAsync'); + var __err = out; + out = $$outStack.pop(); -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' } else if ( '; -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; } - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } - } + out += ' ' + $exclType + ' == \'number\' ? ( (' + $exclusive + ' = ' + $schemaValue + ' === undefined || ' + $schemaValueExcl + ' ' + $op + '= ' + $schemaValue + ') ? ' + $data + ' ' + $notOp + '= ' + $schemaValueExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) : ( (' + $exclusive + ' = ' + $schemaValueExcl + ' === true) ? ' + $data + ' ' + $notOp + '= ' + $schemaValue + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { var op' + $lvl + ' = ' + $exclusive + ' ? \'' + $op + '\' : \'' + $op + '=\'; '; - for (; index < length; index++) { - iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; } -} + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -module.exports = exports['default']; -},{"./eachOfLimit":27,"./internal/breakLoop":32,"./internal/doLimit":34,"./internal/once":44,"./internal/onlyOnce":45,"./internal/wrapAsync":52,"lodash/isArrayLike":927,"lodash/noop":936}],27:[function(require,module,exports){ -'use strict'; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachOfLimit; + out += ' ( ' + $schemaValue + ' === undefined || ' + $schemaExcl + ' ' + $op + '= ' + $schemaValue + ' ? ' + $data + ' ' + $notOp + '= ' + $schemaExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); -var _eachOfLimit2 = require('./internal/eachOfLimit'); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } -var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; -var _wrapAsync = require('./internal/wrapAsync'); + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + out += ' ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' || ' + $data + ' !== ' + $data + ') { '; + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); -} -module.exports = exports['default']; -},{"./internal/eachOfLimit":37,"./internal/wrapAsync":52}],28:[function(require,module,exports){ -'use strict'; + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { comparison: ' + $opExpr + ', limit: ' + $schemaValue + ', exclusive: ' + $exclusive + ' } '; -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + $opStr + ' '; -var _eachOfLimit = require('./eachOfLimit'); + if ($isData) { + out += '\' + ' + $schemaValue; + } else { + out += '' + $schemaValue + '\''; + } + } -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + if (it.opts.verbose) { + out += ' , schema: '; -var _doLimit = require('./internal/doLimit'); + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } -var _doLimit2 = _interopRequireDefault(_doLimit); + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' } '; + } else { + out += ' {} '; + } -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); -module.exports = exports['default']; -},{"./eachOfLimit":27,"./internal/doLimit":34}],29:[function(require,module,exports){ -'use strict'; + var __err = out; + out = $$outStack.pop(); -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -var _eachLimit = require('./eachLimit'); + out += ' } '; -var _eachLimit2 = _interopRequireDefault(_eachLimit); + if ($breakOnError) { + out += ' else { '; + } -var _doLimit = require('./internal/doLimit'); + return out; +}; -var _doLimit2 = _interopRequireDefault(_doLimit); +},{}],48:[function(require,module,exports){ +'use strict'; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); -module.exports = exports['default']; -},{"./eachLimit":25,"./internal/doLimit":34}],30:[function(require,module,exports){ -'use strict'; + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; -Object.defineProperty(exports, "__esModule", { - value: true -}); + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } -var _createTester = require('./internal/createTester'); + out += ' ' + $data + '.length ' + $op + ' ' + $schemaValue + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var _createTester2 = _interopRequireDefault(_createTester); + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } '; -var _doParallel = require('./internal/doParallel'); + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; -var _doParallel2 = _interopRequireDefault(_doParallel); + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } -var _notId = require('./internal/notId'); + out += ' than '; -var _notId2 = _interopRequireDefault(_notId); + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + $schema; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' items\' '; + } -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default']; -},{"./internal/createTester":33,"./internal/doParallel":35,"./internal/notId":43}],31:[function(require,module,exports){ -"use strict"; + if (it.opts.verbose) { + out += ' , schema: '; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = DLL; -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -DLL.prototype.removeLink = function (node) { - if (node.prev) node.prev.next = node.next;else this.head = node.next; - if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + out += ' } '; + } else { + out += ' {} '; + } - node.prev = node.next = null; - this.length -= 1; - return node; -}; + var __err = out; + out = $$outStack.pop(); -DLL.prototype.empty = function () { - while (this.head) this.shift(); - return this; -}; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -DLL.prototype.insertAfter = function (node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode;else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; + out += '} '; -DLL.prototype.insertBefore = function (node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode;else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; + if ($breakOnError) { + out += ' else { '; + } -DLL.prototype.unshift = function (node) { - if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); + return out; }; -DLL.prototype.push = function (node) { - if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); -}; +},{}],49:[function(require,module,exports){ +'use strict'; -DLL.prototype.shift = function () { - return this.head && this.removeLink(this.head); -}; +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -DLL.prototype.pop = function () { - return this.tail && this.removeLink(this.tail); -}; + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for (var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; -}; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while (!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; -module.exports = exports["default"]; -},{}],32:[function(require,module,exports){ -"use strict"; + if (it.opts.unicode === false) { + out += ' ' + $data + '.length '; + } else { + out += ' ucs2length(' + $data + ') '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -exports.default = {}; -module.exports = exports["default"]; -},{}],33:[function(require,module,exports){ -'use strict'; + out += ' ' + $op + ' ' + $schemaValue + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _createTester; + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } '; -var _noop = require('lodash/noop'); + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; -var _noop2 = _interopRequireDefault(_noop); + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } -var _breakLoop = require('./breakLoop'); + out += ' than '; -var _breakLoop2 = _interopRequireDefault(_breakLoop); + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + $schema; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' characters\' '; + } -function _createTester(check, getResult) { - return function (eachfn, arr, iteratee, cb) { - cb = cb || _noop2.default; - var testPassed = false; - var testResult; - eachfn(arr, function (value, _, callback) { - iteratee(value, function (err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, _breakLoop2.default); - } else { - callback(); - } - }); - }, function (err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} -module.exports = exports['default']; -},{"./breakLoop":32,"lodash/noop":936}],34:[function(require,module,exports){ -"use strict"; + if (it.opts.verbose) { + out += ' , schema: '; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doLimit; -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} -module.exports = exports["default"]; -},{}],35:[function(require,module,exports){ -'use strict'; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doParallel; + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _eachOf = require('../eachOf'); + out += ' } '; + } else { + out += ' {} '; + } -var _eachOf2 = _interopRequireDefault(_eachOf); + var __err = out; + out = $$outStack.pop(); -var _wrapAsync = require('./wrapAsync'); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + out += '} '; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if ($breakOnError) { + out += ' else { '; + } -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(_eachOf2.default, obj, (0, _wrapAsync2.default)(iteratee), callback); - }; -} -module.exports = exports['default']; -},{"../eachOf":26,"./wrapAsync":52}],36:[function(require,module,exports){ + return out; +}; + +},{}],50:[function(require,module,exports){ 'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doParallelLimit; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -var _eachOfLimit = require('./eachOfLimit'); + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } -var _wrapAsync = require('./wrapAsync'); + out += ' Object.keys(' + $data + ').length ' + $op + ' ' + $schemaValue + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } '; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn((0, _eachOfLimit2.default)(limit), obj, (0, _wrapAsync2.default)(iteratee), callback); - }; -} -module.exports = exports['default']; -},{"./eachOfLimit":37,"./wrapAsync":52}],37:[function(require,module,exports){ -'use strict'; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _eachOfLimit; + out += ' than '; -var _noop = require('lodash/noop'); + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + $schema; + } -var _noop2 = _interopRequireDefault(_noop); + out += ' properties\' '; + } -var _once = require('./once'); + if (it.opts.verbose) { + out += ' , schema: '; -var _once2 = _interopRequireDefault(_once); + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } -var _iterator = require('./iterator'); + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _iterator2 = _interopRequireDefault(_iterator); + out += ' } '; + } else { + out += ' {} '; + } -var _onlyOnce = require('./onlyOnce'); + var __err = out; + out = $$outStack.pop(); -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -var _breakLoop = require('./breakLoop'); + out += '} '; -var _breakLoop2 = _interopRequireDefault(_breakLoop); + if ($breakOnError) { + out += ' else { '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return out; +}; -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = (0, _iterator2.default)(obj); - var done = false; - var running = 0; - var looping = false; +},{}],51:[function(require,module,exports){ +'use strict'; - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } else if (value === _breakLoop2.default || done && running <= 0) { - done = true; - return callback(null); - } else if (!looping) { - replenish(); - } - } +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; - function replenish() { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); - } - looping = false; + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; + + while ($i < l1) { + $sch = arr1[$i += 1]; + + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; } + } + } + } - replenish(); - }; -} -module.exports = exports['default']; -},{"./breakLoop":32,"./iterator":41,"./once":44,"./onlyOnce":45,"lodash/noop":936}],38:[function(require,module,exports){ -'use strict'; + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + $closingBraces.slice(0, -1) + ' '; + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _filter; + out = it.util.cleanUpCode(out); + return out; +}; -var _arrayMap = require('lodash/_arrayMap'); +},{}],52:[function(require,module,exports){ +'use strict'; -var _arrayMap2 = _interopRequireDefault(_arrayMap); +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function ($sch) { + return it.util.schemaHasRules($sch, it.RULES.all); + }); -var _isArrayLike = require('lodash/isArrayLike'); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + $errs + ' = errors; var ' + $valid + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; -var _baseProperty = require('lodash/_baseProperty'); + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + $valid + ' = ' + $valid + ' || ' + $nextValid + '; if (!' + $valid + ') { '; + $closingBraces += '}'; + } + } -var _baseProperty2 = _interopRequireDefault(_baseProperty); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + $closingBraces + ' if (!' + $valid + ') { var err = '; + /* istanbul ignore else */ -var _noop = require('lodash/noop'); + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'anyOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; -var _noop2 = _interopRequireDefault(_noop); + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } -var _wrapAsync = require('./wrapAsync'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + out += ' } '; + } else { + out += ' {} '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({ index: index, value: x }); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, (0, _arrayMap2.default)(results.sort(function (a, b) { - return a.index - b.index; - }), (0, _baseProperty2.default)('value'))); - } - }); -} + out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } '; -function _filter(eachfn, coll, iteratee, callback) { - var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback || _noop2.default); -} -module.exports = exports['default']; -},{"./wrapAsync":52,"lodash/_arrayMap":880,"lodash/_baseProperty":892,"lodash/isArrayLike":927,"lodash/noop":936}],39:[function(require,module,exports){ -'use strict'; + if (it.opts.allErrors) { + out += ' } '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } -exports.default = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); + return out; }; -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -module.exports = exports['default']; -},{}],40:[function(require,module,exports){ +},{}],53:[function(require,module,exports){ 'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); -exports.default = function (fn) { - return function () /*...args, callback*/{ - var args = (0, _slice2.default)(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; + if (it.opts.$comment === true) { + out += ' console.log(' + $comment + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + $comment + ', ' + it.util.toQuotedString($errSchemaPath) + ', validate.root.schema);'; + } -var _slice = require('./slice'); + return out; +}; -var _slice2 = _interopRequireDefault(_slice); +},{}],54:[function(require,module,exports){ +'use strict'; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -module.exports = exports['default']; -},{"./slice":50}],41:[function(require,module,exports){ -'use strict'; + if (!$isData) { + out += ' var schema' + $lvl + ' = validate.schema' + $schemaPath + ';'; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = iterator; + out += 'var ' + $valid + ' = equal(' + $data + ', schema' + $lvl + '); if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var _isArrayLike = require('lodash/isArrayLike'); + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'const' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { allowedValue: schema' + $lvl + ' } '; -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } -var _getIterator = require('./getIterator'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _getIterator2 = _interopRequireDefault(_getIterator); + out += ' } '; + } else { + out += ' {} '; + } -var _keys = require('lodash/keys'); + var __err = out; + out = $$outStack.pop(); -var _keys2 = _interopRequireDefault(_keys); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' }'; -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? { value: coll[i], key: i } : null; - }; -} + if ($breakOnError) { + out += ' else { '; + } -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) return null; - i++; - return { value: item.value, key: i }; - }; -} + return out; +}; -function createObjectIterator(obj) { - var okeys = (0, _keys2.default)(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? { value: obj[key], key: key } : null; - }; -} +},{}],55:[function(require,module,exports){ +'use strict'; -function iterator(coll) { - if ((0, _isArrayLike2.default)(coll)) { - return createArrayIterator(coll); +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all); + out += 'var ' + $errs + ' = errors;var ' + $valid + ';'; + + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + $nextValid + ' = false; for (var ' + $idx + ' = 0; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; } - var iterator = (0, _getIterator2.default)(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} -module.exports = exports['default']; -},{"./getIterator":39,"lodash/isArrayLike":927,"lodash/keys":934}],42:[function(require,module,exports){ -'use strict'; + out += ' if (' + $nextValid + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + $closingBraces + ' if (!' + $nextValid + ') {'; + } else { + out += ' if (' + $data + '.length == 0) {'; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _asyncMap; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var _noop = require('lodash/noop'); + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'contains' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; -var _noop2 = _interopRequireDefault(_noop); + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } -var _wrapAsync = require('./wrapAsync'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + out += ' } '; + } else { + out += ' {} '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var __err = out; + out = $$outStack.pop(); -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || _noop2.default; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = (0, _wrapAsync2.default)(iteratee); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default']; -},{"./wrapAsync":52,"lodash/noop":936}],43:[function(require,module,exports){ -"use strict"; + out += ' } else { '; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = notId; -function notId(v) { - return !v; -} -module.exports = exports["default"]; -},{}],44:[function(require,module,exports){ -"use strict"; + if ($nonEmptySchema) { + out += ' errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = once; -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; -},{}],45:[function(require,module,exports){ -"use strict"; + if (it.opts.allErrors) { + out += ' } '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = onlyOnce; -function onlyOnce(fn) { - return function () { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; -},{}],46:[function(require,module,exports){ + out = it.util.cleanUpCode(out); + return out; +}; + +},{}],56:[function(require,module,exports){ 'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _parallel; +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -var _noop = require('lodash/noop'); + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; -var _noop2 = _interopRequireDefault(_noop); + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + $definition + ' = RULES.custom[\'' + $keyword + '\'].definition; var ' + $validateCode + ' = ' + $definition + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } -var _isArrayLike = require('lodash/isArrayLike'); + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + if (!($inline || $macro)) { + out += '' + $ruleErrs + ' = null;'; + } -var _slice = require('./slice'); + out += 'var ' + $errs + ' = errors;var ' + $valid + ';'; -var _slice2 = _interopRequireDefault(_slice); + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + $schemaValue + ' === undefined) { ' + $valid + ' = true; } else { '; -var _wrapAsync = require('./wrapAsync'); + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + $valid + ' = ' + $definition + '.validateSchema(' + $schemaValue + '); if (' + $valid + ') { '; + } + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + if ($inline) { + if ($rDef.statements) { + out += ' ' + $ruleValidate.validate + ' '; + } else { + out += ' ' + $valid + ' = ' + $ruleValidate.validate + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + $code; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + $validateCode + '.call( '; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } -function _parallel(eachfn, tasks, callback) { - callback = callback || _noop2.default; - var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + if ($compile || $rDef.schema === false) { + out += ' , ' + $data + ' '; + } else { + out += ' , ' + $schemaValue + ' , ' + $data + ' , validate.schema' + it.schemaPath + ' '; + } - eachfn(tasks, function (task, key, callback) { - (0, _wrapAsync2.default)(task)(function (err, result) { - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default']; -},{"./slice":50,"./wrapAsync":52,"lodash/isArrayLike":927,"lodash/noop":936}],47:[function(require,module,exports){ -'use strict'; + out += ' , (dataPath || \'\')'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = queue; + if (it.errorPath != '""') { + out += ' + ' + it.errorPath; + } -var _baseIndexOf = require('lodash/_baseIndexOf'); + var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + $parentData + ' , ' + $parentDataProperty + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); -var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); + if ($rDef.errors === false) { + out += ' ' + $valid + ' = '; -var _isArray = require('lodash/isArray'); + if ($asyncKeyword) { + out += 'await '; + } -var _isArray2 = _interopRequireDefault(_isArray); + out += '' + def_callRuleValidate + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + $ruleErrs + ' = null; try { ' + $valid + ' = await ' + def_callRuleValidate + '; } catch (e) { ' + $valid + ' = false; if (e instanceof ValidationError) ' + $ruleErrs + ' = e.errors; else throw e; } '; + } else { + out += ' ' + $ruleErrs + ' = null; ' + $valid + ' = ' + def_callRuleValidate + '; '; + } + } + } -var _noop = require('lodash/noop'); + if ($rDef.modifying) { + out += ' if (' + $parentData + ') ' + $data + ' = ' + $parentData + '[' + $parentDataProperty + '];'; + } -var _noop2 = _interopRequireDefault(_noop); + out += '' + $closingBraces; -var _onlyOnce = require('./onlyOnce'); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + if ($rDef.valid === undefined) { + out += ' !'; -var _setImmediate = require('./setImmediate'); + if ($macro) { + out += '' + $nextValid; + } else { + out += '' + $valid; + } + } else { + out += ' ' + !$rDef.valid + ' '; + } -var _setImmediate2 = _interopRequireDefault(_setImmediate); + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var _DoublyLinkedList = require('./DoublyLinkedList'); + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { keyword: \'' + $rule.keyword + '\' } '; -var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + $rule.keyword + '" keyword validation\' '; + } -var _wrapAsync = require('./wrapAsync'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + out += ' } '; + } else { + out += ' {} '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var __err = out; + out = $$outStack.pop(); -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } else if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - var _worker = (0, _wrapAsync2.default)(worker); - var numRunning = 0; - var workersList = []; + var def_customError = out; + out = $$outStack.pop(); - var processingScheduled = false; - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + $i + '=' + $errs + '; ' + $i + ' 0) { - workersList.splice(index, 1); - } + return out; +}; - task.callback.apply(task, arguments); +},{}],57:[function(require,module,exports){ +'use strict'; - if (err != null) { - q.error(err, task.data); - } +module.exports = function generate_dependencies(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $schemaDeps = {}, + $propertyDeps = {}, + $ownProperties = it.opts.ownProperties; + + for ($property in $schema) { + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } + + out += 'var ' + $errs + ' = errors;'; + var $currentErrorPath = it.errorPath; + out += 'var missing' + $lvl + ';'; + + for (var $property in $propertyDeps) { + $deps = $propertyDeps[$property]; + + if ($deps.length) { + out += ' if ( ' + $data + it.util.getProperty($property) + ' !== undefined '; + + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') '; + } + + if ($breakOnError) { + out += ' && ( '; + var arr1 = $deps; + + if (arr1) { + var $propertyKey, + $i = -1, + l1 = arr1.length - 1; + + while ($i < l1) { + $propertyKey = arr1[$i += 1]; + + if ($i) { + out += ' || '; } - if (numRunning <= q.concurrency - q.buffer) { - q.unsaturated(); - } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + $useData + ' === undefined '; - if (q.idle()) { - q.drain(); + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; } - q.process(); - }; - } - var isProcessing = false; - var q = { - _tasks: new _DoublyLinkedList2.default(), - concurrency: concurrency, - payload: payload, - saturated: _noop2.default, - unsaturated: _noop2.default, - buffer: concurrency / 4, - empty: _noop2.default, - drain: _noop2.default, - error: _noop2.default, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = _noop2.default; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while (!q.paused && numRunning < q.concurrency && q._tasks.length) { - var tasks = [], - data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } + out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) '; + } + } - numRunning += 1; + out += ')) { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (q._tasks.length === 0) { - q.empty(); - } + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } - if (numRunning === q.concurrency) { - q.saturated(); - } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ - var cb = (0, _onlyOnce2.default)(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function () { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { - return; + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'dependencies' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + '\' } '; + + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + + if ($deps.length == 1) { + out += 'property ' + it.util.escapeQuotes($deps[0]); + } else { + out += 'properties ' + it.util.escapeQuotes($deps.join(", ")); } - q.paused = false; - (0, _setImmediate2.default)(q.process); - } - }; - return q; -} -module.exports = exports['default']; -},{"./DoublyLinkedList":31,"./onlyOnce":45,"./setImmediate":49,"./wrapAsync":52,"lodash/_baseIndexOf":885,"lodash/isArray":926,"lodash/noop":936}],48:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reject; + out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' '; + } -var _filter = require('./filter'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _filter2 = _interopRequireDefault(_filter); + out += ' } '; + } else { + out += ' {} '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var __err = out; + out = $$outStack.pop(); -function reject(eachfn, arr, iteratee, callback) { - (0, _filter2.default)(eachfn, arr, function (value, cb) { - iteratee(value, function (err, v) { - cb(err, !v); - }); - }, callback); -} -module.exports = exports['default']; -},{"./filter":38}],49:[function(require,module,exports){ -'use strict'; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + out += ' ) { '; + var arr2 = $deps; + + if (arr2) { + var $propertyKey, + i2 = -1, + l2 = arr2.length - 1; + + while (i2 < l2) { + $propertyKey = arr2[i2 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hasNextTick = exports.hasSetImmediate = undefined; -exports.fallback = fallback; -exports.wrap = wrap; + out += ' if ( ' + $useData + ' === undefined '; -var _slice = require('./slice'); + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } -var _slice2 = _interopRequireDefault(_slice); + out += ') { var err = '; + /* istanbul ignore else */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'dependencies' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + '\' } '; -var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; -function fallback(fn) { - setTimeout(fn, 0); -} + if ($deps.length == 1) { + out += 'property ' + it.util.escapeQuotes($deps[0]); + } else { + out += 'properties ' + it.util.escapeQuotes($deps.join(", ")); + } -function wrap(defer) { - return function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} + out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' '; + } -var _defer; + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} + out += ' } '; + } else { + out += ' {} '; + } -exports.default = wrap(_defer); -},{"./slice":50}],50:[function(require,module,exports){ -"use strict"; + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = slice; -function slice(arrayLike, start) { - start = start | 0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for (var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; + out += ' } '; + + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } } - return newArr; -} -module.exports = exports["default"]; -},{}],51:[function(require,module,exports){ -"use strict"; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _withoutIndex; -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} -module.exports = exports["default"]; -},{}],52:[function(require,module,exports){ -'use strict'; + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isAsync = undefined; + for (var $property in $schemaDeps) { + var $sch = $schemaDeps[$property]; -var _asyncify = require('../asyncify'); + if (it.util.schemaHasRules($sch, it.RULES.all)) { + out += ' ' + $nextValid + ' = true; if ( ' + $data + it.util.getProperty($property) + ' !== undefined '; -var _asyncify2 = _interopRequireDefault(_asyncify); + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; -var supportsSymbol = typeof Symbol === 'function'; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} + if ($breakOnError) { + out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {'; + } -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; -} + out = it.util.cleanUpCode(out); + return out; +}; -exports.default = wrapAsync; -exports.isAsync = isAsync; -},{"../asyncify":20}],53:[function(require,module,exports){ +},{}],58:[function(require,module,exports){ 'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -var _doParallel = require('./internal/doParallel'); + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; -var _doParallel2 = _interopRequireDefault(_doParallel); + if (!$isData) { + out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + ';'; + } -var _map = require('./internal/map'); + out += 'var ' + $valid + ';'; -var _map2 = _interopRequireDefault(_map); + if ($isData) { + out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {'; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += '' + $valid + ' = false;for (var ' + $i + '=0; ' + $i + '<' + $vSchema + '.length; ' + $i + '++) if (equal(' + $data + ', ' + $vSchema + '[' + $i + '])) { ' + $valid + ' = true; break; }'; -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -exports.default = (0, _doParallel2.default)(_map2.default); -module.exports = exports['default']; -},{"./internal/doParallel":35,"./internal/map":42}],54:[function(require,module,exports){ -'use strict'; + if ($isData) { + out += ' } '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var _doParallelLimit = require('./internal/doParallelLimit'); + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'enum' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { allowedValues: schema' + $lvl + ' } '; -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } -var _map = require('./internal/map'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _map2 = _interopRequireDefault(_map); + out += ' } '; + } else { + out += ' {} '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var __err = out; + out = $$outStack.pop(); -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_map2.default); -module.exports = exports['default']; -},{"./internal/doParallelLimit":36,"./internal/map":42}],55:[function(require,module,exports){ -'use strict'; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = parallelLimit; + out += ' }'; -var _eachOf = require('./eachOf'); + if ($breakOnError) { + out += ' else { '; + } -var _eachOf2 = _interopRequireDefault(_eachOf); + return out; +}; -var _parallel = require('./internal/parallel'); +},{}],59:[function(require,module,exports){ +'use strict'; -var _parallel2 = _interopRequireDefault(_parallel); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - (0, _parallel2.default)(_eachOf2.default, tasks, callback); -} -module.exports = exports['default']; -},{"./eachOf":26,"./internal/parallel":46}],56:[function(require,module,exports){ -'use strict'; + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + return out; + } -exports.default = function (worker, concurrency) { - var _worker = (0, _wrapAsync2.default)(worker); - return (0, _queue2.default)(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; -var _queue = require('./internal/queue'); + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -var _queue2 = _interopRequireDefault(_queue); + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); -var _wrapAsync = require('./internal/wrapAsync'); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + $format + ' = formats[' + $schemaValue + ']; var ' + $isObject + ' = typeof ' + $format + ' == \'object\' && !(' + $format + ' instanceof RegExp) && ' + $format + '.validate; var ' + $formatType + ' = ' + $isObject + ' && ' + $format + '.type || \'string\'; if (' + $isObject + ') { '; -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + if (it.async) { + out += ' var async' + $lvl + ' = ' + $format + '.async; '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' ' + $format + ' = ' + $format + '.validate; } if ( '; -module.exports = exports['default']; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || '; + } -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ + out += ' ('; -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ -},{"./internal/queue":47,"./internal/wrapAsync":52}],57:[function(require,module,exports){ -'use strict'; + if ($unknownFormats != 'ignore') { + out += ' (' + $schemaValue + ' && !' + $format + ' '; -Object.defineProperty(exports, "__esModule", { - value: true -}); + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + $schemaValue + ') == -1 '; + } -var _reject = require('./internal/reject'); + out += ') || '; + } -var _reject2 = _interopRequireDefault(_reject); + out += ' (' + $format + ' && ' + $formatType + ' == \'' + $ruleType + '\' && !(typeof ' + $format + ' == \'function\' ? '; -var _doParallel = require('./internal/doParallel'); + if (it.async) { + out += ' (async' + $lvl + ' ? await ' + $format + '(' + $data + ') : ' + $format + '(' + $data + ')) '; + } else { + out += ' ' + $format + '(' + $data + ') '; + } -var _doParallel2 = _interopRequireDefault(_doParallel); + out += ' : ' + $format + '.test(' + $data + '))))) {'; + } else { + var $format = it.formats[$schema]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -exports.default = (0, _doParallel2.default)(_reject2.default); -module.exports = exports['default']; -},{"./internal/doParallel":35,"./internal/reject":48}],58:[function(require,module,exports){ -'use strict'; + if ($breakOnError) { + out += ' if (true) { '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = series; + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } -var _parallel = require('./internal/parallel'); + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } -var _parallel2 = _interopRequireDefault(_parallel); + var $isObject = _typeof($format) == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; -var _eachOfSeries = require('./eachOfSeries'); + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return out; + } -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - (0, _parallel2.default)(_eachOfSeries2.default, tasks, callback); -} -module.exports = exports['default']; -},{"./eachOfSeries":28,"./internal/parallel":46}],59:[function(require,module,exports){ -'use strict'; + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + $formatRef + '(' + $data + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (typeof $format == 'function') { + out += ' ' + $formatRef + '(' + $data + ') '; + } else { + out += ' ' + $formatRef + '.test(' + $data + ') '; + } -var _setImmediate = require('./internal/setImmediate'); + out += ') { '; + } + } -var _setImmediate2 = _interopRequireDefault(_setImmediate); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'format' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { format: '; -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `setImmediate`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name setImmediate - * @static - * @memberOf module:Utils - * @method - * @see [async.nextTick]{@link module:Utils.nextTick} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -exports.default = _setImmediate2.default; -module.exports = exports['default']; -},{"./internal/setImmediate":49}],60:[function(require,module,exports){ -'use strict'; + if ($isData) { + out += '' + $schemaValue; + } else { + out += '' + it.util.toQuotedString($schema); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + out += ' } '; -var _createTester = require('./internal/createTester'); + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; -var _createTester2 = _interopRequireDefault(_createTester); + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + it.util.escapeQuotes($schema); + } -var _doParallel = require('./internal/doParallel'); + out += '"\' '; + } -var _doParallel2 = _interopRequireDefault(_doParallel); + if (it.opts.verbose) { + out += ' , schema: '; -var _identity = require('lodash/identity'); + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + it.util.toQuotedString($schema); + } -var _identity2 = _interopRequireDefault(_identity); + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' } '; + } else { + out += ' {} '; + } -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default']; -},{"./internal/createTester":33,"./internal/doParallel":35,"lodash/identity":924}],61:[function(require,module,exports){ -'use strict'; + var __err = out; + out = $$outStack.pop(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = timeout; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -var _initialParams = require('./internal/initialParams'); + out += ' } '; -var _initialParams2 = _interopRequireDefault(_initialParams); + if ($breakOnError) { + out += ' else { '; + } -var _wrapAsync = require('./internal/wrapAsync'); + return out; +}; -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); +},{}],60:[function(require,module,exports){ +'use strict'; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && it.util.schemaHasRules($thenSch, it.RULES.all), + $elsePresent = $elseSch !== undefined && it.util.schemaHasRules($elseSch, it.RULES.all), + $currentBaseId = $it.baseId; + + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + $errs + ' = errors; var ' + $valid + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + + if ($thenPresent) { + out += ' if (' + $nextValid + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + $valid + ' = ' + $nextValid + '; '; + + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + $ifClause + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = (0, _wrapAsync2.default)(asyncFn); + out += ' } '; - return (0, _initialParams2.default)(function (args, callback) { - var timedOut = false; - var timer; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + $nextValid + ') { '; + } - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + $valid + ' = ' + $nextValid + '; '; - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + $ifClause + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} -module.exports = exports['default']; -},{"./internal/initialParams":40,"./internal/wrapAsync":52}],62:[function(require,module,exports){ -'use strict'; + out += ' } '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + out += ' if (!' + $valid + ') { var err = '; + /* istanbul ignore else */ -var _timesLimit = require('./timesLimit'); + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'if' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { failingKeyword: ' + $ifClause + ' } '; -var _timesLimit2 = _interopRequireDefault(_timesLimit); + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + $ifClause + ' + \'" schema\' '; + } -var _doLimit = require('./internal/doLimit'); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var _doLimit2 = _interopRequireDefault(_doLimit); + out += ' } '; + } else { + out += ' {} '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ -exports.default = (0, _doLimit2.default)(_timesLimit2.default, Infinity); -module.exports = exports['default']; -},{"./internal/doLimit":34,"./timesLimit":63}],63:[function(require,module,exports){ -'use strict'; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = timeLimit; + out += ' } '; -var _mapLimit = require('./mapLimit'); + if ($breakOnError) { + out += ' else { '; + } -var _mapLimit2 = _interopRequireDefault(_mapLimit); + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } -var _baseRange = require('lodash/_baseRange'); + return out; +}; -var _baseRange2 = _interopRequireDefault(_baseRange); +},{}],61:[function(require,module,exports){ +'use strict'; //all requires must be explicit because browserify won't work with dynamic requires -var _wrapAsync = require('./internal/wrapAsync'); +module.exports = { + '$ref': require('./ref'), + allOf: require('./allOf'), + anyOf: require('./anyOf'), + '$comment': require('./comment'), + "const": require('./const'), + contains: require('./contains'), + dependencies: require('./dependencies'), + 'enum': require('./enum'), + format: require('./format'), + 'if': require('./if'), + items: require('./items'), + maximum: require('./_limit'), + minimum: require('./_limit'), + maxItems: require('./_limitItems'), + minItems: require('./_limitItems'), + maxLength: require('./_limitLength'), + minLength: require('./_limitLength'), + maxProperties: require('./_limitProperties'), + minProperties: require('./_limitProperties'), + multipleOf: require('./multipleOf'), + not: require('./not'), + oneOf: require('./oneOf'), + pattern: require('./pattern'), + properties: require('./properties'), + propertyNames: require('./propertyNames'), + required: require('./required'), + uniqueItems: require('./uniqueItems'), + validate: require('./validate') +}; + +},{"./_limit":47,"./_limitItems":48,"./_limitLength":49,"./_limitProperties":50,"./allOf":51,"./anyOf":52,"./comment":53,"./const":54,"./contains":55,"./dependencies":57,"./enum":58,"./format":59,"./if":60,"./items":62,"./multipleOf":63,"./not":64,"./oneOf":65,"./pattern":66,"./properties":67,"./propertyNames":68,"./ref":69,"./required":70,"./uniqueItems":71,"./validate":72}],62:[function(require,module,exports){ +'use strict'; -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + $errs + ' = errors;var ' + $valid + ';'; + + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + + if ($additionalItems === false) { + out += ' ' + $valid + ' = ' + $data + '.length <= ' + $schema.length + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'additionalItems' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schema.length + ' } '; -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _mapLimit2.default)((0, _baseRange2.default)(0, count, 1), limit, _iteratee, callback); -} -module.exports = exports['default']; -},{"./internal/wrapAsync":52,"./mapLimit":54,"lodash/_baseRange":893}],64:[function(require,module,exports){ -'use strict'; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + $schema.length + ' items\' '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -exports.default = function (tasks, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (!(0, _isArray2.default)(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; + out += ' } '; + } else { + out += ' {} '; + } - function nextTask(args) { - var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); - args.push((0, _onlyOnce2.default)(next)); - task.apply(null, args); - } + var __err = out; + out = $$outStack.pop(); - function next(err /*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; } - nextTask((0, _slice2.default)(arguments, 1)); - } - - nextTask([]); -}; + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -var _isArray = require('lodash/isArray'); + out += ' } '; + $errSchemaPath = $currErrSchemaPath; -var _isArray2 = _interopRequireDefault(_isArray); + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } -var _noop = require('lodash/noop'); + var arr1 = $schema; -var _noop2 = _interopRequireDefault(_noop); + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; -var _once = require('./internal/once'); + while ($i < l1) { + $sch = arr1[$i += 1]; -var _once2 = _interopRequireDefault(_once); + if (it.util.schemaHasRules($sch, it.RULES.all)) { + out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $i + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; -var _slice = require('./internal/slice'); + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } -var _slice2 = _interopRequireDefault(_slice); + out += ' } '; -var _onlyOnce = require('./internal/onlyOnce'); + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } + } -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + if (_typeof($additionalItems) == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $schema.length + ') { for (var ' + $idx + ' = ' + $schema.length + '; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; -var _wrapAsync = require('./internal/wrapAsync'); + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + out += ' } } '; -module.exports = exports['default']; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } else if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + $idx + ' = ' + 0 + '; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -},{"./internal/once":44,"./internal/onlyOnce":45,"./internal/slice":50,"./internal/wrapAsync":52,"lodash/isArray":926,"lodash/noop":936}],65:[function(require,module,exports){ -'use strict'; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = whilst; + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } -var _noop = require('lodash/noop'); + out += ' }'; + } -var _noop2 = _interopRequireDefault(_noop); + if ($breakOnError) { + out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {'; + } -var _slice = require('./internal/slice'); + out = it.util.cleanUpCode(out); + return out; +}; -var _slice2 = _interopRequireDefault(_slice); +},{}],63:[function(require,module,exports){ +'use strict'; -var _onlyOnce = require('./internal/onlyOnce'); +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + out += 'var division' + $lvl + ';if ('; -var _wrapAsync = require('./internal/wrapAsync'); + if ($isData) { + out += ' ' + $schemaValue + ' !== undefined && ( typeof ' + $schemaValue + ' != \'number\' || '; + } -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + out += ' (division' + $lvl + ' = ' + $data + ' / ' + $schemaValue + ', '; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + $lvl + ') - division' + $lvl + ') > 1e-' + it.opts.multipleOfPrecision + ' '; + } else { + out += ' division' + $lvl + ' !== parseInt(division' + $lvl + ') '; + } -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - if (!test()) return callback(null); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = (0, _slice2.default)(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} -module.exports = exports['default']; -},{"./internal/onlyOnce":45,"./internal/slice":50,"./internal/wrapAsync":52,"lodash/noop":936}],66:[function(require,module,exports){ + out += ' ) '; -/** - * Expose `Backoff`. - */ + if ($isData) { + out += ' ) '; + } -module.exports = Backoff; + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -/** - * Initialize backoff timer with `opts`. - * - * - `min` initial timeout in milliseconds [100] - * - `max` max timeout [10000] - * - `jitter` [0] - * - `factor` [2] - * - * @param {Object} opts - * @api public - */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'multipleOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { multipleOf: ' + $schemaValue + ' } '; -function Backoff(opts) { - opts = opts || {}; - this.ms = opts.min || 100; - this.max = opts.max || 10000; - this.factor = opts.factor || 2; - this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; - this.attempts = 0; -} + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; -/** - * Return the backoff duration. - * - * @return {Number} - * @api public - */ + if ($isData) { + out += '\' + ' + $schemaValue; + } else { + out += '' + $schemaValue + '\''; + } + } -Backoff.prototype.duration = function(){ - var ms = this.ms * Math.pow(this.factor, this.attempts++); - if (this.jitter) { - var rand = Math.random(); - var deviation = Math.floor(rand * this.jitter * ms); - ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; - } - return Math.min(ms, this.max) | 0; -}; + if (it.opts.verbose) { + out += ' , schema: '; -/** - * Reset the number of attempts. - * - * @api public - */ + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } -Backoff.prototype.reset = function(){ - this.attempts = 0; -}; + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -/** - * Set the minimum duration - * - * @api public - */ + out += ' } '; + } else { + out += ' {} '; + } -Backoff.prototype.setMin = function(min){ - this.ms = min; -}; + var __err = out; + out = $$outStack.pop(); -/** - * Set the maximum duration - * - * @api public - */ + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -Backoff.prototype.setMax = function(max){ - this.max = max; -}; + out += '} '; -/** - * Set the jitter - * - * @api public - */ + if ($breakOnError) { + out += ' else { '; + } -Backoff.prototype.setJitter = function(jitter){ - this.jitter = jitter; + return out; }; - -},{}],67:[function(require,module,exports){ +},{}],64:[function(require,module,exports){ 'use strict'; -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + $errs + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + + out += ' ' + it.validate($it) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + $nextValid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ + + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'not' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + + out += ' } '; + } else { + out += ' {} '; + } - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; + var __err = out; + out = $$outStack.pop(); - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); + out += ' validate.errors = [' + __err + ']; return false; '; } - - i = ai < bi && ai >= 0 ? ai : bi; + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - if (begs.length) { - result = [ left, right ]; + out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } '; + + if (it.opts.allErrors) { + out += ' } '; } - } + } else { + out += ' var err = '; + /* istanbul ignore else */ - return result; -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'not' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; -},{}],68:[function(require,module,exports){ -// base-x encoding -// Forked from https://github.com/cryptocoinjs/bs58 -// Originally written by Mike Hearn for BitcoinJ -// Copyright (c) 2011 Google Inc -// Ported to JavaScript by Stefan Thomas -// Merged Buffer refactorings from base58-native by Stephen Pair -// Copyright (c) 2013 BitPay Inc + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } -var Buffer = require('safe-buffer').Buffer + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -module.exports = function base (ALPHABET) { - var ALPHABET_MAP = {} - var BASE = ALPHABET.length - var LEADER = ALPHABET.charAt(0) + out += ' } '; + } else { + out += ' {} '; + } - // pre-compute lookup table - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z) + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z + if ($breakOnError) { + out += ' if (false) { '; + } } - function encode (source) { - if (source.length === 0) return '' + return out; +}; - var digits = [0] - for (var i = 0; i < source.length; ++i) { - for (var j = 0, carry = source[i]; j < digits.length; ++j) { - carry += digits[j] << 8 - digits[j] = carry % BASE - carry = (carry / BASE) | 0 - } +},{}],65:[function(require,module,exports){ +'use strict'; - while (carry > 0) { - digits.push(carry % BASE) - carry = (carry / BASE) | 0 +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + $errs + ' = errors , ' + $prevValid + ' = false , ' + $valid + ' = false , ' + $passingSchemas + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; + + while ($i < l1) { + $sch = arr1[$i += 1]; + + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + $nextValid + ' = true; '; } - } - var string = '' - - // deal with leading zeros - for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER - // convert digits to a string - for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]] + if ($i) { + out += ' if (' + $nextValid + ' && ' + $prevValid + ') { ' + $valid + ' = false; ' + $passingSchemas + ' = [' + $passingSchemas + ', ' + $i + ']; } else { '; + $closingBraces += '}'; + } - return string + out += ' if (' + $nextValid + ') { ' + $valid + ' = ' + $prevValid + ' = true; ' + $passingSchemas + ' = ' + $i + '; }'; + } } - function decodeUnsafe (string) { - if (typeof string !== 'string') throw new TypeError('Expected String') - if (string.length === 0) return Buffer.allocUnsafe(0) - - var bytes = [0] - for (var i = 0; i < string.length; i++) { - var value = ALPHABET_MAP[string[i]] - if (value === undefined) return + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + $closingBraces + 'if (!' + $valid + ') { var err = '; + /* istanbul ignore else */ - for (var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * BASE - bytes[j] = carry & 0xff - carry >>= 8 - } + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'oneOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { passingSchemas: ' + $passingSchemas + ' } '; - while (carry > 0) { - bytes.push(carry & 0xff) - carry >>= 8 - } + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; } - // deal with leading zeros - for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) { - bytes.push(0) + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; } - return Buffer.from(bytes.reverse()) + out += ' } '; + } else { + out += ' {} '; } - function decode (string) { - var buffer = decodeUnsafe(string) - if (buffer) return buffer + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - throw new Error('Non-base' + BASE + ' character') + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode + out += '} else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; }'; + + if (it.opts.allErrors) { + out += ' } '; } -} -},{"safe-buffer":1256}],69:[function(require,module,exports){ -"use strict"; + return out; +}; -/** - * Generate a character map. - * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" - * @param {object} mappings map overrides from key to value - * @method - */ +},{}],66:[function(require,module,exports){ +'use strict'; -var charmap = function (alphabet, mappings) { - mappings || (mappings = {}); - alphabet.split("").forEach(function (c, i) { - if (!(c in mappings)) mappings[c] = i; - }); - return mappings; -} +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -/** - * The RFC 4648 base 32 alphabet and character map. - * @see {@link https://tools.ietf.org/html/rfc4648} - */ + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; -var rfc4648 = { - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", - charmap: { - 0: 14, - 1: 8 + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || '; } -}; - -rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); -/** - * The Crockford base 32 alphabet and character map. - * @see {@link http://www.crockford.com/wrmg/base32.html} - */ + out += ' !' + $regexp + '.test(' + $data + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -var crockford = { - alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", - charmap: { - O: 0, - I: 1, - L: 1 - } -}; + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'pattern' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { pattern: '; -crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + if ($isData) { + out += '' + $schemaValue; + } else { + out += '' + it.util.toQuotedString($schema); + } -/** - * base32hex - * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} - */ + out += ' } '; -var base32hex = { - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", - charmap: {} -}; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; -base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + it.util.escapeQuotes($schema); + } -/** - * Create a new `Decoder` with the given options. - * - * @param {object} [options] - * @param {string} [type] Supported Base-32 variants are "rfc4648" and - * "crockford". - * @param {object} [charmap] Override the character map used in decoding. - * @constructor - */ + out += '"\' '; + } -function Decoder (options) { - this.buf = []; - this.shift = 8; - this.carry = 0; + if (it.opts.verbose) { + out += ' , schema: '; - if (options) { + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + it.util.toQuotedString($schema); + } - switch (options.type) { - case "rfc4648": - this.charmap = exports.rfc4648.charmap; - break; - case "crockford": - this.charmap = exports.crockford.charmap; - break; - case "base32hex": - this.charmap = exports.base32hex.charmap; - break; - default: - throw new Error("invalid type"); + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; } - if (options.charmap) this.charmap = options.charmap; + out += ' } '; + } else { + out += ' {} '; } -} - -/** - * The default character map coresponds to RFC4648. - */ - -Decoder.prototype.charmap = rfc4648.charmap; -/** - * Decode a string, continuing from the previous state. - * - * @param {string} str - * @return {Decoder} this - */ + var __err = out; + out = $$outStack.pop(); -Decoder.prototype.write = function (str) { - var charmap = this.charmap; - var buf = this.buf; - var shift = this.shift; - var carry = this.carry; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } - // decode string - str.toUpperCase().split("").forEach(function (char) { + out += '} '; - // ignore padding - if (char == "=") return; + if ($breakOnError) { + out += ' else { '; + } - // lookup symbol - var symbol = charmap[char] & 0xff; + return out; +}; - // 1: 00000 000 - // 2: 00 00000 0 - // 3: 0000 0000 - // 4: 0 00000 00 - // 5: 000 00000 - // 6: 00000 000 - // 7: 00 00000 0 +},{}],67:[function(require,module,exports){ +'use strict'; - shift -= 5; - if (shift > 0) { - carry |= symbol << shift; - } else if (shift < 0) { - buf.push(carry | (symbol >> -shift)); - shift += 8; - carry = (symbol << shift) & 0xff; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = _typeof($aProperties) == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); + out += 'var ' + $errs + ' = errors;var ' + $nextValid + ' = true;'; + + if ($ownProperties) { + out += ' var ' + $dataProperties + ' = undefined;'; + } + + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; '; } else { - buf.push(carry | symbol); - shift = 8; - carry = 0; + out += ' for (var ' + $key + ' in ' + $data + ') { '; } - }); - // save state - this.shift = shift; - this.carry = carry; + if ($someProperties) { + out += ' var isAdditional' + $lvl + ' = !(false '; - // for chaining - return this; -}; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + $schemaPath + '.hasOwnProperty(' + $key + ') '; + } else { + var arr1 = $schemaKeys; -/** - * Finish decoding. - * - * @param {string} [str] The final string to decode. - * @return {Array} Decoded byte array. - */ + if (arr1) { + var $propertyKey, + i1 = -1, + l1 = arr1.length - 1; -Decoder.prototype.finalize = function (str) { - if (str) { - this.write(str); - } - if (this.shift !== 8 && this.carry !== 0) { - this.buf.push(this.carry); - this.shift = 8; - this.carry = 0; - } - return this.buf; -}; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + $key + ' == ' + it.util.toQuotedString($propertyKey) + ' '; + } + } + } + } -/** - * Create a new `Encoder` with the given options. - * - * @param {object} [options] - * @param {string} [type] Supported Base-32 variants are "rfc4648" and - * "crockford". - * @param {object} [alphabet] Override the alphabet used in encoding. - * @constructor - */ + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; -function Encoder (options) { - this.buf = ""; - this.shift = 3; - this.carry = 0; + if (arr2) { + var $pProperty, + $i = -1, + l2 = arr2.length - 1; - if (options) { + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + it.usePattern($pProperty) + '.test(' + $key + ') '; + } + } + } - switch (options.type) { - case "rfc4648": - this.alphabet = exports.rfc4648.alphabet; - break; - case "crockford": - this.alphabet = exports.crockford.alphabet; - break; - case "base32hex": - this.alphabet = exports.base32hex.alphabet; - break; - default: - throw new Error("invalid type"); + out += ' ); if (isAdditional' + $lvl + ') { '; } - if (options.alphabet) this.alphabet = options.alphabet; - else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); - } -} - -/** - * The default alphabet coresponds to RFC4648. - */ - -Encoder.prototype.alphabet = rfc4648.alphabet; + if ($removeAdditional == 'all') { + out += ' delete ' + $data + '[' + $key + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; -/** - * Encode a byte array, continuing from the previous state. - * - * @param {byte[]} buf The byte array to encode. - * @return {Encoder} this - */ + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } -Encoder.prototype.write = function (buf) { - var shift = this.shift; - var carry = this.carry; - var symbol; - var byte; - var i; + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + $data + '[' + $key + ']; '; + } else { + out += ' ' + $nextValid + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ + + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'additionalProperties' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { additionalProperty: \'' + $additionalProperty + '\' } '; + + if (it.opts.messages !== false) { + out += ' , message: \''; + + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } - // encode each byte in buf - for (i = 0; i < buf.length; i++) { - byte = buf[i]; + out += '\' '; + } - // 1: 00000 000 - // 2: 00 00000 0 - // 3: 0000 0000 - // 4: 0 00000 00 - // 5: 000 00000 - // 6: 00000 000 - // 7: 00 00000 0 + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } - symbol = carry | (byte >> shift); - this.buf += this.alphabet[symbol & 0x1f]; + out += ' } '; + } else { + out += ' {} '; + } - if (shift > 5) { - shift -= 5; - symbol = byte >> shift; - this.buf += this.alphabet[symbol & 0x1f]; - } + var __err = out; + out = $$outStack.pop(); - shift = 5 - shift; - carry = byte << shift; - shift = 8 - shift; - } + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } - // save state - this.shift = shift; - this.carry = carry; + $errSchemaPath = $currErrSchemaPath; - // for chaining - return this; -}; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + $errs + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } -/** - * Finish encoding. - * - * @param {byte[]} [buf] The final byte array to encode. - * @return {string} The encoded byte array. - */ + out += ' if (!' + $nextValid + ') { errors = ' + $errs + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + $data + '[' + $key + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } -Encoder.prototype.finalize = function (buf) { - if (buf) { - this.write(buf); - } - if (this.shift !== 3) { - this.buf += this.alphabet[this.carry & 0x1f]; - this.shift = 3; - this.carry = 0; - } - return this.buf; -}; + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } + } + } -/** - * Convenience encoder. - * - * @param {byte[]} buf The byte array to encode. - * @param {object} [options] Options to pass to the encoder. - * @return {string} The encoded string. - */ + it.errorPath = $currentErrorPath; + } -exports.encode = function (buf, options) { - return new Encoder(options).finalize(buf); -}; + if ($someProperties) { + out += ' } '; + } -/** - * Convenience decoder. - * - * @param {string} str The string to decode. - * @param {object} [options] Options to pass to the decoder. - * @return {byte[]} The decoded byte array. - */ + out += ' } '; -exports.decode = function (str, options) { - return new Decoder(options).finalize(str); -}; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } -// Exports. -exports.Decoder = Decoder; -exports.Encoder = Encoder; -exports.charmap = charmap; -exports.crockford = crockford; -exports.rfc4648 = rfc4648; -exports.base32hex = base32hex; + var $useDefaults = it.opts.useDefaults && !it.compositeRule; -},{}],70:[function(require,module,exports){ -"use strict"; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; -// Module dependencies. -var base32 = require("./base32"); + if (arr3) { + var $propertyKey, + i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; -// Wrap decoder finalize to return a buffer; -var finalizeDecode = base32.Decoder.prototype.finalize; -base32.Decoder.prototype.finalize = function (buf) { - var bytes = finalizeDecode.call(this, buf); - return new Buffer(bytes); -}; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch["default"] !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + $nextData + ' = ' + $passData + '; '; + } -// Export Base32. -module.exports = base32; + if ($hasDefault) { + out += ' ' + $code + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + $useData + ' === undefined '; -},{"./base32":69}],71:[function(require,module,exports){ -/*! - * basic-auth - * Copyright(c) 2013 TJ Holowaychuk - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2016 Douglas Christopher Wilson - * MIT Licensed - */ + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } -'use strict' + out += ') { ' + $nextValid + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); -/** - * Module dependencies. - * @private - */ + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } -var Buffer = require('safe-buffer').Buffer + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -/** - * Module exports. - * @public - */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; -module.exports = auth -module.exports.parse = parse + if (it.opts.messages !== false) { + out += ' , message: \''; -/** - * RegExp for basic auth credentials - * - * credentials = auth-scheme 1*SP token68 - * auth-scheme = "Basic" ; case insensitive - * token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"=" - * @private - */ + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } -var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/ + out += '\' '; + } -/** - * RegExp for basic auth user/pass - * - * user-pass = userid ":" password - * userid = * - * password = *TEXT - * @private - */ + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -var USER_PASS_REGEXP = /^([^:]*):(.*)$/ + out += ' } '; + } else { + out += ' {} '; + } -/** - * Parse the Authorization header field of a request. - * - * @param {object} req - * @return {object} with .name and .pass - * @public - */ + var __err = out; + out = $$outStack.pop(); -function auth (req) { - if (!req) { - throw new TypeError('argument req is required') - } + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } - if (typeof req !== 'object') { - throw new TypeError('argument req is required to be an object') - } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + $useData + ' === undefined '; - // get header - var header = getAuthorization(req) + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } - // parse header - return parse(header) -} + out += ') { ' + $nextValid + ' = true; } else { '; + } else { + out += ' if (' + $useData + ' !== undefined '; -/** - * Decode base64 string. - * @private - */ + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } -function decodeBase64 (str) { - return Buffer.from(str, 'base64').toString() -} + out += ' ) { '; + } + } -/** - * Get the Authorization header from request object. - * @private - */ + out += ' ' + $code + ' } '; + } + } -function getAuthorization (req) { - if (!req.headers || typeof req.headers !== 'object') { - throw new TypeError('argument req is required to have headers property') + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } } - return req.headers.authorization -} + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; -/** - * Parse basic auth to object. - * - * @param {string} string - * @return {object} - * @public - */ + if (arr4) { + var $pProperty, + i4 = -1, + l4 = arr4.length - 1; -function parse (string) { - if (typeof string !== 'string') { - return undefined - } + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; - // parse header - var match = CREDENTIALS_REGEXP.exec(string) + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); - if (!match) { - return undefined - } + if ($ownProperties) { + out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; '; + } else { + out += ' for (var ' + $key + ' in ' + $data + ') { '; + } - // decode user pass - var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1])) + out += ' if (' + it.usePattern($pProperty) + '.test(' + $key + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; - if (!userPass) { - return undefined - } + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } - // return credentials object - return new Credentials(userPass[1], userPass[2]) -} + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } -/** - * Object to represent user credentials. - * @private - */ + out += ' } '; -function Credentials (name, pass) { - this.name = name - this.pass = pass -} + if ($breakOnError) { + out += ' else ' + $nextValid + ' = true; '; + } -},{"safe-buffer":72}],72:[function(require,module,exports){ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer + out += ' } '; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } + } } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} + if ($breakOnError) { + out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {'; + } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + out = it.util.cleanUpCode(out); + return out; +}; -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +},{}],68:[function(require,module,exports){ +'use strict'; -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + $errs + ' = errors;'; + + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + + if ($ownProperties) { + out += ' var ' + $dataProperties + ' = undefined; '; + } + + if ($ownProperties) { + out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; '; } else { - buf.fill(fill) + out += ' for (var ' + $key + ' in ' + $data + ') { '; } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} -},{"buffer":undefined}],73:[function(require,module,exports){ -'use strict' -var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l' + out += ' var startErrs' + $lvl + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; -// pre-compute lookup table -var ALPHABET_MAP = {} -for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z) + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z -} + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + $nextValid + ') { for (var ' + $i + '=startErrs' + $lvl + '; ' + $i + ' 126) throw new Error('Invalid prefix (' + prefix + ')') + if (it.opts.messages !== false) { + out += ' , message: \'property name \\\'' + $invalidName + '\\\' is invalid\' '; + } - chk = polymodStep(chk) ^ (c >> 5) - } - chk = polymodStep(chk) + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i) - chk = polymodStep(chk) ^ (v & 0x1f) - } - return chk -} + out += ' } '; + } else { + out += ' {} '; + } -function encode (prefix, words, LIMIT) { - LIMIT = LIMIT || 90 - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - prefix = prefix.toLowerCase() + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } - // determine chk mod - var chk = prefixChk(prefix) - var result = prefix + '1' - for (var i = 0; i < words.length; ++i) { - var x = words[i] - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + if ($breakOnError) { + out += ' break; '; + } - chk = polymodStep(chk) ^ x - result += ALPHABET.charAt(x) + out += ' } }'; } - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk) + if ($breakOnError) { + out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {'; } - chk ^= 1 - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f - result += ALPHABET.charAt(v) - } + out = it.util.cleanUpCode(out); + return out; +}; - return result -} +},{}],69:[function(require,module,exports){ +'use strict'; -function decode (str, LIMIT) { - LIMIT = LIMIT || 90 - if (str.length < 8) throw new TypeError(str + ' too short') - if (str.length > LIMIT) throw new TypeError('Exceeds length limit') +module.exports = function generate_ref(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + } else { + var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); - // don't allow mixed case - var lowered = str.toLowerCase() - var uppered = str.toUpperCase() - if (str !== lowered && str !== uppered) throw new Error('Mixed-case string ' + str) - str = lowered + if ($refVal === undefined) { + var $message = it.MissingRefError.message(it.baseId, $schema); - var split = str.lastIndexOf('1') - if (split === -1) throw new Error('No separator character for ' + str) - if (split === 0) throw new Error('Missing prefix for ' + str) + if (it.opts.missingRefs == 'fail') { + it.logger.error($message); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ - var prefix = str.slice(0, split) - var wordChars = str.slice(split + 1) - if (wordChars.length < 6) throw new Error('Data too short') + if (it.createErrors !== false) { + out += ' { keyword: \'' + '$ref' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { ref: \'' + it.util.escapeQuotes($schema) + '\' } '; - var chk = prefixChk(prefix) - var words = [] - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i) - var v = ALPHABET_MAP[c] - if (v === undefined) throw new Error('Unknown character ' + c) - chk = polymodStep(chk) ^ v + if (it.opts.messages !== false) { + out += ' , message: \'can\\\'t resolve reference ' + it.util.escapeQuotes($schema) + '\' '; + } - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v) - } + if (it.opts.verbose) { + out += ' , schema: ' + it.util.toQuotedString($schema) + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } - if (chk !== 1) throw new Error('Invalid checksum for ' + str) - return { prefix: prefix, words: words } -} + out += ' } '; + } else { + out += ' {} '; + } -function convert (data, inBits, outBits, pad) { - var value = 0 - var bits = 0 - var maxV = (1 << outBits) - 1 + var __err = out; + out = $$outStack.pop(); - var result = [] - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i] - bits += inBits + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } - while (bits >= outBits) { - bits -= outBits - result.push((value >> bits) & maxV) + if ($breakOnError) { + out += ' if (false) { '; + } + } else if (it.opts.missingRefs == 'ignore') { + it.logger.warn($message); + + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + throw new it.MissingRefError(it.baseId, $schema, $message); + } + } else if ($refVal.inline) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); + out += ' ' + $code + ' '; + + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + } + } else { + $async = $refVal.$async === true || it.async && $refVal.$async !== false; + $refCode = $refVal.code; } } - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV) + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + + if (it.opts.passContext) { + out += ' ' + $refCode + '.call(this, '; + } else { + out += ' ' + $refCode + '( '; } - } else { - if (bits >= inBits) throw new Error('Excess padding') - if ((value << (outBits - bits)) & maxV) throw new Error('Non-zero padding') - } - return result -} + out += ' ' + $data + ', (dataPath || \'\')'; -function toWords (bytes) { - return convert(bytes, 8, 5, true) -} + if (it.errorPath != '""') { + out += ' + ' + it.errorPath; + } -function fromWords (words) { - return convert(words, 5, 8, false) -} + var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + $parentData + ' , ' + $parentDataProperty + ', rootData) '; + var __callValidate = out; + out = $$outStack.pop(); -module.exports = { - decode: decode, - encode: encode, - toWords: toWords, - fromWords: fromWords -} + if ($async) { + if (!it.async) throw new Error('async schema referenced by sync schema'); -},{}],74:[function(require,module,exports){ -/* - * big.js v5.1.2 - * A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic. - * Copyright (c) 2017 Michael Mclaughlin - * https://github.com/MikeMcl/big.js/LICENCE - */ -;(function (GLOBAL) { - 'use strict'; - var Big, - - -/************************************** EDITABLE DEFAULTS *****************************************/ - - - // The default values below must be integers within the stated ranges. - - /* - * The maximum number of decimal places (DP) of the results of operations involving division: - * div and sqrt, and pow with negative exponents. - */ - DP = 20, // 0 to MAX_DP - - /* - * The rounding mode (RM) used when rounding to the above decimal places. - * - * 0 Towards zero (i.e. truncate, no rounding). (ROUND_DOWN) - * 1 To nearest neighbour. If equidistant, round up. (ROUND_HALF_UP) - * 2 To nearest neighbour. If equidistant, to even. (ROUND_HALF_EVEN) - * 3 Away from zero. (ROUND_UP) - */ - RM = 1, // 0, 1, 2 or 3 - - // The maximum value of DP and Big.DP. - MAX_DP = 1E6, // 0 to 1000000 - - // The maximum magnitude of the exponent argument to the pow method. - MAX_POWER = 1E6, // 1 to 1000000 - - /* - * The negative exponent (NE) at and beneath which toString returns exponential notation. - * (JavaScript numbers: -7) - * -1000000 is the minimum recommended exponent value of a Big. - */ - NE = -7, // 0 to -1000000 - - /* - * The positive exponent (PE) at and above which toString returns exponential notation. - * (JavaScript numbers: 21) - * 1000000 is the maximum recommended exponent value of a Big. - * (This limit is not enforced or checked.) - */ - PE = 21, // 0 to 1000000 - - -/**************************************************************************************************/ - - - // Error messages. - NAME = '[big.js] ', - INVALID = NAME + 'Invalid ', - INVALID_DP = INVALID + 'decimal places', - INVALID_RM = INVALID + 'rounding mode', - DIV_BY_ZERO = NAME + 'Division by zero', - - // The shared prototype object. - P = {}, - UNDEFINED = void 0, - NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; - - - /* - * Create and return a Big constructor. - * - */ - function _Big_() { - - /* - * The Big constructor and exported function. - * Create and return a new instance of a Big number object. - * - * n {number|string|Big} A numeric value. - */ - function Big(n) { - var x = this; - - // Enable constructor usage without new. - if (!(x instanceof Big)) return n === UNDEFINED ? _Big_() : new Big(n); - - // Duplicate. - if (n instanceof Big) { - x.s = n.s; - x.e = n.e; - x.c = n.c.slice(); - } else { - parse(x, n); - } - - /* - * Retain a reference to this Big constructor, and shadow Big.prototype.constructor which - * points to Object. - */ - x.constructor = Big; - } - - Big.prototype = P; - Big.DP = DP; - Big.RM = RM; - Big.NE = NE; - Big.PE = PE; - Big.version = '5.0.2'; - - return Big; - } - - - /* - * Parse the number or string value passed to a Big constructor. - * - * x {Big} A Big number instance. - * n {number|string} A numeric value. - */ - function parse(x, n) { - var e, i, nl; - - // Minus zero? - if (n === 0 && 1 / n < 0) n = '-0'; - else if (!NUMERIC.test(n += '')) throw Error(INVALID + 'number'); - - // Determine sign. - x.s = n.charAt(0) == '-' ? (n = n.slice(1), -1) : 1; - - // Decimal point? - if ((e = n.indexOf('.')) > -1) n = n.replace('.', ''); - - // Exponential form? - if ((i = n.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +n.slice(i + 1); - n = n.substring(0, i); - } else if (e < 0) { - - // Integer. - e = n.length; - } - - nl = n.length; - - // Determine leading zeros. - for (i = 0; i < nl && n.charAt(i) == '0';) ++i; - - if (i == nl) { - - // Zero. - x.c = [x.e = 0]; - } else { - - // Determine trailing zeros. - for (; nl > 0 && n.charAt(--nl) == '0';); - x.e = e - i - 1; - x.c = []; - - // Convert string to array of digits without leading/trailing zeros. - for (e = 0; i <= nl;) x.c[e++] = +n.charAt(i++); - } - - return x; - } - - - /* - * Round Big x to a maximum of dp decimal places using rounding mode rm. - * Called by stringify, P.div, P.round and P.sqrt. - * - * x {Big} The Big to round. - * dp {number} Integer, 0 to MAX_DP inclusive. - * rm {number} 0, 1, 2 or 3 (DOWN, HALF_UP, HALF_EVEN, UP) - * [more] {boolean} Whether the result of division was truncated. - */ - function round(x, dp, rm, more) { - var xc = x.c, - i = x.e + dp + 1; - - if (i < xc.length) { - if (rm === 1) { - - // xc[i] is the digit after the digit that may be rounded up. - more = xc[i] >= 5; - } else if (rm === 2) { - more = xc[i] > 5 || xc[i] == 5 && - (more || i < 0 || xc[i + 1] !== UNDEFINED || xc[i - 1] & 1); - } else if (rm === 3) { - more = more || xc[i] !== UNDEFINED || i < 0; - } else { - more = false; - if (rm !== 0) throw Error(INVALID_RM); - } - - if (i < 1) { - xc.length = 1; - - if (more) { - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - x.e = -dp; - xc[0] = 1; - } else { - - // Zero. - xc[0] = x.e = 0; - } - } else { - - // Remove any digits after the required decimal places. - xc.length = i--; - - // Round up? - if (more) { - - // Rounding up may mean the previous digit has to be rounded up. - for (; ++xc[i] > 9;) { - xc[i] = 0; - if (!i--) { - ++x.e; - xc.unshift(1); - } - } - } - - // Remove trailing zeros. - for (i = xc.length; !xc[--i];) xc.pop(); - } - } else if (rm < 0 || rm > 3 || rm !== ~~rm) { - throw Error(INVALID_RM); - } - - return x; - } - - - /* - * Return a string representing the value of Big x in normal or exponential notation. - * Handles P.toExponential, P.toFixed, P.toJSON, P.toPrecision, P.toString and P.valueOf. - * - * x {Big} - * id? {number} Caller id. - * 1 toExponential - * 2 toFixed - * 3 toPrecision - * 4 valueOf - * n? {number|undefined} Caller's argument. - * k? {number|undefined} - */ - function stringify(x, id, n, k) { - var e, s, - Big = x.constructor, - z = !x.c[0]; - - if (n !== UNDEFINED) { - if (n !== ~~n || n < (id == 3) || n > MAX_DP) { - throw Error(id == 3 ? INVALID + 'precision' : INVALID_DP); - } - - x = new Big(x); - - // The index of the digit that may be rounded up. - n = k - x.e; - - // Round? - if (x.c.length > ++k) round(x, n, Big.RM); - - // toFixed: recalculate k as x.e may have changed if value rounded up. - if (id == 2) k = x.e + n + 1; - - // Append zeros? - for (; x.c.length < k;) x.c.push(0); - } - - e = x.e; - s = x.c.join(''); - n = s.length; - - // Exponential notation? - if (id != 2 && (id == 1 || id == 3 && k <= e || e <= Big.NE || e >= Big.PE)) { - s = s.charAt(0) + (n > 1 ? '.' + s.slice(1) : '') + (e < 0 ? 'e' : 'e+') + e; - - // Normal notation. - } else if (e < 0) { - for (; ++e;) s = '0' + s; - s = '0.' + s; - } else if (e > 0) { - if (++e > n) for (e -= n; e--;) s += '0'; - else if (e < n) s = s.slice(0, e) + '.' + s.slice(e); - } else if (n > 1) { - s = s.charAt(0) + '.' + s.slice(1); - } - - return x.s < 0 && (!z || id == 4) ? '-' + s : s; - } - - - // Prototype/instance methods - - - /* - * Return a new Big whose value is the absolute value of this Big. - */ - P.abs = function () { - var x = new this.constructor(this); - x.s = 1; - return x; - }; - - - /* - * Return 1 if the value of this Big is greater than the value of Big y, - * -1 if the value of this Big is less than the value of Big y, or - * 0 if they have the same value. - */ - P.cmp = function (y) { - var isneg, - x = this, - xc = x.c, - yc = (y = new x.constructor(y)).c, - i = x.s, - j = y.s, - k = x.e, - l = y.e; - - // Either zero? - if (!xc[0] || !yc[0]) return !xc[0] ? !yc[0] ? 0 : -j : i; - - // Signs differ? - if (i != j) return i; - - isneg = i < 0; - - // Compare exponents. - if (k != l) return k > l ^ isneg ? 1 : -1; - - j = (k = xc.length) < (l = yc.length) ? k : l; - - // Compare digit by digit. - for (i = -1; ++i < j;) { - if (xc[i] != yc[i]) return xc[i] > yc[i] ^ isneg ? 1 : -1; - } - - // Compare lengths. - return k == l ? 0 : k > l ^ isneg ? 1 : -1; - }; - - - /* - * Return a new Big whose value is the value of this Big divided by the value of Big y, rounded, - * if necessary, to a maximum of Big.DP decimal places using rounding mode Big.RM. - */ - P.div = function (y) { - var x = this, - Big = x.constructor, - a = x.c, // dividend - b = (y = new Big(y)).c, // divisor - k = x.s == y.s ? 1 : -1, - dp = Big.DP; - - if (dp !== ~~dp || dp < 0 || dp > MAX_DP) throw Error(INVALID_DP); - - // Divisor is zero? - if (!b[0]) throw Error(DIV_BY_ZERO); - - // Dividend is 0? Return +-0. - if (!a[0]) return new Big(k * 0); - - var bl, bt, n, cmp, ri, - bz = b.slice(), - ai = bl = b.length, - al = a.length, - r = a.slice(0, bl), // remainder - rl = r.length, - q = y, // quotient - qc = q.c = [], - qi = 0, - d = dp + (q.e = x.e - y.e) + 1; // number of digits of the result - - q.s = k; - k = d < 0 ? 0 : d; - - // Create version of divisor with leading zero. - bz.unshift(0); - - // Add zeros to make remainder as long as divisor. - for (; rl++ < bl;) r.push(0); - - do { - - // n is how many times the divisor goes into current remainder. - for (n = 0; n < 10; n++) { - - // Compare divisor and remainder. - if (bl != (rl = r.length)) { - cmp = bl > rl ? 1 : -1; - } else { - for (ri = -1, cmp = 0; ++ri < bl;) { - if (b[ri] != r[ri]) { - cmp = b[ri] > r[ri] ? 1 : -1; - break; - } - } - } - - // If divisor < remainder, subtract divisor from remainder. - if (cmp < 0) { - - // Remainder can't be more than 1 digit longer than divisor. - // Equalise lengths using divisor with extra leading zero? - for (bt = rl == bl ? b : bz; rl;) { - if (r[--rl] < bt[rl]) { - ri = rl; - for (; ri && !r[--ri];) r[ri] = 9; - --r[ri]; - r[rl] += 10; - } - r[rl] -= bt[rl]; - } - - for (; !r[0];) r.shift(); - } else { - break; - } - } - - // Add the digit n to the result array. - qc[qi++] = cmp ? n : ++n; - - // Update the remainder. - if (r[0] && cmp) r[rl] = a[ai] || 0; - else r = [a[ai]]; - - } while ((ai++ < al || r[0] !== UNDEFINED) && k--); - - // Leading zero? Do not remove if result is simply zero (qi == 1). - if (!qc[0] && qi != 1) { - - // There can't be more than one zero. - qc.shift(); - q.e--; - } - - // Round? - if (qi > d) round(q, dp, Big.RM, r[0] !== UNDEFINED); - - return q; - }; - - - /* - * Return true if the value of this Big is equal to the value of Big y, otherwise return false. - */ - P.eq = function (y) { - return !this.cmp(y); - }; - - - /* - * Return true if the value of this Big is greater than the value of Big y, otherwise return - * false. - */ - P.gt = function (y) { - return this.cmp(y) > 0; - }; - - - /* - * Return true if the value of this Big is greater than or equal to the value of Big y, otherwise - * return false. - */ - P.gte = function (y) { - return this.cmp(y) > -1; - }; - - - /* - * Return true if the value of this Big is less than the value of Big y, otherwise return false. - */ - P.lt = function (y) { - return this.cmp(y) < 0; - }; - - - /* - * Return true if the value of this Big is less than or equal to the value of Big y, otherwise - * return false. - */ - P.lte = function (y) { - return this.cmp(y) < 1; - }; - - - /* - * Return a new Big whose value is the value of this Big minus the value of Big y. - */ - P.minus = P.sub = function (y) { - var i, j, t, xlty, - x = this, - Big = x.constructor, - a = x.s, - b = (y = new Big(y)).s; - - // Signs differ? - if (a != b) { - y.s = -b; - return x.plus(y); - } - - var xc = x.c.slice(), - xe = x.e, - yc = y.c, - ye = y.e; - - // Either zero? - if (!xc[0] || !yc[0]) { - - // y is non-zero? x is non-zero? Or both are zero. - return yc[0] ? (y.s = -b, y) : new Big(xc[0] ? x : 0); - } - - // Determine which is the bigger number. Prepend zeros to equalise exponents. - if (a = xe - ye) { - - if (xlty = a < 0) { - a = -a; - t = xc; - } else { - ye = xe; - t = yc; - } - - t.reverse(); - for (b = a; b--;) t.push(0); - t.reverse(); - } else { - - // Exponents equal. Check digit by digit. - j = ((xlty = xc.length < yc.length) ? xc : yc).length; - - for (a = b = 0; b < j; b++) { - if (xc[b] != yc[b]) { - xlty = xc[b] < yc[b]; - break; - } - } - } - - // x < y? Point xc to the array of the bigger number. - if (xlty) { - t = xc; - xc = yc; - yc = t; - y.s = -y.s; - } - - /* - * Append zeros to xc if shorter. No need to add zeros to yc if shorter as subtraction only - * needs to start at yc.length. - */ - if ((b = (j = yc.length) - (i = xc.length)) > 0) for (; b--;) xc[i++] = 0; - - // Subtract yc from xc. - for (b = i; j > a;) { - if (xc[--j] < yc[j]) { - for (i = j; i && !xc[--i];) xc[i] = 9; - --xc[i]; - xc[j] += 10; - } - - xc[j] -= yc[j]; - } - - // Remove trailing zeros. - for (; xc[--b] === 0;) xc.pop(); - - // Remove leading zeros and adjust exponent accordingly. - for (; xc[0] === 0;) { - xc.shift(); - --ye; - } - - if (!xc[0]) { - - // n - n = +0 - y.s = 1; - - // Result must be zero. - xc = [ye = 0]; - } - - y.c = xc; - y.e = ye; - - return y; - }; - - - /* - * Return a new Big whose value is the value of this Big modulo the value of Big y. - */ - P.mod = function (y) { - var ygtx, - x = this, - Big = x.constructor, - a = x.s, - b = (y = new Big(y)).s; - - if (!y.c[0]) throw Error(DIV_BY_ZERO); - - x.s = y.s = 1; - ygtx = y.cmp(x) == 1; - x.s = a; - y.s = b; - - if (ygtx) return new Big(x); - - a = Big.DP; - b = Big.RM; - Big.DP = Big.RM = 0; - x = x.div(y); - Big.DP = a; - Big.RM = b; - - return this.minus(x.times(y)); - }; - - - /* - * Return a new Big whose value is the value of this Big plus the value of Big y. - */ - P.plus = P.add = function (y) { - var t, - x = this, - Big = x.constructor, - a = x.s, - b = (y = new Big(y)).s; - - // Signs differ? - if (a != b) { - y.s = -b; - return x.minus(y); - } - - var xe = x.e, - xc = x.c, - ye = y.e, - yc = y.c; - - // Either zero? y is non-zero? x is non-zero? Or both are zero. - if (!xc[0] || !yc[0]) return yc[0] ? y : new Big(xc[0] ? x : a * 0); - - xc = xc.slice(); - - // Prepend zeros to equalise exponents. - // Note: Faster to use reverse then do unshifts. - if (a = xe - ye) { - if (a > 0) { - ye = xe; - t = yc; - } else { - a = -a; - t = xc; - } - - t.reverse(); - for (; a--;) t.push(0); - t.reverse(); - } - - // Point xc to the longer array. - if (xc.length - yc.length < 0) { - t = yc; - yc = xc; - xc = t; - } - - a = yc.length; - - // Only start adding at yc.length - 1 as the further digits of xc can be left as they are. - for (b = 0; a; xc[a] %= 10) b = (xc[--a] = xc[a] + yc[a] + b) / 10 | 0; - - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - - if (b) { - xc.unshift(b); - ++ye; - } - - // Remove trailing zeros. - for (a = xc.length; xc[--a] === 0;) xc.pop(); - - y.c = xc; - y.e = ye; - - return y; - }; - - - /* - * Return a Big whose value is the value of this Big raised to the power n. - * If n is negative, round to a maximum of Big.DP decimal places using rounding - * mode Big.RM. - * - * n {number} Integer, -MAX_POWER to MAX_POWER inclusive. - */ - P.pow = function (n) { - var x = this, - one = new x.constructor(1), - y = one, - isneg = n < 0; - - if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) throw Error(INVALID + 'exponent'); - if (isneg) n = -n; - - for (;;) { - if (n & 1) y = y.times(x); - n >>= 1; - if (!n) break; - x = x.times(x); - } - - return isneg ? one.div(y) : y; - }; - - - /* - * Return a new Big whose value is the value of this Big rounded to a maximum of dp decimal - * places using rounding mode rm. - * If dp is not specified, round to 0 decimal places. - * If rm is not specified, use Big.RM. - * - * dp? {number} Integer, 0 to MAX_DP inclusive. - * rm? 0, 1, 2 or 3 (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_UP) - */ - P.round = function (dp, rm) { - var Big = this.constructor; - if (dp === UNDEFINED) dp = 0; - else if (dp !== ~~dp || dp < 0 || dp > MAX_DP) throw Error(INVALID_DP); - return round(new Big(this), dp, rm === UNDEFINED ? Big.RM : rm); - }; - - - /* - * Return a new Big whose value is the square root of the value of this Big, rounded, if - * necessary, to a maximum of Big.DP decimal places using rounding mode Big.RM. - */ - P.sqrt = function () { - var r, c, t, - x = this, - Big = x.constructor, - s = x.s, - e = x.e, - half = new Big(0.5); - - // Zero? - if (!x.c[0]) return new Big(x); - - // Negative? - if (s < 0) throw Error(NAME + 'No square root'); - - // Estimate. - s = Math.sqrt(x.toString()); - - // Math.sqrt underflow/overflow? - // Re-estimate: pass x to Math.sqrt as integer, then adjust the result exponent. - if (s === 0 || s === 1 / 0) { - c = x.c.join(''); - if (!(c.length + e & 1)) c += '0'; - r = new Big(Math.sqrt(c).toString()); - r.e = ((e + 1) / 2 | 0) - (e < 0 || e & 1); - } else { - r = new Big(s.toString()); - } - - e = r.e + (Big.DP += 4); - - // Newton-Raphson iteration. - do { - t = r; - r = half.times(t.plus(x.div(t))); - } while (t.c.slice(0, e).join('') !== r.c.slice(0, e).join('')); - - return round(r, Big.DP -= 4, Big.RM); - }; - - - /* - * Return a new Big whose value is the value of this Big times the value of Big y. - */ - P.times = P.mul = function (y) { - var c, - x = this, - Big = x.constructor, - xc = x.c, - yc = (y = new Big(y)).c, - a = xc.length, - b = yc.length, - i = x.e, - j = y.e; - - // Determine sign of result. - y.s = x.s == y.s ? 1 : -1; - - // Return signed 0 if either 0. - if (!xc[0] || !yc[0]) return new Big(y.s * 0); - - // Initialise exponent of result as x.e + y.e. - y.e = i + j; - - // If array xc has fewer digits than yc, swap xc and yc, and lengths. - if (a < b) { - c = xc; - xc = yc; - yc = c; - j = a; - a = b; - b = j; - } - - // Initialise coefficient array of result with zeros. - for (c = new Array(j = a + b); j--;) c[j] = 0; - - // Multiply. - - // i is initially xc.length. - for (i = b; i--;) { - b = 0; - - // a is yc.length. - for (j = a + i; j > i;) { - - // Current sum of products at this digit position, plus carry. - b = c[j] + yc[i] * xc[j - i - 1] + b; - c[j--] = b % 10; - - // carry - b = b / 10 | 0; - } - - c[j] = (c[j] + b) % 10; - } - - // Increment result exponent if there is a final carry, otherwise remove leading zero. - if (b) ++y.e; - else c.shift(); - - // Remove trailing zeros. - for (i = c.length; !c[--i];) c.pop(); - y.c = c; - - return y; - }; - - - /* - * Return a string representing the value of this Big in exponential notation to dp fixed decimal - * places and rounded using Big.RM. - * - * dp? {number} Integer, 0 to MAX_DP inclusive. - */ - P.toExponential = function (dp) { - return stringify(this, 1, dp, dp); - }; - - - /* - * Return a string representing the value of this Big in normal notation to dp fixed decimal - * places and rounded using Big.RM. - * - * dp? {number} Integer, 0 to MAX_DP inclusive. - * - * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. - * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. - */ - P.toFixed = function (dp) { - return stringify(this, 2, dp, this.e + dp); - }; - - - /* - * Return a string representing the value of this Big rounded to sd significant digits using - * Big.RM. Use exponential notation if sd is less than the number of digits necessary to represent - * the integer part of the value in normal notation. - * - * sd {number} Integer, 1 to MAX_DP inclusive. - */ - P.toPrecision = function (sd) { - return stringify(this, 3, sd, sd - 1); - }; - - - /* - * Return a string representing the value of this Big. - * Return exponential notation if this Big has a positive exponent equal to or greater than - * Big.PE, or a negative exponent equal to or less than Big.NE. - * Omit the sign for negative zero. - */ - P.toString = function () { - return stringify(this); - }; - - - /* - * Return a string representing the value of this Big. - * Return exponential notation if this Big has a positive exponent equal to or greater than - * Big.PE, or a negative exponent equal to or less than Big.NE. - * Include the sign for negative zero. - */ - P.valueOf = P.toJSON = function () { - return stringify(this, 4); - }; - - - // Export - - - Big = _Big_(); - - Big['default'] = Big.Big = Big; - - //AMD. - if (typeof define === 'function' && define.amd) { - define(function () { return Big; }); - - // Node and other CommonJS-like environments that support module.exports. - } else if (typeof module !== 'undefined' && module.exports) { - module.exports = Big; - - //Browser. - } else { - GLOBAL.Big = Big; - } -})(this); + if ($breakOnError) { + out += ' var ' + $valid + '; '; + } -},{}],75:[function(require,module,exports){ -// (public) Constructor -function BigInteger(a, b, c) { - if (!(this instanceof BigInteger)) - return new BigInteger(a, b, c) + out += ' try { await ' + __callValidate + '; '; - if (a != null) { - if ("number" == typeof a) this.fromNumber(a, b, c) - else if (b == null && "string" != typeof a) this.fromString(a, 256) - else this.fromString(a, b) - } -} + if ($breakOnError) { + out += ' ' + $valid + ' = true; '; + } -var proto = BigInteger.prototype + out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; -// duck-typed isBigInteger -proto.__bigi = require('../package.json').version -BigInteger.isBigInteger = function (obj, check_ver) { - return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) -} + if ($breakOnError) { + out += ' ' + $valid + ' = false; '; + } -// Bits per digit -var dbits + out += ' } '; -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. + if ($breakOnError) { + out += ' if (' + $valid + ') { '; + } + } else { + out += ' if (!' + __callValidate + ') { if (vErrors === null) vErrors = ' + $refCode + '.errors; else vErrors = vErrors.concat(' + $refCode + '.errors); errors = vErrors.length; } '; -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c - c = Math.floor(v / 0x4000000) - w[j++] = v & 0x3ffffff - } - return c -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15 - while (--n >= 0) { - var l = this[i] & 0x7fff - var h = this[i++] >> 15 - var m = xh * l + h * xl - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) - w[j++] = l & 0x3fffffff + if ($breakOnError) { + out += ' else { '; + } + } } - return c -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14 - while (--n >= 0) { - var l = this[i] & 0x3fff - var h = this[i++] >> 14 - var m = xh * l + h * xl - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c - c = (l >> 28) + (m >> 14) + xh * h - w[j++] = l & 0xfffffff - } - return c -} - -// wtf? -BigInteger.prototype.am = am1 -dbits = 26 - -BigInteger.prototype.DB = dbits -BigInteger.prototype.DM = ((1 << dbits) - 1) -var DV = BigInteger.prototype.DV = (1 << dbits) - -var BI_FP = 52 -BigInteger.prototype.FV = Math.pow(2, BI_FP) -BigInteger.prototype.F1 = BI_FP - dbits -BigInteger.prototype.F2 = 2 * dbits - BI_FP - -// Digit conversions -var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" -var BI_RC = new Array() -var rr, vv -rr = "0".charCodeAt(0) -for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv -rr = "a".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv -rr = "A".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv -function int2char(n) { - return BI_RM.charAt(n) -} + return out; +}; -function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)] - return (c == null) ? -1 : c -} +},{}],70:[function(require,module,exports){ +'use strict'; -// (protected) copy this to r -function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] - r.t = this.t - r.s = this.s -} +module.exports = function generate_required(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1 - this.s = (x < 0) ? -1 : 0 - if (x > 0) this[0] = x - else if (x < -1) this[0] = x + DV - else this.t = 0 -} + var $vSchema = 'schema' + $lvl; -// return bigint initialized to value -function nbv(i) { - var r = new BigInteger() - r.fromInt(i) - return r -} + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; -// (protected) set from string and radix -function bnpFromString(s, b) { - var self = this - - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 256) k = 8; // byte array - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else { - self.fromRadix(s, b) - return - } - self.t = 0 - self.s = 0 - var i = s.length, - mi = false, - sh = 0 - while (--i >= 0) { - var x = (k == 8) ? s[i] & 0xff : intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-") mi = true - continue - } - mi = false - if (sh == 0) - self[self.t++] = x - else if (sh + k > self.DB) { - self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh - self[self.t++] = (x >> (self.DB - sh)) - } else - self[self.t - 1] |= x << sh - sh += k - if (sh >= self.DB) sh -= self.DB - } - if (k == 8 && (s[0] & 0x80) != 0) { - self.s = -1 - if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh - } - self.clamp() - if (mi) BigInteger.ZERO.subTo(self, self) -} + if (arr1) { + var $property, + i1 = -1, + l1 = arr1.length - 1; -// (protected) clamp off excess high words -function bnpClamp() { - var c = this.s & this.DM - while (this.t > 0 && this[this.t - 1] == c)--this.t -} + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; -// (public) return string representation in given radix -function bnToString(b) { - var self = this - if (self.s < 0) return "-" + self.negate() - .toString(b) - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else return self.toRadix(b) - var km = (1 << k) - 1, - d, m = false, - r = "", - i = self.t - var p = self.DB - (i * self.DB) % k - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) > 0) { - m = true - r = int2char(d) - } - while (i >= 0) { - if (p < k) { - d = (self[i] & ((1 << p) - 1)) << (k - p) - d |= self[--i] >> (p += self.DB - k) - } else { - d = (self[i] >> (p -= k)) & km - if (p <= 0) { - p += self.DB - --i + if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) { + $required[$required.length] = $property; + } } } - if (d > 0) m = true - if (m) r += int2char(d) + } else { + var $required = $schema; } } - return m ? r : "0" -} -// (public) -this -function bnNegate() { - var r = new BigInteger() - BigInteger.ZERO.subTo(this, r) - return r -} + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; -// (public) |this| -function bnAbs() { - return (this.s < 0) ? this.negate() : this -} + if ($breakOnError) { + out += ' var missing' + $lvl + '; '; -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s - a.s - if (r != 0) return r - var i = this.t - r = i - a.t - if (r != 0) return (this.s < 0) ? -r : r - while (--i >= 0) - if ((r = this[i] - a[i]) != 0) return r - return 0 -} + if ($loopRequired) { + if (!$isData) { + out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; '; + } -// returns bit length of the integer x -function nbits(x) { - var r = 1, - t - if ((t = x >>> 16) != 0) { - x = t - r += 16 - } - if ((t = x >> 8) != 0) { - x = t - r += 8 - } - if ((t = x >> 4) != 0) { - x = t - r += 4 - } - if ((t = x >> 2) != 0) { - x = t - r += 2 - } - if ((t = x >> 1) != 0) { - x = t - r += 1 - } - return r -} + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; -// (public) return the number of bits in "this" -function bnBitLength() { - if (this.t <= 0) return 0 - return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) -} + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } -// (public) return the number of bytes in "this" -function bnByteLength() { - return this.bitLength() >> 3 -} + out += ' var ' + $valid + ' = true; '; -// (protected) r = this << n*DB -function bnpDLShiftTo(n, r) { - var i - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] - for (i = n - 1; i >= 0; --i) r[i] = 0 - r.t = this.t + n - r.s = this.s -} + if ($isData) { + out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {'; + } -// (protected) r = this >> n*DB -function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i] - r.t = Math.max(this.t - n, 0) - r.s = this.s -} + out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { ' + $valid + ' = ' + $data + '[' + $vSchema + '[' + $i + ']] !== undefined '; -// (protected) r = this << n -function bnpLShiftTo(n, r) { - var self = this - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << cbs) - 1 - var ds = Math.floor(n / self.DB), - c = (self.s << bs) & self.DM, - i - for (i = self.t - 1; i >= 0; --i) { - r[i + ds + 1] = (self[i] >> cbs) | c - c = (self[i] & bm) << bs - } - for (i = ds - 1; i >= 0; --i) r[i] = 0 - r[ds] = c - r.t = self.t + ds + 1 - r.s = self.s - r.clamp() -} - -// (protected) r = this >> n -function bnpRShiftTo(n, r) { - var self = this - r.s = self.s - var ds = Math.floor(n / self.DB) - if (ds >= self.t) { - r.t = 0 - return - } - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << bs) - 1 - r[0] = self[ds] >> bs - for (var i = ds + 1; i < self.t; ++i) { - r[i - ds - 1] |= (self[i] & bm) << cbs - r[i - ds] = self[i] >> bs - } - if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs - r.t = self.t - ds - r.clamp() -} - -// (protected) r = this - a -function bnpSubTo(a, r) { - var self = this - var i = 0, - c = 0, - m = Math.min(a.t, self.t) - while (i < m) { - c += self[i] - a[i] - r[i++] = c & self.DM - c >>= self.DB - } - if (a.t < self.t) { - c -= a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c -= a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c -= a.s - } - r.s = (c < 0) ? -1 : 0 - if (c < -1) r[i++] = self.DV + c - else if (c > 0) r[i++] = c - r.t = i - r.clamp() -} + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) '; + } -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a, r) { - var x = this.abs(), - y = a.abs() - var i = x.t - r.t = i + y.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) - r.s = 0 - r.clamp() - if (this.s != a.s) BigInteger.ZERO.subTo(r, r) -} + out += '; if (!' + $valid + ') break; } '; -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs() - var i = r.t = 2 * x.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1) - if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r[i + x.t] -= x.DV - r[i + x.t + 1] = 1 - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) - r.s = 0 - r.clamp() -} + if ($isData) { + out += ' } '; + } -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m, q, r) { - var self = this - var pm = m.abs() - if (pm.t <= 0) return - var pt = self.abs() - if (pt.t < pm.t) { - if (q != null) q.fromInt(0) - if (r != null) self.copyTo(r) - return - } - if (r == null) r = new BigInteger() - var y = new BigInteger(), - ts = self.s, - ms = m.s - var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y) - pt.lShiftTo(nsh, r) - } else { - pm.copyTo(y) - pt.copyTo(r) - } - var ys = y.t - var y0 = y[ys - 1] - if (y0 == 0) return - var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) - var d1 = self.FV / yt, - d2 = (1 << self.F1) / yt, - e = 1 << self.F2 - var i = r.t, - j = i - ys, - t = (q == null) ? new BigInteger() : q - y.dlShiftTo(j, t) - if (r.compareTo(t) >= 0) { - r[r.t++] = 1 - r.subTo(t, r) - } - BigInteger.ONE.dlShiftTo(ys, t) - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0 - while (--j >= 0) { - // Estimate quotient digit - var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out - y.dlShiftTo(j, t) - r.subTo(t, r) - while (r[i] < --qd) r.subTo(t, r) - } - } - if (q != null) { - r.drShiftTo(ys, q) - if (ts != ms) BigInteger.ZERO.subTo(q, q) - } - r.t = ys - r.clamp() - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r) -} + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -// (public) this mod a -function bnMod(a) { - var r = new BigInteger() - this.abs() - .divRemTo(a, null, r) - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) - return r -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; -// Modular reduction using "classic" algorithm -function Classic(m) { - this.m = m -} + if (it.opts.messages !== false) { + out += ' , message: \''; -function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) - else return x -} + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } -function cRevert(x) { - return x -} + out += '\' '; + } -function cReduce(x) { - x.divRemTo(this.m, null, x) -} + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -function cMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} + out += ' } '; + } else { + out += ' {} '; + } -function cSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} + var __err = out; + out = $$outStack.pop(); -Classic.prototype.convert = cConvert -Classic.prototype.revert = cRevert -Classic.prototype.reduce = cReduce -Classic.prototype.mulTo = cMulTo -Classic.prototype.sqrTo = cSqrTo + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if (this.t < 1) return 0 - var x = this[0] - if ((x & 1) == 0) return 0 - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y > 0) ? this.DV - y : -y -} + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; -// Montgomery reduction -function Montgomery(m) { - this.m = m - this.mp = m.invDigit() - this.mpl = this.mp & 0x7fff - this.mph = this.mp >> 15 - this.um = (1 << (m.DB - 15)) - 1 - this.mt2 = 2 * m.t -} + if (arr2) { + var $propertyKey, + $i = -1, + l2 = arr2.length - 1; -// xR mod m -function montConvert(x) { - var r = new BigInteger() - x.abs() - .dlShiftTo(this.m.t, r) - r.divRemTo(this.m, null, r) - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) - return r -} + while ($i < l2) { + $propertyKey = arr2[$i += 1]; -// x/R mod m -function montRevert(x) { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r -} + if ($i) { + out += ' || '; + } -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while (x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0 - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff - var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM - // use am to combine the multiply-shift-add into one call - j = i + this.m.t - x[j] += this.m.am(0, u0, x, i, 0, this.m.t) - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV - x[++j]++ - } - } - x.clamp() - x.drShiftTo(this.m.t, x) - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) -} + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + $useData + ' === undefined '; -// r = "x^2/R mod m"; x != r -function montSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } -// r = "xy/R mod m"; x,y != r -function montMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} + out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) '; + } + } -Montgomery.prototype.convert = montConvert -Montgomery.prototype.revert = montRevert -Montgomery.prototype.reduce = montReduce -Montgomery.prototype.mulTo = montMulTo -Montgomery.prototype.sqrTo = montSqrTo + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; -// (protected) true iff this is even -function bnpIsEven() { - return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 -} + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE - var r = new BigInteger(), - r2 = new BigInteger(), - g = z.convert(this), - i = nbits(e) - 1 - g.copyTo(r) - while (--i >= 0) { - z.sqrTo(r, r2) - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) - else { - var t = r - r = r2 - r2 = t - } - } - return z.revert(r) -} + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e, m) { - var z - if (e < 256 || m.isEven()) z = new Classic(m) - else z = new Montgomery(m) - return this.exp(e, z) -} - -// protected -proto.copyTo = bnpCopyTo -proto.fromInt = bnpFromInt -proto.fromString = bnpFromString -proto.clamp = bnpClamp -proto.dlShiftTo = bnpDLShiftTo -proto.drShiftTo = bnpDRShiftTo -proto.lShiftTo = bnpLShiftTo -proto.rShiftTo = bnpRShiftTo -proto.subTo = bnpSubTo -proto.multiplyTo = bnpMultiplyTo -proto.squareTo = bnpSquareTo -proto.divRemTo = bnpDivRemTo -proto.invDigit = bnpInvDigit -proto.isEven = bnpIsEven -proto.exp = bnpExp - -// public -proto.toString = bnToString -proto.negate = bnNegate -proto.abs = bnAbs -proto.compareTo = bnCompareTo -proto.bitLength = bnBitLength -proto.byteLength = bnByteLength -proto.mod = bnMod -proto.modPowInt = bnModPowInt - -// (public) -function bnClone() { - var r = new BigInteger() - this.copyTo(r) - return r -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; -// (public) return value as integer -function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV - else if (this.t == 0) return -1 - } else if (this.t == 1) return this[0] - else if (this.t == 0) return 0 - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] -} + if (it.opts.messages !== false) { + out += ' , message: \''; -// (public) return value as byte -function bnByteValue() { - return (this.t == 0) ? this.s : (this[0] << 24) >> 24 -} + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } -// (public) return value as short (assumes DB>=16) -function bnShortValue() { - return (this.t == 0) ? this.s : (this[0] << 16) >> 16 -} + out += '\' '; + } -// (protected) return x s.t. r^x < DV -function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)) -} + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -// (public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { - if (this.s < 0) return -1 - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 - else return 1 -} + out += ' } '; + } else { + out += ' {} '; + } -// (protected) convert to radix string -function bnpToRadix(b) { - if (b == null) b = 10 - if (this.signum() == 0 || b < 2 || b > 36) return "0" - var cs = this.chunkSize(b) - var a = Math.pow(b, cs) - var d = nbv(a), - y = new BigInteger(), - z = new BigInteger(), - r = "" - this.divRemTo(d, y, z) - while (y.signum() > 0) { - r = (a + z.intValue()) - .toString(b) - .substr(1) + r - y.divRemTo(d, y, z) - } - return z.intValue() - .toString(b) + r -} + var __err = out; + out = $$outStack.pop(); -// (protected) convert from radix string -function bnpFromRadix(s, b) { - var self = this - self.fromInt(0) - if (b == null) b = 10 - var cs = self.chunkSize(b) - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0 - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-" && self.signum() == 0) mi = true - continue - } - w = b * w + x - if (++j >= cs) { - self.dMultiply(d) - self.dAddOffset(w, 0) - j = 0 - w = 0 - } - } - if (j > 0) { - self.dMultiply(Math.pow(b, j)) - self.dAddOffset(w, 0) - } - if (mi) BigInteger.ZERO.subTo(self, self) -} + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -// (protected) alternate constructor -function bnpFromNumber(a, b, c) { - var self = this - if ("number" == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) self.fromInt(1) - else { - self.fromNumber(a, c) - if (!self.testBit(a - 1)) // force MSB set - self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) - if (self.isEven()) self.dAddOffset(1, 0); // force odd - while (!self.isProbablePrime(b)) { - self.dAddOffset(2, 0) - if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) + out += ' } else { '; } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7 - x.length = (a >> 3) + 1 - b.nextBytes(x) - if (t > 0) x[0] &= ((1 << t) - 1) - else x[0] = 0 - self.fromString(x, 256) - } -} - -// (public) convert to bigendian byte array -function bnToByteArray() { - var self = this - var i = self.t, - r = new Array() - r[0] = self.s - var p = self.DB - (i * self.DB) % 8, - d, k = 0 - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) - r[k++] = d | (self.s << (self.DB - p)) - while (i >= 0) { - if (p < 8) { - d = (self[i] & ((1 << p) - 1)) << (8 - p) - d |= self[--i] >> (p += self.DB - 8) - } else { - d = (self[i] >> (p -= 8)) & 0xff - if (p <= 0) { - p += self.DB - --i + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; '; } - } - if ((d & 0x80) != 0) d |= -256 - if (k === 0 && (self.s & 0x80) != (d & 0x80))++k - if (k > 0 || d != self.s) r[k++] = d - } - } - return r -} -function bnEquals(a) { - return (this.compareTo(a) == 0) -} + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; -function bnMin(a) { - return (this.compareTo(a) < 0) ? this : a -} + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } -function bnMax(a) { - return (this.compareTo(a) > 0) ? this : a -} + if ($isData) { + out += ' if (' + $vSchema + ' && !Array.isArray(' + $vSchema + ')) { var err = '; + /* istanbul ignore else */ -// (protected) r = this op a (bitwise) -function bnpBitwiseTo(a, op, r) { - var self = this - var i, f, m = Math.min(a.t, self.t) - for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) - if (a.t < self.t) { - f = a.s & self.DM - for (i = m; i < self.t; ++i) r[i] = op(self[i], f) - r.t = self.t - } else { - f = self.s & self.DM - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) - r.t = a.t - } - r.s = op(self.s, a.s) - r.clamp() -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; -// (public) this & a -function op_and(x, y) { - return x & y -} + if (it.opts.messages !== false) { + out += ' , message: \''; -function bnAnd(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_and, r) - return r -} + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } -// (public) this | a -function op_or(x, y) { - return x | y -} + out += '\' '; + } -function bnOr(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_or, r) - return r -} + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -// (public) this ^ a -function op_xor(x, y) { - return x ^ y -} + out += ' } '; + } else { + out += ' {} '; + } -function bnXor(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_xor, r) - return r -} + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + $vSchema + ' !== undefined) { '; + } -// (public) this & ~a -function op_andnot(x, y) { - return x & ~y -} + out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { if (' + $data + '[' + $vSchema + '[' + $i + ']] === undefined '; -function bnAndNot(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_andnot, r) - return r -} + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) '; + } -// (public) ~this -function bnNot() { - var r = new BigInteger() - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] - r.t = this.t - r.s = ~this.s - return r -} + out += ') { var err = '; + /* istanbul ignore else */ -// (public) this << n -function bnShiftLeft(n) { - var r = new BigInteger() - if (n < 0) this.rShiftTo(-n, r) - else this.lShiftTo(n, r) - return r -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; -// (public) this >> n -function bnShiftRight(n) { - var r = new BigInteger() - if (n < 0) this.lShiftTo(-n, r) - else this.rShiftTo(n, r) - return r -} + if (it.opts.messages !== false) { + out += ' , message: \''; -// return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { - if (x == 0) return -1 - var r = 0 - if ((x & 0xffff) == 0) { - x >>= 16 - r += 16 - } - if ((x & 0xff) == 0) { - x >>= 8 - r += 8 - } - if ((x & 0xf) == 0) { - x >>= 4 - r += 4 - } - if ((x & 3) == 0) { - x >>= 2 - r += 2 - } - if ((x & 1) == 0)++r - return r -} + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } -// (public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]) - if (this.s < 0) return this.t * this.DB - return -1 -} + out += '\' '; + } -// return number of 1 bits in x -function cbit(x) { - var r = 0 - while (x != 0) { - x &= x - 1 - ++r - } - return r -} + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -// (public) return number of set bits -function bnBitCount() { - var r = 0, - x = this.s & this.DM - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) - return r -} + out += ' } '; + } else { + out += ' {} '; + } -// (public) true iff nth bit is set -function bnTestBit(n) { - var j = Math.floor(n / this.DB) - if (j >= this.t) return (this.s != 0) - return ((this[j] & (1 << (n % this.DB))) != 0) -} + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; -// (protected) this op (1<>= self.DB - } - if (a.t < self.t) { - c += a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c += a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += a.s - } - r.s = (c < 0) ? -1 : 0 - if (c > 0) r[i++] = c - else if (c < -1) r[i++] = self.DV + c - r.t = i - r.clamp() -} + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } -// (public) this + a -function bnAdd(a) { - var r = new BigInteger() - this.addTo(a, r) - return r -} + out += ') { var err = '; + /* istanbul ignore else */ -// (public) this - a -function bnSubtract(a) { - var r = new BigInteger() - this.subTo(a, r) - return r -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; -// (public) this * a -function bnMultiply(a) { - var r = new BigInteger() - this.multiplyTo(a, r) - return r -} + if (it.opts.messages !== false) { + out += ' , message: \''; -// (public) this^2 -function bnSquare() { - var r = new BigInteger() - this.squareTo(r) - return r -} + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } -// (public) this / a -function bnDivide(a) { - var r = new BigInteger() - this.divRemTo(a, r, null) - return r -} + out += '\' '; + } -// (public) this % a -function bnRemainder(a) { - var r = new BigInteger() - this.divRemTo(a, null, r) - return r -} + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -// (public) [this/a,this%a] -function bnDivideAndRemainder(a) { - var q = new BigInteger(), - r = new BigInteger() - this.divRemTo(a, q, r) - return new Array(q, r) -} + out += ' } '; + } else { + out += ' {} '; + } -// (protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) - ++this.t - this.clamp() -} + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } -// (protected) this += n << w words, this >= 0 -function bnpDAddOffset(n, w) { - if (n == 0) return - while (this.t <= w) this[this.t++] = 0 - this[w] += n - while (this[w] >= this.DV) { - this[w] -= this.DV - if (++w >= this.t) this[this.t++] = 0 - ++this[w] + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; } -} -// A "null" reducer -function NullExp() {} - -function nNop(x) { - return x -} + return out; +}; -function nMulTo(x, y, r) { - x.multiplyTo(y, r) -} +},{}],71:[function(require,module,exports){ +'use strict'; -function nSqrTo(x, r) { - x.squareTo(r) -} +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } -NullExp.prototype.convert = nNop -NullExp.prototype.revert = nNop -NullExp.prototype.mulTo = nMulTo -NullExp.prototype.sqrTo = nSqrTo + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + $valid + '; if (' + $schemaValue + ' === false || ' + $schemaValue + ' === undefined) ' + $valid + ' = true; else if (typeof ' + $schemaValue + ' != \'boolean\') ' + $valid + ' = false; else { '; + } -// (public) this^e -function bnPow(e) { - return this.exp(e, new NullExp()) -} + out += ' var i = ' + $data + '.length , ' + $valid + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); -// (protected) r = lower n words of "this * a", a.t <= n -// "this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n) - r.s = 0; // assumes a,this >= 0 - r.t = i - while (i > 0) r[--i] = 0 - var j - for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) - r.clamp() -} + if (!$itemType || $itemType == 'object' || $itemType == 'array' || $typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + $data + '[i], ' + $data + '[j])) { ' + $valid + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + $data + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + it.util[$method]($itemType, 'item', true) + ') continue; '; -// (protected) r = "this * a" without lower n words, n > 0 -// "this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a, n, r) { - --n - var i = r.t = this.t + a.t - n - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0 - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) - r.clamp() - r.drShiftTo(1, r) -} + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } -// Barrett modular reduction -function Barrett(m) { - // setup Barrett - this.r2 = new BigInteger() - this.q3 = new BigInteger() - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) - this.mu = this.r2.divide(m) - this.m = m -} + out += ' if (typeof itemIndices[item] == \'number\') { ' + $valid + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } -function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) - else if (x.compareTo(this.m) < 0) return x - else { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r - } -} + out += ' } '; -function barrettRevert(x) { - return x -} + if ($isData) { + out += ' } '; + } -// x = x mod m (HAC 14.42) -function barrettReduce(x) { - var self = this - x.drShiftTo(self.m.t - 1, self.r2) - if (x.t > self.m.t + 1) { - x.t = self.m.t + 1 - x.clamp() - } - self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) - self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) - while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) - x.subTo(self.r2, x) - while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) -} + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -// r = x^2 mod m; x != r -function barrettSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'uniqueItems' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { i: i, j: j } '; -// r = x*y mod m; x,y != r -function barrettMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } -Barrett.prototype.convert = barrettConvert -Barrett.prototype.revert = barrettRevert -Barrett.prototype.reduce = barrettReduce -Barrett.prototype.mulTo = barrettMulTo -Barrett.prototype.sqrTo = barrettSqrTo + if (it.opts.verbose) { + out += ' , schema: '; -// (public) this^e % m (HAC 14.85) -function bnModPow(e, m) { - var i = e.bitLength(), - k, r = nbv(1), - z - if (i <= 0) return r - else if (i < 18) k = 1 - else if (i < 48) k = 3 - else if (i < 144) k = 4 - else if (i < 768) k = 5 - else k = 6 - if (i < 8) - z = new Classic(m) - else if (m.isEven()) - z = new Barrett(m) - else - z = new Montgomery(m) - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1 - g[1] = z.convert(this) - if (k > 1) { - var g2 = new BigInteger() - z.sqrTo(g[1], g2) - while (n <= km) { - g[n] = new BigInteger() - z.mulTo(g2, g[n - 2], g[n]) - n += 2 - } - } + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } - var j = e.t - 1, - w, is1 = true, - r2 = new BigInteger(), - t - i = nbits(e[j]) - 1 - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) - } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } - n = k - while ((w & 1) == 0) { - w >>= 1 - --n - } - if ((i -= n) < 0) { - i += this.DB - --j - } - if (is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r) - is1 = false + out += ' } '; } else { - while (n > 1) { - z.sqrTo(r, r2) - z.sqrTo(r2, r) - n -= 2 - } - if (n > 0) z.sqrTo(r, r2) - else { - t = r - r = r2 - r2 = t - } - z.mulTo(r2, g[w], r) + out += ' {} '; } - while (j >= 0 && (e[j] & (1 << i)) == 0) { - z.sqrTo(r, r2) - t = r - r = r2 - r2 = t - if (--i < 0) { - i = this.DB - 1 - --j - } - } - } - return z.revert(r) -} + var __err = out; + out = $$outStack.pop(); -// (public) gcd(this,a) (HAC 14.54) -function bnGCD(a) { - var x = (this.s < 0) ? this.negate() : this.clone() - var y = (a.s < 0) ? a.negate() : a.clone() - if (x.compareTo(y) < 0) { - var t = x - x = y - y = t - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit() - if (g < 0) return x - if (i < g) g = i - if (g > 0) { - x.rShiftTo(g, x) - y.rShiftTo(g, y) - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) - if (x.compareTo(y) >= 0) { - x.subTo(y, x) - x.rShiftTo(1, x) + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } } else { - y.subTo(x, y) - y.rShiftTo(1, y) + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - } - if (g > 0) y.lShiftTo(g, y) - return y -} -// (protected) this % n, n < 2^26 -function bnpModInt(n) { - if (n <= 0) return 0 - var d = this.DV % n, - r = (this.s < 0) ? n - 1 : 0 - if (this.t > 0) - if (d == 0) r = this[0] % n - else - for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n - return r -} + out += ' } '; -// (public) 1/this % m (HAC 14.61) -function bnModInverse(m) { - var ac = m.isEven() - if (this.signum() === 0) throw new Error('division by zero') - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO - var u = m.clone(), - v = this.clone() - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1) - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u) - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a) - b.subTo(m, b) - } - a.rShiftTo(1, a) - } else if (!b.isEven()) b.subTo(m, b) - b.rShiftTo(1, b) + if ($breakOnError) { + out += ' else { '; } - while (v.isEven()) { - v.rShiftTo(1, v) - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c) - d.subTo(m, d) - } - c.rShiftTo(1, c) - } else if (!d.isEven()) d.subTo(m, d) - d.rShiftTo(1, d) + } else { + if ($breakOnError) { + out += ' if (true) { '; } - if (u.compareTo(v) >= 0) { - u.subTo(v, u) - if (ac) a.subTo(c, a) - b.subTo(d, b) - } else { - v.subTo(u, v) - if (ac) c.subTo(a, c) - d.subTo(b, d) - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO - while (d.compareTo(m) >= 0) d.subTo(m, d) - while (d.signum() < 0) d.addTo(m, d) - return d -} - -var lowprimes = [ - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, - 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, - 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, - 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, - 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, - 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 -] + } -var lplim = (1 << 26) / lowprimes[lowprimes.length - 1] + return out; +}; -// (public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { - var i, x = this.abs() - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true - return false - } - if (x.isEven()) return false - i = 1 - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1 - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] - m = x.modInt(m) - while (i < j) if (m % lowprimes[i++] == 0) return false - } - return x.millerRabin(t) -} +},{}],72:[function(require,module,exports){ +'use strict'; -// (protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE) - var k = n1.getLowestSetBit() - if (k <= 0) return false - var r = n1.shiftRight(k) - t = (t + 1) >> 1 - if (t > lowprimes.length) t = lowprimes.length - var a = new BigInteger(null) - var j, bases = [] - for (var i = 0; i < t; ++i) { - for (;;) { - j = lowprimes[Math.floor(Math.random() * lowprimes.length)] - if (bases.indexOf(j) == -1) break - } - bases.push(j) - a.fromInt(j) - var y = a.modPow(r, this) - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1 - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this) - if (y.compareTo(BigInteger.ONE) == 0) return false - } - if (y.compareTo(n1) != 0) return false - } - } - return true -} - -// protected -proto.chunkSize = bnpChunkSize -proto.toRadix = bnpToRadix -proto.fromRadix = bnpFromRadix -proto.fromNumber = bnpFromNumber -proto.bitwiseTo = bnpBitwiseTo -proto.changeBit = bnpChangeBit -proto.addTo = bnpAddTo -proto.dMultiply = bnpDMultiply -proto.dAddOffset = bnpDAddOffset -proto.multiplyLowerTo = bnpMultiplyLowerTo -proto.multiplyUpperTo = bnpMultiplyUpperTo -proto.modInt = bnpModInt -proto.millerRabin = bnpMillerRabin - -// public -proto.clone = bnClone -proto.intValue = bnIntValue -proto.byteValue = bnByteValue -proto.shortValue = bnShortValue -proto.signum = bnSigNum -proto.toByteArray = bnToByteArray -proto.equals = bnEquals -proto.min = bnMin -proto.max = bnMax -proto.and = bnAnd -proto.or = bnOr -proto.xor = bnXor -proto.andNot = bnAndNot -proto.not = bnNot -proto.shiftLeft = bnShiftLeft -proto.shiftRight = bnShiftRight -proto.getLowestSetBit = bnGetLowestSetBit -proto.bitCount = bnBitCount -proto.testBit = bnTestBit -proto.setBit = bnSetBit -proto.clearBit = bnClearBit -proto.flipBit = bnFlipBit -proto.add = bnAdd -proto.subtract = bnSubtract -proto.multiply = bnMultiply -proto.divide = bnDivide -proto.remainder = bnRemainder -proto.divideAndRemainder = bnDivideAndRemainder -proto.modPow = bnModPow -proto.modInverse = bnModInverse -proto.pow = bnPow -proto.gcd = bnGCD -proto.isProbablePrime = bnIsProbablePrime - -// JSBN-specific extension -proto.square = bnSquare - -// constants -BigInteger.ZERO = nbv(0) -BigInteger.ONE = nbv(1) -BigInteger.valueOf = nbv - -module.exports = BigInteger - -},{"../package.json":78}],76:[function(require,module,exports){ -// FIXME: Kind of a weird way to throw exceptions, consider removing -var assert = require('assert') -var BigInteger = require('./bigi') - -/** - * Turns a byte array into a big integer. - * - * This function will interpret a byte array as a big integer in big - * endian notation. - */ -BigInteger.fromByteArrayUnsigned = function(byteArray) { - // BigInteger expects a DER integer conformant byte array - if (byteArray[0] & 0x80) { - return new BigInteger([0].concat(byteArray)) - } - - return new BigInteger(byteArray) -} - -/** - * Returns a byte array representation of the big integer. - * - * This returns the absolute of the contained value in big endian - * form. A value of zero results in an empty array. - */ -BigInteger.prototype.toByteArrayUnsigned = function() { - var byteArray = this.toByteArray() - return byteArray[0] === 0 ? byteArray.slice(1) : byteArray -} - -BigInteger.fromDERInteger = function(byteArray) { - return new BigInteger(byteArray) -} +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; -/* - * Converts BigInteger to a DER integer representation. - * - * The format for this value uses the most significant bit as a sign - * bit. If the most significant bit is already set and the integer is - * positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 -*/ -BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); -BigInteger.fromBuffer = function(buffer) { - // BigInteger expects a DER integer conformant byte array - if (buffer[0] & 0x80) { - var byteArray = Array.prototype.slice.call(buffer) + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); - return new BigInteger([0].concat(byteArray)) + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);else throw new Error($keywordsMsg); + } } - return new BigInteger(buffer) -} + if (it.isTop) { + out += ' var validate = '; -BigInteger.fromHex = function(hex) { - if (hex === '') return BigInteger.ZERO + if ($async) { + it.async = true; + out += 'async '; + } - assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string') - assert.equal(hex.length % 2, 0, 'Incomplete hex') - return new BigInteger(hex, 16) -} + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; -BigInteger.prototype.toBuffer = function(size) { - var byteArray = this.toByteArrayUnsigned() - var zeros = [] + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } - var padding = size - byteArray.length - while (zeros.length < padding) zeros.push(0) + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; - return new Buffer(zeros.concat(byteArray)) -} + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + $valid + ' = false; '; + } -BigInteger.prototype.toHex = function(size) { - return this.toBuffer(size).toString('hex') -} + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -},{"./bigi":75,"assert":undefined}],77:[function(require,module,exports){ -var BigInteger = require('./bigi') + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; -//addons -require('./convert') + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } -module.exports = BigInteger -},{"./bigi":75,"./convert":76}],78:[function(require,module,exports){ -module.exports={ - "name": "bigi", - "version": "1.4.2", - "description": "Big integers.", - "keywords": [ - "cryptography", - "math", - "bitcoin", - "arbitrary", - "precision", - "arithmetic", - "big", - "integer", - "int", - "number", - "biginteger", - "bigint", - "bignumber", - "decimal", - "float" - ], - "devDependencies": { - "coveralls": "^2.11.2", - "istanbul": "^0.3.5", - "jshint": "^2.5.1", - "mocha": "^2.1.0", - "mochify": "^2.1.0" - }, - "repository": { - "url": "https://github.com/cryptocoinjs/bigi", - "type": "git" - }, - "main": "./lib/index.js", - "scripts": { - "browser-test": "./node_modules/.bin/mochify --wd -R spec", - "test": "./node_modules/.bin/_mocha -- test/*.js", - "jshint": "./node_modules/.bin/jshint --config jshint.json lib/*.js ; true", - "unit": "./node_modules/.bin/mocha", - "coverage": "./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js", - "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info" - }, - "dependencies": {}, - "testling": { - "files": "test/*.js", - "harness": "mocha", - "browsers": [ - "ie/9..latest", - "firefox/latest", - "chrome/latest", - "safari/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } -,"_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz" -,"_integrity": "sha1-nGZalfiLiwj8Bc/XMfVhhZ1yWCU=" -,"_from": "bigi@1.4.2" -} -},{}],79:[function(require,module,exports){ -;(function (globalObject) { - 'use strict'; - -/* - * bignumber.js v6.0.0 - * A JavaScript library for arbitrary-precision arithmetic. - * https://github.com/MikeMcl/bignumber.js - * Copyright (c) 2018 Michael Mclaughlin - * MIT Licensed. - * - * BigNumber.prototype methods | BigNumber methods - * | - * absoluteValue abs | clone - * comparedTo | config set - * decimalPlaces dp | DECIMAL_PLACES - * dividedBy div | ROUNDING_MODE - * dividedToIntegerBy idiv | EXPONENTIAL_AT - * exponentiatedBy pow | RANGE - * integerValue | CRYPTO - * isEqualTo eq | MODULO_MODE - * isFinite | POW_PRECISION - * isGreaterThan gt | FORMAT - * isGreaterThanOrEqualTo gte | ALPHABET - * isInteger | isBigNumber - * isLessThan lt | maximum max - * isLessThanOrEqualTo lte | minimum min - * isNaN | random - * isNegative | - * isPositive | - * isZero | - * minus | - * modulo mod | - * multipliedBy times | - * negated | - * plus | - * precision sd | - * shiftedBy | - * squareRoot sqrt | - * toExponential | - * toFixed | - * toFormat | - * toFraction | - * toJSON | - * toNumber | - * toPrecision | - * toString | - * valueOf | - * - */ - - - var BigNumber, - isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, - - mathceil = Math.ceil, - mathfloor = Math.floor, - - bignumberError = '[BigNumber Error] ', - tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', - - BASE = 1e14, - LOG_BASE = 14, - MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 - // MAX_INT32 = 0x7fffffff, // 2^31 - 1 - POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], - SQRT_BASE = 1e7, - - // EDITABLE - // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and - // the arguments to toExponential, toFixed, toFormat, and toPrecision. - MAX = 1E9; // 0 to MAX_INT32 - - - /* - * Create and return a BigNumber constructor. - */ - function clone(configObject) { - var div, convertBase, parseNumeric, - P = BigNumber.prototype, - ONE = new BigNumber(1), - - - //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- - - - // The default values below must be integers within the inclusive ranges stated. - // The values can also be changed at run-time using BigNumber.set. - - // The maximum number of decimal places for operations involving division. - DECIMAL_PLACES = 20, // 0 to MAX - - // The rounding mode used when rounding to the above decimal places, and when using - // toExponential, toFixed, toFormat and toPrecision, and round (default value). - // UP 0 Away from zero. - // DOWN 1 Towards zero. - // CEIL 2 Towards +Infinity. - // FLOOR 3 Towards -Infinity. - // HALF_UP 4 Towards nearest neighbour. If equidistant, up. - // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. - // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. - // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. - // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. - ROUNDING_MODE = 4, // 0 to 8 - - // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] - - // The exponent value at and beneath which toString returns exponential notation. - // Number type: -7 - TO_EXP_NEG = -7, // 0 to -MAX - - // The exponent value at and above which toString returns exponential notation. - // Number type: 21 - TO_EXP_POS = 21, // 0 to MAX - - // RANGE : [MIN_EXP, MAX_EXP] - - // The minimum exponent value, beneath which underflow to zero occurs. - // Number type: -324 (5e-324) - MIN_EXP = -1e7, // -1 to -MAX - - // The maximum exponent value, above which overflow to Infinity occurs. - // Number type: 308 (1.7976931348623157e+308) - // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. - MAX_EXP = 1e7, // 1 to MAX - - // Whether to use cryptographically-secure random number generation, if available. - CRYPTO = false, // true or false - - // The modulo mode used when calculating the modulus: a mod n. - // The quotient (q = a / n) is calculated according to the corresponding rounding mode. - // The remainder (r) is calculated as: r = a - n * q. - // - // UP 0 The remainder is positive if the dividend is negative, else is negative. - // DOWN 1 The remainder has the same sign as the dividend. - // This modulo mode is commonly known as 'truncated division' and is - // equivalent to (a % n) in JavaScript. - // FLOOR 3 The remainder has the same sign as the divisor (Python %). - // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. - // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). - // The remainder is always positive. - // - // The truncated division, floored division, Euclidian division and IEEE 754 remainder - // modes are commonly used for the modulus operation. - // Although the other rounding modes can also be used, they may not give useful results. - MODULO_MODE = 1, // 0 to 9 - - // The maximum number of significant digits of the result of the exponentiatedBy operation. - // If POW_PRECISION is 0, there will be unlimited significant digits. - POW_PRECISION = 0, // 0 to MAX - - // The format specification used by the BigNumber.prototype.toFormat method. - FORMAT = { - decimalSeparator: '.', - groupSeparator: ',', - groupSize: 3, - secondaryGroupSize: 0, - fractionGroupSeparator: '\xA0', // non-breaking space - fractionGroupSize: 0 - }, - - // The alphabet used for base conversion. - // It must be at least 2 characters long, with no '.' or repeated character. - // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' - ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; - - - //------------------------------------------------------------------------------------------ - - - // CONSTRUCTOR - - - /* - * The BigNumber constructor and exported function. - * Create and return a new instance of a BigNumber object. - * - * n {number|string|BigNumber} A numeric value. - * [b] {number} The base of n. Integer, 2 to ALPHABET.length inclusive. - */ - function BigNumber( n, b ) { - var alphabet, c, e, i, isNum, len, str, - x = this; - - // Enable constructor usage without new. - if ( !( x instanceof BigNumber ) ) { - - // Don't throw on constructor call without new (#81). - // '[BigNumber Error] Constructor call without new: {n}' - //throw Error( bignumberError + ' Constructor call without new: ' + n ); - return new BigNumber( n, b ); - } - - if ( b == null ) { - - // Duplicate. - if ( n instanceof BigNumber ) { - x.s = n.s; - x.e = n.e; - x.c = ( n = n.c ) ? n.slice() : n; - return; - } - - isNum = typeof n == 'number'; - - if ( isNum && n * 0 == 0 ) { - - // Use `1 / n` to handle minus zero also. - x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; - - // Faster path for integers. - if ( n === ~~n ) { - for ( e = 0, i = n; i >= 10; i /= 10, e++ ); - x.e = e; - x.c = [n]; - return; - } - - str = n + ''; - } else { - if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, isNum ); - x.s = str.charCodeAt(0) == 45 ? ( str = str.slice(1), -1 ) : 1; - } - - } else { - - // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' - intCheck( b, 2, ALPHABET.length, 'Base' ); - str = n + ''; - - // Allow exponential notation to be used with base 10 argument, while - // also rounding to DECIMAL_PLACES as with other bases. - if ( b == 10 ) { - x = new BigNumber( n instanceof BigNumber ? n : str ); - return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); - } - - isNum = typeof n == 'number'; - - if (isNum) { - - // Avoid potential interpretation of Infinity and NaN as base 44+ values. - if ( n * 0 != 0 ) return parseNumeric( x, str, isNum, b ); - - x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; - - // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' - if ( str.replace( /^0\.0*|\./, '' ).length > 15 ) { - throw Error - ( tooManyDigits + n ); - } - - // Prevent later check for length on converted number. - isNum = false; - } else { - x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; - - // Allow e.g. hexadecimal 'FF' as well as 'ff'. - if ( b > 10 && b < 37 ) str = str.toLowerCase(); - } - - alphabet = ALPHABET.slice( 0, b ); - e = i = 0; - - // Check that str is a valid base b number. - // Don't use RegExp so alphabet can contain special characters. - for ( len = str.length; i < len; i++ ) { - if ( alphabet.indexOf( c = str.charAt(i) ) < 0 ) { - if ( c == '.' ) { - - // If '.' is not the first character and it has not be found before. - if ( i > e ) { - e = len; - continue; - } - } - - return parseNumeric( x, n + '', isNum, b ); - } - } - - str = convertBase( str, b, 10, x.s ); - } - - // Decimal point? - if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); - - // Exponential form? - if ( ( i = str.search( /e/i ) ) > 0 ) { - - // Determine exponent. - if ( e < 0 ) e = i; - e += +str.slice( i + 1 ); - str = str.substring( 0, i ); - } else if ( e < 0 ) { - - // Integer. - e = str.length; - } - - // Determine leading zeros. - for ( i = 0; str.charCodeAt(i) === 48; i++ ); - - // Determine trailing zeros. - for ( len = str.length; str.charCodeAt(--len) === 48; ); - str = str.slice( i, len + 1 ); - - if (str) { - len = str.length; - - // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' - if ( isNum && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) { - throw Error - ( tooManyDigits + ( x.s * n ) ); - } - - e = e - i - 1; - - // Overflow? - if ( e > MAX_EXP ) { - - // Infinity. - x.c = x.e = null; - - // Underflow? - } else if ( e < MIN_EXP ) { - - // Zero. - x.c = [ x.e = 0 ]; - } else { - x.e = e; - x.c = []; - - // Transform base - - // e is the base 10 exponent. - // i is where to slice str to get the first element of the coefficient array. - i = ( e + 1 ) % LOG_BASE; - if ( e < 0 ) i += LOG_BASE; - - if ( i < len ) { - if (i) x.c.push( +str.slice( 0, i ) ); - - for ( len -= LOG_BASE; i < len; ) { - x.c.push( +str.slice( i, i += LOG_BASE ) ); - } - - str = str.slice(i); - i = LOG_BASE - str.length; - } else { - i -= len; - } - - for ( ; i--; str += '0' ); - x.c.push( +str ); - } - } else { - - // Zero. - x.c = [ x.e = 0 ]; - } - } - - - // CONSTRUCTOR PROPERTIES - - - BigNumber.clone = clone; - - BigNumber.ROUND_UP = 0; - BigNumber.ROUND_DOWN = 1; - BigNumber.ROUND_CEIL = 2; - BigNumber.ROUND_FLOOR = 3; - BigNumber.ROUND_HALF_UP = 4; - BigNumber.ROUND_HALF_DOWN = 5; - BigNumber.ROUND_HALF_EVEN = 6; - BigNumber.ROUND_HALF_CEIL = 7; - BigNumber.ROUND_HALF_FLOOR = 8; - BigNumber.EUCLID = 9; - - - /* - * Configure infrequently-changing library-wide settings. - * - * Accept an object with the following optional properties (if the value of a property is - * a number, it must be an integer within the inclusive range stated): - * - * DECIMAL_PLACES {number} 0 to MAX - * ROUNDING_MODE {number} 0 to 8 - * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] - * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] - * CRYPTO {boolean} true or false - * MODULO_MODE {number} 0 to 9 - * POW_PRECISION {number} 0 to MAX - * ALPHABET {string} A string of two or more unique characters, and not - * containing '.'. The empty string, null or undefined - * resets the alphabet to its default value. - * FORMAT {object} An object with some of the following properties: - * decimalSeparator {string} - * groupSeparator {string} - * groupSize {number} - * secondaryGroupSize {number} - * fractionGroupSeparator {string} - * fractionGroupSize {number} - * - * (The values assigned to the above FORMAT object properties are not checked for validity.) - * - * E.g. - * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) - * - * Ignore properties/parameters set to null or undefined, except for ALPHABET. - * - * Return an object with the properties current values. - */ - BigNumber.config = BigNumber.set = function (obj) { - var p, v; - - if ( obj != null ) { - - if ( typeof obj == 'object' ) { - - // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. - // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' - if ( obj.hasOwnProperty( p = 'DECIMAL_PLACES' ) ) { - v = obj[p]; - intCheck( v, 0, MAX, p ); - DECIMAL_PLACES = v; - } - - // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. - // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' - if ( obj.hasOwnProperty( p = 'ROUNDING_MODE' ) ) { - v = obj[p]; - intCheck( v, 0, 8, p ); - ROUNDING_MODE = v; - } - - // EXPONENTIAL_AT {number|number[]} - // Integer, -MAX to MAX inclusive or - // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. - // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' - if ( obj.hasOwnProperty( p = 'EXPONENTIAL_AT' ) ) { - v = obj[p]; - if ( isArray(v) ) { - intCheck( v[0], -MAX, 0, p ); - intCheck( v[1], 0, MAX, p ); - TO_EXP_NEG = v[0]; - TO_EXP_POS = v[1]; - } else { - intCheck( v, -MAX, MAX, p ); - TO_EXP_NEG = -( TO_EXP_POS = v < 0 ? -v : v ); - } - } - - // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or - // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. - // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' - if ( obj.hasOwnProperty( p = 'RANGE' ) ) { - v = obj[p]; - if ( isArray(v) ) { - intCheck( v[0], -MAX, -1, p ); - intCheck( v[1], 1, MAX, p ); - MIN_EXP = v[0]; - MAX_EXP = v[1]; - } else { - intCheck( v, -MAX, MAX, p ); - if (v) { - MIN_EXP = -( MAX_EXP = v < 0 ? -v : v ); - } else { - throw Error - ( bignumberError + p + ' cannot be zero: ' + v ); - } - } - } - - // CRYPTO {boolean} true or false. - // '[BigNumber Error] CRYPTO not true or false: {v}' - // '[BigNumber Error] crypto unavailable' - if ( obj.hasOwnProperty( p = 'CRYPTO' ) ) { - v = obj[p]; - if ( v === !!v ) { - if (v) { - if ( typeof crypto != 'undefined' && crypto && - (crypto.getRandomValues || crypto.randomBytes) ) { - CRYPTO = v; - } else { - CRYPTO = !v; - throw Error - ( bignumberError + 'crypto unavailable' ); - } - } else { - CRYPTO = v; - } - } else { - throw Error - ( bignumberError + p + ' not true or false: ' + v ); - } - } - - // MODULO_MODE {number} Integer, 0 to 9 inclusive. - // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' - if ( obj.hasOwnProperty( p = 'MODULO_MODE' ) ) { - v = obj[p]; - intCheck( v, 0, 9, p ); - MODULO_MODE = v; - } - - // POW_PRECISION {number} Integer, 0 to MAX inclusive. - // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' - if ( obj.hasOwnProperty( p = 'POW_PRECISION' ) ) { - v = obj[p]; - intCheck( v, 0, MAX, p ); - POW_PRECISION = v; - } - - // FORMAT {object} - // '[BigNumber Error] FORMAT not an object: {v}' - if ( obj.hasOwnProperty( p = 'FORMAT' ) ) { - v = obj[p]; - if ( typeof v == 'object' ) FORMAT = v; - else throw Error - ( bignumberError + p + ' not an object: ' + v ); - } - - // ALPHABET {string} - // '[BigNumber Error] ALPHABET invalid: {v}' - if ( obj.hasOwnProperty( p = 'ALPHABET' ) ) { - v = obj[p]; - - // Disallow if only one character, or contains '.' or a repeated character. - if ( typeof v == 'string' && !/^.$|\.|(.).*\1/.test(v) ) { - ALPHABET = v; - } else { - throw Error - ( bignumberError + p + ' invalid: ' + v ); - } - } - - } else { - - // '[BigNumber Error] Object expected: {v}' - throw Error - ( bignumberError + 'Object expected: ' + obj ); - } - } - - return { - DECIMAL_PLACES: DECIMAL_PLACES, - ROUNDING_MODE: ROUNDING_MODE, - EXPONENTIAL_AT: [ TO_EXP_NEG, TO_EXP_POS ], - RANGE: [ MIN_EXP, MAX_EXP ], - CRYPTO: CRYPTO, - MODULO_MODE: MODULO_MODE, - POW_PRECISION: POW_PRECISION, - FORMAT: FORMAT, - ALPHABET: ALPHABET - }; - }; - - - /* - * Return true if v is a BigNumber instance, otherwise return false. - * - * v {any} - */ - BigNumber.isBigNumber = function (v) { - return v instanceof BigNumber || v && v._isBigNumber === true || false; - }; - - - /* - * Return a new BigNumber whose value is the maximum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.maximum = BigNumber.max = function () { - return maxOrMin( arguments, P.lt ); - }; - - - /* - * Return a new BigNumber whose value is the minimum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.minimum = BigNumber.min = function () { - return maxOrMin( arguments, P.gt ); - }; - - - /* - * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, - * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing - * zeros are produced). - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' - * '[BigNumber Error] crypto unavailable' - */ - BigNumber.random = (function () { - var pow2_53 = 0x20000000000000; - - // Return a 53 bit integer n, where 0 <= n < 9007199254740992. - // Check if Math.random() produces more than 32 bits of randomness. - // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. - // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. - var random53bitInt = (Math.random() * pow2_53) & 0x1fffff - ? function () { return mathfloor( Math.random() * pow2_53 ); } - : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + - (Math.random() * 0x800000 | 0); }; - - return function (dp) { - var a, b, e, k, v, - i = 0, - c = [], - rand = new BigNumber(ONE); - - if ( dp == null ) dp = DECIMAL_PLACES; - else intCheck( dp, 0, MAX ); - - k = mathceil( dp / LOG_BASE ); - - if (CRYPTO) { - - // Browsers supporting crypto.getRandomValues. - if (crypto.getRandomValues) { - - a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); - - for ( ; i < k; ) { - - // 53 bits: - // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) - // 11111 11111111 11111111 11111111 11100000 00000000 00000000 - // ((Math.pow(2, 32) - 1) >>> 11).toString(2) - // 11111 11111111 11111111 - // 0x20000 is 2^21. - v = a[i] * 0x20000 + (a[i + 1] >>> 11); - - // Rejection sampling: - // 0 <= v < 9007199254740992 - // Probability that v >= 9e15, is - // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 - if ( v >= 9e15 ) { - b = crypto.getRandomValues( new Uint32Array(2) ); - a[i] = b[0]; - a[i + 1] = b[1]; - } else { - - // 0 <= v <= 8999999999999999 - // 0 <= (v % 1e14) <= 99999999999999 - c.push( v % 1e14 ); - i += 2; - } - } - i = k / 2; - - // Node.js supporting crypto.randomBytes. - } else if (crypto.randomBytes) { - - // buffer - a = crypto.randomBytes( k *= 7 ); - - for ( ; i < k; ) { - - // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 - // 0x100000000 is 2^32, 0x1000000 is 2^24 - // 11111 11111111 11111111 11111111 11111111 11111111 11111111 - // 0 <= v < 9007199254740992 - v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + - ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + - ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; - - if ( v >= 9e15 ) { - crypto.randomBytes(7).copy( a, i ); - } else { - - // 0 <= (v % 1e14) <= 99999999999999 - c.push( v % 1e14 ); - i += 7; - } - } - i = k / 7; - } else { - CRYPTO = false; - throw Error - ( bignumberError + 'crypto unavailable' ); - } - } - - // Use Math.random. - if (!CRYPTO) { - - for ( ; i < k; ) { - v = random53bitInt(); - if ( v < 9e15 ) c[i++] = v % 1e14; - } - } - - k = c[--i]; - dp %= LOG_BASE; - - // Convert trailing digits to zeros according to dp. - if ( k && dp ) { - v = POWS_TEN[LOG_BASE - dp]; - c[i] = mathfloor( k / v ) * v; - } - - // Remove trailing elements which are zero. - for ( ; c[i] === 0; c.pop(), i-- ); - - // Zero? - if ( i < 0 ) { - c = [ e = 0 ]; - } else { - - // Remove leading elements which are zero and adjust exponent accordingly. - for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); - - // Count the digits of the first element of c to determine leading zeros, and... - for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); - - // adjust the exponent accordingly. - if ( i < LOG_BASE ) e -= LOG_BASE - i; - } - - rand.e = e; - rand.c = c; - return rand; - }; - })(); - - - // PRIVATE FUNCTIONS - - - // Called by BigNumber and BigNumber.prototype.toString. - convertBase = ( function () { - var decimal = '0123456789'; - - /* - * Convert string of baseIn to an array of numbers of baseOut. - * Eg. toBaseOut('255', 10, 16) returns [15, 15]. - * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. - */ - function toBaseOut( str, baseIn, baseOut, alphabet ) { - var j, - arr = [0], - arrL, - i = 0, - len = str.length; - - for ( ; i < len; ) { - for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); - - arr[0] += alphabet.indexOf( str.charAt( i++ ) ); - - for ( j = 0; j < arr.length; j++ ) { - - if ( arr[j] > baseOut - 1 ) { - if ( arr[j + 1] == null ) arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - - return arr.reverse(); - } - - // Convert a numeric string of baseIn to a numeric string of baseOut. - // If the caller is toString, we are converting from base 10 to baseOut. - // If the caller is BigNumber, we are converting from baseIn to base 10. - return function ( str, baseIn, baseOut, sign, callerIsToString ) { - var alphabet, d, e, k, r, x, xc, y, - i = str.indexOf( '.' ), - dp = DECIMAL_PLACES, - rm = ROUNDING_MODE; - - // Non-integer. - if ( i >= 0 ) { - k = POW_PRECISION; - - // Unlimited precision. - POW_PRECISION = 0; - str = str.replace( '.', '' ); - y = new BigNumber(baseIn); - x = y.pow( str.length - i ); - POW_PRECISION = k; - - // Convert str as if an integer, then restore the fraction part by dividing the - // result by its base raised to a power. - - y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e, '0' ), - 10, baseOut, decimal ); - y.e = y.c.length; - } - - // Convert the number as integer. - - xc = toBaseOut( str, baseIn, baseOut, callerIsToString - ? ( alphabet = ALPHABET, decimal ) - : ( alphabet = decimal, ALPHABET ) ); - - - // xc now represents str as an integer and converted to baseOut. e is the exponent. - e = k = xc.length; - - // Remove trailing zeros. - for ( ; xc[--k] == 0; xc.pop() ); - - // Zero? - if ( !xc[0] ) return alphabet.charAt(0); - - // Does str represent an integer? If so, no need for the division. - if ( i < 0 ) { - --e; - } else { - x.c = xc; - x.e = e; - - // The sign is needed for correct rounding. - x.s = sign; - x = div( x, y, dp, rm, baseOut ); - xc = x.c; - r = x.r; - e = x.e; - } - - // xc now represents str converted to baseOut. - - // THe index of the rounding digit. - d = e + dp + 1; - - // The rounding digit: the digit to the right of the digit that may be rounded up. - i = xc[d]; - - // Look at the rounding digits and mode to determine whether to round up. - - k = baseOut / 2; - r = r || d < 0 || xc[d + 1] != null; - - r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) - : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || - rm == ( x.s < 0 ? 8 : 7 ) ); - - // If the index of the rounding digit is not greater than zero, or xc represents - // zero, then the result of the base conversion is zero or, if rounding up, a value - // such as 0.00001. - if ( d < 1 || !xc[0] ) { - - // 1^-dp or 0 - str = r ? toFixedPoint( alphabet.charAt(1), -dp, alphabet.charAt(0) ) - : alphabet.charAt(0); - } else { - - // Truncate xc to the required number of decimal places. - xc.length = d; - - // Round up? - if (r) { - - // Rounding up may mean the previous digit has to be rounded up and so on. - for ( --baseOut; ++xc[--d] > baseOut; ) { - xc[d] = 0; - - if ( !d ) { - ++e; - xc = [1].concat(xc); - } - } - } - - // Determine trailing zeros. - for ( k = xc.length; !xc[--k]; ); - - // E.g. [4, 11, 15] becomes 4bf. - for ( i = 0, str = ''; i <= k; str += alphabet.charAt( xc[i++] ) ); - - // Add leading zeros, decimal point and trailing zeros as required. - str = toFixedPoint( str, e, alphabet.charAt(0) ); - } - - // The caller will add the sign. - return str; - }; - })(); - - - // Perform division in the specified base. Called by div and convertBase. - div = (function () { - - // Assume non-zero x and k. - function multiply( x, k, base ) { - var m, temp, xlo, xhi, - carry = 0, - i = x.length, - klo = k % SQRT_BASE, - khi = k / SQRT_BASE | 0; - - for ( x = x.slice(); i--; ) { - xlo = x[i] % SQRT_BASE; - xhi = x[i] / SQRT_BASE | 0; - m = khi * xlo + xhi * klo; - temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; - carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; - x[i] = temp % base; - } - - if (carry) x = [carry].concat(x); - - return x; - } - - function compare( a, b, aL, bL ) { - var i, cmp; - - if ( aL != bL ) { - cmp = aL > bL ? 1 : -1; - } else { - - for ( i = cmp = 0; i < aL; i++ ) { - - if ( a[i] != b[i] ) { - cmp = a[i] > b[i] ? 1 : -1; - break; - } - } - } - return cmp; - } - - function subtract( a, b, aL, base ) { - var i = 0; - - // Subtract b from a. - for ( ; aL--; ) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - - // Remove leading zeros. - for ( ; !a[0] && a.length > 1; a.splice(0, 1) ); - } - - // x: dividend, y: divisor. - return function ( x, y, dp, rm, base ) { - var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, - yL, yz, - s = x.s == y.s ? 1 : -1, - xc = x.c, - yc = y.c; - - // Either NaN, Infinity or 0? - if ( !xc || !xc[0] || !yc || !yc[0] ) { - - return new BigNumber( - - // Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : - - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s * 0 : s / 0 - ); - } - - q = new BigNumber(s); - qc = q.c = []; - e = x.e - y.e; - s = dp + e + 1; - - if ( !base ) { - base = BASE; - e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); - s = s / LOG_BASE | 0; - } - - // Result exponent may be one less then the current value of e. - // The coefficients of the BigNumbers from convertBase may have trailing zeros. - for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); - - if ( yc[i] > ( xc[i] || 0 ) ) e--; - - if ( s < 0 ) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i = 0; - s += 2; - - // Normalise xc and yc so highest order digit of yc is >= base / 2. - - n = mathfloor( base / ( yc[0] + 1 ) ); - - // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. - // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { - if ( n > 1 ) { - yc = multiply( yc, n, base ); - xc = multiply( xc, n, base ); - yL = yc.length; - xL = xc.length; - } - - xi = yL; - rem = xc.slice( 0, yL ); - remL = rem.length; - - // Add zeros to make remainder as long as divisor. - for ( ; remL < yL; rem[remL++] = 0 ); - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if ( yc[1] >= base / 2 ) yc0++; - // Not necessary, but to prevent trial digit n > base, when using base 3. - // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; - - do { - n = 0; - - // Compare divisor and remainder. - cmp = compare( yc, rem, yL, remL ); - - // If divisor < remainder. - if ( cmp < 0 ) { - - // Calculate trial digit, n. - - rem0 = rem[0]; - if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); - - // n is how many times the divisor goes into the current remainder. - n = mathfloor( rem0 / yc0 ); - - // Algorithm: - // 1. product = divisor * trial digit (n) - // 2. if product > remainder: product -= divisor, n-- - // 3. remainder -= product - // 4. if product was < remainder at 2: - // 5. compare new remainder and divisor - // 6. If remainder > divisor: remainder -= divisor, n++ - - if ( n > 1 ) { - - // n may be > base only when base is 3. - if (n >= base) n = base - 1; - - // product = divisor * trial digit. - prod = multiply( yc, n, base ); - prodL = prod.length; - remL = rem.length; - - // Compare product and remainder. - // If product > remainder. - // Trial digit n too high. - // n is 1 too high about 5% of the time, and is not known to have - // ever been more than 1 too high. - while ( compare( prod, rem, prodL, remL ) == 1 ) { - n--; - - // Subtract divisor from product. - subtract( prod, yL < prodL ? yz : yc, prodL, base ); - prodL = prod.length; - cmp = 1; - } - } else { - - // n is 0 or 1, cmp is -1. - // If n is 0, there is no need to compare yc and rem again below, - // so change cmp to 1 to avoid it. - // If n is 1, leave cmp as -1, so yc and rem are compared again. - if ( n == 0 ) { - - // divisor < remainder, so n must be at least 1. - cmp = n = 1; - } - - // product = divisor - prod = yc.slice(); - prodL = prod.length; - } - - if ( prodL < remL ) prod = [0].concat(prod); - - // Subtract product from remainder. - subtract( rem, prod, remL, base ); - remL = rem.length; - - // If product was < remainder. - if ( cmp == -1 ) { - - // Compare divisor and new remainder. - // If divisor < new remainder, subtract divisor from remainder. - // Trial digit n too low. - // n is 1 too low about 5% of the time, and very rarely 2 too low. - while ( compare( yc, rem, yL, remL ) < 1 ) { - n++; - - // Subtract divisor from remainder. - subtract( rem, yL < remL ? yz : yc, remL, base ); - remL = rem.length; - } - } - } else if ( cmp === 0 ) { - n++; - rem = [0]; - } // else cmp === 1 and n will be 0 - - // Add the next digit, n, to the result array. - qc[i++] = n; - - // Update the remainder. - if ( rem[0] ) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [ xc[xi] ]; - remL = 1; - } - } while ( ( xi++ < xL || rem[0] != null ) && s-- ); - - more = rem[0] != null; - - // Leading zero? - if ( !qc[0] ) qc.splice(0, 1); - } - - if ( base == BASE ) { - - // To calculate q.e, first get the number of digits of qc[0]. - for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); - - round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); - - // Caller is convertBase. - } else { - q.e = e; - q.r = +more; - } - - return q; - }; - })(); - - - /* - * Return a string representing the value of BigNumber n in fixed-point or exponential - * notation rounded to the specified decimal places or significant digits. - * - * n: a BigNumber. - * i: the index of the last digit required (i.e. the digit that may be rounded up). - * rm: the rounding mode. - * id: 1 (toExponential) or 2 (toPrecision). - */ - function format( n, i, rm, id ) { - var c0, e, ne, len, str; - - if ( rm == null ) rm = ROUNDING_MODE; - else intCheck( rm, 0, 8 ); - - if ( !n.c ) return n.toString(); - - c0 = n.c[0]; - ne = n.e; - - if ( i == null ) { - str = coeffToString( n.c ); - str = id == 1 || id == 2 && ne <= TO_EXP_NEG - ? toExponential( str, ne ) - : toFixedPoint( str, ne, '0' ); - } else { - n = round( new BigNumber(n), i, rm ); - - // n.e may have changed if the value was rounded up. - e = n.e; - - str = coeffToString( n.c ); - len = str.length; - - // toPrecision returns exponential notation if the number of significant digits - // specified is less than the number of digits necessary to represent the integer - // part of the value in fixed-point notation. - - // Exponential notation. - if ( id == 1 || id == 2 && ( i <= e || e <= TO_EXP_NEG ) ) { - - // Append zeros? - for ( ; len < i; str += '0', len++ ); - str = toExponential( str, e ); - - // Fixed-point notation. - } else { - i -= ne; - str = toFixedPoint( str, e, '0' ); - - // Append zeros? - if ( e + 1 > len ) { - if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); - } else { - i += e - len; - if ( i > 0 ) { - if ( e + 1 == len ) str += '.'; - for ( ; i--; str += '0' ); - } - } - } - } - - return n.s < 0 && c0 ? '-' + str : str; - } - - - // Handle BigNumber.max and BigNumber.min. - function maxOrMin( args, method ) { - var m, n, - i = 0; - - if ( isArray( args[0] ) ) args = args[0]; - m = new BigNumber( args[0] ); - - for ( ; ++i < args.length; ) { - n = new BigNumber( args[i] ); - - // If any number is NaN, return NaN. - if ( !n.s ) { - m = n; - break; - } else if ( method.call( m, n ) ) { - m = n; - } - } - - return m; - } - - - /* - * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. - * Called by minus, plus and times. - */ - function normalise( n, c, e ) { - var i = 1, - j = c.length; - - // Remove trailing zeros. - for ( ; !c[--j]; c.pop() ); - - // Calculate the base 10 exponent. First get the number of digits of c[0]. - for ( j = c[0]; j >= 10; j /= 10, i++ ); - - // Overflow? - if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { - - // Infinity. - n.c = n.e = null; - - // Underflow? - } else if ( e < MIN_EXP ) { - - // Zero. - n.c = [ n.e = 0 ]; - } else { - n.e = e; - n.c = c; - } - - return n; - } - - - // Handle values that fail the validity test in BigNumber. - parseNumeric = (function () { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, - dotAfter = /^([^.]+)\.$/, - dotBefore = /^\.([^.]+)$/, - isInfinityOrNaN = /^-?(Infinity|NaN)$/, - whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - - return function ( x, str, isNum, b ) { - var base, - s = isNum ? str : str.replace( whitespaceOrPlus, '' ); - - // No exception on ±Infinity or NaN. - if ( isInfinityOrNaN.test(s) ) { - x.s = isNaN(s) ? null : s < 0 ? -1 : 1; - x.c = x.e = null; - } else { - if ( !isNum ) { - - // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i - s = s.replace( basePrefix, function ( m, p1, p2 ) { - base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; - return !b || b == base ? p1 : m; - }); - - if (b) { - base = b; - - // E.g. '1.' to '1', '.1' to '0.1' - s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); - } - - if ( str != s ) return new BigNumber( s, base ); - } - - // '[BigNumber Error] Not a number: {n}' - // '[BigNumber Error] Not a base {b} number: {n}' - throw Error - ( bignumberError + 'Not a' + ( b ? ' base ' + b : '' ) + ' number: ' + str ); - } - } - })(); - - - /* - * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. - * If r is truthy, it is known that there are more digits after the rounding digit. - */ - function round( x, sd, rm, r ) { - var d, i, j, k, n, ni, rd, - xc = x.c, - pows10 = POWS_TEN; - - // if x is not Infinity or NaN... - if (xc) { - - // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. - // n is a base 1e14 number, the value of the element of array x.c containing rd. - // ni is the index of n within x.c. - // d is the number of digits of n. - // i is the index of rd within n including leading zeros. - // j is the actual index of rd within n (if < 0, rd is a leading zero). - out: { - - // Get the number of digits of the first element of xc. - for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); - i = sd - d; - - // If the rounding digit is in the first element of xc... - if ( i < 0 ) { - i += LOG_BASE; - j = sd; - n = xc[ ni = 0 ]; - - // Get the rounding digit at index j of n. - rd = n / pows10[ d - j - 1 ] % 10 | 0; - } else { - ni = mathceil( ( i + 1 ) / LOG_BASE ); - - if ( ni >= xc.length ) { - - if (r) { - - // Needed by sqrt. - for ( ; xc.length <= ni; xc.push(0) ); - n = rd = 0; - d = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; - } else { - break out; - } - } else { - n = k = xc[ni]; - - // Get the number of digits of n. - for ( d = 1; k >= 10; k /= 10, d++ ); - - // Get the index of rd within n. - i %= LOG_BASE; - - // Get the index of rd within n, adjusted for leading zeros. - // The number of leading zeros of n is given by LOG_BASE - d. - j = i - LOG_BASE + d; - - // Get the rounding digit at index j of n. - rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; - } - } - - r = r || sd < 0 || - - // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); - - r = rm < 4 - ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) - : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && - - // Check whether the digit to the left of the rounding digit is odd. - ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || - rm == ( x.s < 0 ? 8 : 7 ) ); - - if ( sd < 1 || !xc[0] ) { - xc.length = 0; - - if (r) { - - // Convert sd to decimal places. - sd -= x.e + 1; - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ]; - x.e = -sd || 0; - } else { - - // Zero. - xc[0] = x.e = 0; - } - - return x; - } - - // Remove excess digits. - if ( i == 0 ) { - xc.length = ni; - k = 1; - ni--; - } else { - xc.length = ni + 1; - k = pows10[ LOG_BASE - i ]; - - // E.g. 56700 becomes 56000 if 7 is the rounding digit. - // j > 0 means i > number of leading zeros of n. - xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; - } - - // Round up? - if (r) { - - for ( ; ; ) { - - // If the digit to be rounded up is in the first element of xc... - if ( ni == 0 ) { - - // i will be the length of xc[0] before k is added. - for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); - j = xc[0] += k; - for ( k = 1; j >= 10; j /= 10, k++ ); - - // if i != k the length has increased. - if ( i != k ) { - x.e++; - if ( xc[0] == BASE ) xc[0] = 1; - } - - break; - } else { - xc[ni] += k; - if ( xc[ni] != BASE ) break; - xc[ni--] = 0; - k = 1; - } - } - } - - // Remove trailing zeros. - for ( i = xc.length; xc[--i] === 0; xc.pop() ); - } - - // Overflow? Infinity. - if ( x.e > MAX_EXP ) { - x.c = x.e = null; - - // Underflow? Zero. - } else if ( x.e < MIN_EXP ) { - x.c = [ x.e = 0 ]; - } - } - - return x; - } - - - // PROTOTYPE/INSTANCE METHODS - - - /* - * Return a new BigNumber whose value is the absolute value of this BigNumber. - */ - P.absoluteValue = P.abs = function () { - var x = new BigNumber(this); - if ( x.s < 0 ) x.s = 1; - return x; - }; - - - /* - * Return - * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), - * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), - * 0 if they have the same value, - * or null if the value of either is NaN. - */ - P.comparedTo = function ( y, b ) { - return compare( this, new BigNumber( y, b ) ); - }; - - - /* - * If dp is undefined or null or true or false, return the number of decimal places of the - * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. - * - * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this - * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or - * ROUNDING_MODE if rm is omitted. - * - * [dp] {number} Decimal places: integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.decimalPlaces = P.dp = function ( dp, rm ) { - var c, n, v, - x = this; - - if ( dp != null ) { - intCheck( dp, 0, MAX ); - if ( rm == null ) rm = ROUNDING_MODE; - else intCheck( rm, 0, 8 ); - - return round( new BigNumber(x), dp + x.e + 1, rm ); - } - - if ( !( c = x.c ) ) return null; - n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; - - // Subtract the number of trailing zeros of the last number. - if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); - if ( n < 0 ) n = 0; - - return n; - }; - - - /* - * n / 0 = I - * n / N = N - * n / I = 0 - * 0 / n = 0 - * 0 / 0 = N - * 0 / N = N - * 0 / I = 0 - * N / n = N - * N / 0 = N - * N / N = N - * N / I = N - * I / n = I - * I / 0 = I - * I / N = N - * I / I = N - * - * Return a new BigNumber whose value is the value of this BigNumber divided by the value of - * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. - */ - P.dividedBy = P.div = function ( y, b ) { - return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); - }; - - - /* - * Return a new BigNumber whose value is the integer part of dividing the value of this - * BigNumber by the value of BigNumber(y, b). - */ - P.dividedToIntegerBy = P.idiv = function ( y, b ) { - return div( this, new BigNumber( y, b ), 0, 1 ); - }; - - - /* - * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), - * otherwise return false. - */ - P.isEqualTo = P.eq = function ( y, b ) { - return compare( this, new BigNumber( y, b ) ) === 0; - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer - * using rounding mode rm, or ROUNDING_MODE if rm is omitted. - * - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' - */ - P.integerValue = function (rm) { - var n = new BigNumber(this); - if ( rm == null ) rm = ROUNDING_MODE; - else intCheck( rm, 0, 8 ); - return round( n, n.e + 1, rm ); - }; - - - /* - * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), - * otherwise return false. - */ - P.isGreaterThan = P.gt = function ( y, b ) { - return compare( this, new BigNumber( y, b ) ) > 0; - }; - - - /* - * Return true if the value of this BigNumber is greater than or equal to the value of - * BigNumber(y, b), otherwise return false. - */ - P.isGreaterThanOrEqualTo = P.gte = function ( y, b ) { - return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; - - }; - - - /* - * Return true if the value of this BigNumber is a finite number, otherwise return false. - */ - P.isFinite = function () { - return !!this.c; - }; - - - /* - * Return true if the value of this BigNumber is an integer, otherwise return false. - */ - P.isInteger = function () { - return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; - }; - - - /* - * Return true if the value of this BigNumber is NaN, otherwise return false. - */ - P.isNaN = function () { - return !this.s; - }; - - - /* - * Return true if the value of this BigNumber is negative, otherwise return false. - */ - P.isNegative = function () { - return this.s < 0; - }; - - - /* - * Return true if the value of this BigNumber is positive, otherwise return false. - */ - P.isPositive = function () { - return this.s > 0; - }; - - - /* - * Return true if the value of this BigNumber is 0 or -0, otherwise return false. - */ - P.isZero = function () { - return !!this.c && this.c[0] == 0; - }; - - - /* - * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), - * otherwise return false. - */ - P.isLessThan = P.lt = function ( y, b ) { - return compare( this, new BigNumber( y, b ) ) < 0; - }; - - - /* - * Return true if the value of this BigNumber is less than or equal to the value of - * BigNumber(y, b), otherwise return false. - */ - P.isLessThanOrEqualTo = P.lte = function ( y, b ) { - return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; - }; - - - /* - * n - 0 = n - * n - N = N - * n - I = -I - * 0 - n = -n - * 0 - 0 = 0 - * 0 - N = N - * 0 - I = -I - * N - n = N - * N - 0 = N - * N - N = N - * N - I = N - * I - n = I - * I - 0 = I - * I - N = N - * I - I = N - * - * Return a new BigNumber whose value is the value of this BigNumber minus the value of - * BigNumber(y, b). - */ - P.minus = function ( y, b ) { - var i, j, t, xLTy, - x = this, - a = x.s; - - y = new BigNumber( y, b ); - b = y.s; - - // Either NaN? - if ( !a || !b ) return new BigNumber(NaN); - - // Signs differ? - if ( a != b ) { - y.s = -b; - return x.plus(y); - } - - var xe = x.e / LOG_BASE, - ye = y.e / LOG_BASE, - xc = x.c, - yc = y.c; - - if ( !xe || !ye ) { - - // Either Infinity? - if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); - - // Either zero? - if ( !xc[0] || !yc[0] ) { - - // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. - return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : - - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 ); - } - } - - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - - // Determine which is the bigger number. - if ( a = xe - ye ) { - - if ( xLTy = a < 0 ) { - a = -a; - t = xc; - } else { - ye = xe; - t = yc; - } - - t.reverse(); - - // Prepend zeros to equalise exponents. - for ( b = a; b--; t.push(0) ); - t.reverse(); - } else { - - // Exponents equal. Check digit by digit. - j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; - - for ( a = b = 0; b < j; b++ ) { - - if ( xc[b] != yc[b] ) { - xLTy = xc[b] < yc[b]; - break; - } - } - } - - // x < y? Point xc to the array of the bigger number. - if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; - - b = ( j = yc.length ) - ( i = xc.length ); - - // Append zeros to xc if shorter. - // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. - if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); - b = BASE - 1; - - // Subtract yc from xc. - for ( ; j > a; ) { - - if ( xc[--j] < yc[j] ) { - for ( i = j; i && !xc[--i]; xc[i] = b ); - --xc[i]; - xc[j] += BASE; - } - - xc[j] -= yc[j]; - } - - // Remove leading zeros and adjust exponent accordingly. - for ( ; xc[0] == 0; xc.splice(0, 1), --ye ); - - // Zero? - if ( !xc[0] ) { - - // Following IEEE 754 (2008) 6.3, - // n - n = +0 but n - n = -0 when rounding towards -Infinity. - y.s = ROUNDING_MODE == 3 ? -1 : 1; - y.c = [ y.e = 0 ]; - return y; - } - - // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity - // for finite x and y. - return normalise( y, xc, ye ); - }; - - - /* - * n % 0 = N - * n % N = N - * n % I = n - * 0 % n = 0 - * -0 % n = -0 - * 0 % 0 = N - * 0 % N = N - * 0 % I = 0 - * N % n = N - * N % 0 = N - * N % N = N - * N % I = N - * I % n = N - * I % 0 = N - * I % N = N - * I % I = N - * - * Return a new BigNumber whose value is the value of this BigNumber modulo the value of - * BigNumber(y, b). The result depends on the value of MODULO_MODE. - */ - P.modulo = P.mod = function ( y, b ) { - var q, s, - x = this; - - y = new BigNumber( y, b ); - - // Return NaN if x is Infinity or NaN, or y is NaN or zero. - if ( !x.c || !y.s || y.c && !y.c[0] ) { - return new BigNumber(NaN); - - // Return x if y is Infinity or x is zero. - } else if ( !y.c || x.c && !x.c[0] ) { - return new BigNumber(x); - } - - if ( MODULO_MODE == 9 ) { - - // Euclidian division: q = sign(y) * floor(x / abs(y)) - // r = x - qy where 0 <= r < abs(y) - s = y.s; - y.s = 1; - q = div( x, y, 0, 3 ); - y.s = s; - q.s *= s; - } else { - q = div( x, y, 0, MODULO_MODE ); - } - - return x.minus( q.times(y) ); - }; - - - /* - * n * 0 = 0 - * n * N = N - * n * I = I - * 0 * n = 0 - * 0 * 0 = 0 - * 0 * N = N - * 0 * I = N - * N * n = N - * N * 0 = N - * N * N = N - * N * I = N - * I * n = I - * I * 0 = N - * I * N = N - * I * I = I - * - * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value - * of BigNumber(y, b). - */ - P.multipliedBy = P.times = function ( y, b ) { - var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, - base, sqrtBase, - x = this, - xc = x.c, - yc = ( y = new BigNumber( y, b ) ).c; - - // Either NaN, ±Infinity or ±0? - if ( !xc || !yc || !xc[0] || !yc[0] ) { - - // Return NaN if either is NaN, or one is 0 and the other is Infinity. - if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { - y.c = y.e = y.s = null; - } else { - y.s *= x.s; - - // Return ±Infinity if either is ±Infinity. - if ( !xc || !yc ) { - y.c = y.e = null; - - // Return ±0 if either is ±0. - } else { - y.c = [0]; - y.e = 0; - } - } - - return y; - } - - e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); - y.s *= x.s; - xcL = xc.length; - ycL = yc.length; - - // Ensure xc points to longer array and xcL to its length. - if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; - - // Initialise the result array with zeros. - for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); - - base = BASE; - sqrtBase = SQRT_BASE; - - for ( i = ycL; --i >= 0; ) { - c = 0; - ylo = yc[i] % sqrtBase; - yhi = yc[i] / sqrtBase | 0; - - for ( k = xcL, j = i + k; j > i; ) { - xlo = xc[--k] % sqrtBase; - xhi = xc[k] / sqrtBase | 0; - m = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; - c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; - zc[j--] = xlo % base; - } - - zc[j] = c; - } - - if (c) { - ++e; - } else { - zc.splice(0, 1); - } - - return normalise( y, zc, e ); - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber negated, - * i.e. multiplied by -1. - */ - P.negated = function () { - var x = new BigNumber(this); - x.s = -x.s || null; - return x; - }; - - - /* - * n + 0 = n - * n + N = N - * n + I = I - * 0 + n = n - * 0 + 0 = 0 - * 0 + N = N - * 0 + I = I - * N + n = N - * N + 0 = N - * N + N = N - * N + I = N - * I + n = I - * I + 0 = I - * I + N = N - * I + I = I - * - * Return a new BigNumber whose value is the value of this BigNumber plus the value of - * BigNumber(y, b). - */ - P.plus = function ( y, b ) { - var t, - x = this, - a = x.s; - - y = new BigNumber( y, b ); - b = y.s; - - // Either NaN? - if ( !a || !b ) return new BigNumber(NaN); - - // Signs differ? - if ( a != b ) { - y.s = -b; - return x.minus(y); - } - - var xe = x.e / LOG_BASE, - ye = y.e / LOG_BASE, - xc = x.c, - yc = y.c; - - if ( !xe || !ye ) { - - // Return ±Infinity if either ±Infinity. - if ( !xc || !yc ) return new BigNumber( a / 0 ); - - // Either zero? - // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. - if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); - } - - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - - // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. - if ( a = xe - ye ) { - if ( a > 0 ) { - ye = xe; - t = yc; - } else { - a = -a; - t = xc; - } - - t.reverse(); - for ( ; a--; t.push(0) ); - t.reverse(); - } - - a = xc.length; - b = yc.length; - - // Point xc to the longer array, and b to the shorter length. - if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; - - // Only start adding at yc.length - 1 as the further digits of xc can be ignored. - for ( a = 0; b; ) { - a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; - xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; - } - - if (a) { - xc = [a].concat(xc); - ++ye; - } - - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - // ye = MAX_EXP + 1 possible - return normalise( y, xc, ye ); - }; - - - /* - * If sd is undefined or null or true or false, return the number of significant digits of - * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. - * If sd is true include integer-part trailing zeros in the count. - * - * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this - * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or - * ROUNDING_MODE if rm is omitted. - * - * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. - * boolean: whether to count integer-part trailing zeros: true or false. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' - */ - P.precision = P.sd = function ( sd, rm ) { - var c, n, v, - x = this; - - if ( sd != null && sd !== !!sd ) { - intCheck( sd, 1, MAX ); - if ( rm == null ) rm = ROUNDING_MODE; - else intCheck( rm, 0, 8 ); - - return round( new BigNumber(x), sd, rm ); - } - - if ( !( c = x.c ) ) return null; - v = c.length - 1; - n = v * LOG_BASE + 1; - - if ( v = c[v] ) { - - // Subtract the number of trailing zeros of the last element. - for ( ; v % 10 == 0; v /= 10, n-- ); - - // Add the number of digits of the first element. - for ( v = c[0]; v >= 10; v /= 10, n++ ); - } - - if ( sd && x.e + 1 > n ) n = x.e + 1; - - return n; - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber shifted by k places - * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. - * - * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' - */ - P.shiftedBy = function (k) { - intCheck( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER ); - return this.times( '1e' + k ); - }; - - - /* - * sqrt(-n) = N - * sqrt( N) = N - * sqrt(-I) = N - * sqrt( I) = I - * sqrt( 0) = 0 - * sqrt(-0) = -0 - * - * Return a new BigNumber whose value is the square root of the value of this BigNumber, - * rounded according to DECIMAL_PLACES and ROUNDING_MODE. - */ - P.squareRoot = P.sqrt = function () { - var m, n, r, rep, t, - x = this, - c = x.c, - s = x.s, - e = x.e, - dp = DECIMAL_PLACES + 4, - half = new BigNumber('0.5'); - - // Negative/NaN/Infinity/zero? - if ( s !== 1 || !c || !c[0] ) { - return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); - } - - // Initial estimate. - s = Math.sqrt( +x ); - - // Math.sqrt underflow/overflow? - // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - if ( s == 0 || s == 1 / 0 ) { - n = coeffToString(c); - if ( ( n.length + e ) % 2 == 0 ) n += '0'; - s = Math.sqrt(n); - e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); - - if ( s == 1 / 0 ) { - n = '1e' + e; - } else { - n = s.toExponential(); - n = n.slice( 0, n.indexOf('e') + 1 ) + e; - } - - r = new BigNumber(n); - } else { - r = new BigNumber( s + '' ); - } - - // Check for zero. - // r could be zero if MIN_EXP is changed after the this value was created. - // This would cause a division by zero (x/t) and hence Infinity below, which would cause - // coeffToString to throw. - if ( r.c[0] ) { - e = r.e; - s = e + dp; - if ( s < 3 ) s = 0; - - // Newton-Raphson iteration. - for ( ; ; ) { - t = r; - r = half.times( t.plus( div( x, t, dp, 1 ) ) ); - - if ( coeffToString( t.c ).slice( 0, s ) === ( n = - coeffToString( r.c ) ).slice( 0, s ) ) { - - // The exponent of r may here be one less than the final result exponent, - // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits - // are indexed correctly. - if ( r.e < e ) --s; - n = n.slice( s - 3, s + 1 ); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits - // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the - // iteration. - if ( n == '9999' || !rep && n == '4999' ) { - - // On the first iteration only, check to see if rounding up gives the - // exact result as the nines may infinitely repeat. - if ( !rep ) { - round( t, t.e + DECIMAL_PLACES + 2, 0 ); - - if ( t.times(t).eq(x) ) { - r = t; - break; - } - } - - dp += 4; - s += 4; - rep = 1; - } else { - - // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact - // result. If not, then there are further digits and m will be truthy. - if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { - - // Truncate to the first rounding digit. - round( r, r.e + DECIMAL_PLACES + 2, 1 ); - m = !r.times(r).eq(x); - } - - break; - } - } - } - } - - return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); - }; - - - /* - * Return a string representing the value of this BigNumber in exponential notation and - * rounded using ROUNDING_MODE to dp fixed decimal places. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toExponential = function ( dp, rm ) { - if ( dp != null ) { - intCheck( dp, 0, MAX ); - dp++; - } - return format( this, dp, rm, 1 ); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounding - * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. - * - * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', - * but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toFixed = function ( dp, rm ) { - if ( dp != null ) { - intCheck( dp, 0, MAX ); - dp = dp + this.e + 1; - } - return format( this, dp, rm ); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounded - * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties - * of the FORMAT object (see BigNumber.set). - * - * FORMAT = { - * decimalSeparator : '.', - * groupSeparator : ',', - * groupSize : 3, - * secondaryGroupSize : 0, - * fractionGroupSeparator : '\xA0', // non-breaking space - * fractionGroupSize : 0 - * }; - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toFormat = function ( dp, rm ) { - var str = this.toFixed( dp, rm ); - - if ( this.c ) { - var i, - arr = str.split('.'), - g1 = +FORMAT.groupSize, - g2 = +FORMAT.secondaryGroupSize, - groupSeparator = FORMAT.groupSeparator, - intPart = arr[0], - fractionPart = arr[1], - isNeg = this.s < 0, - intDigits = isNeg ? intPart.slice(1) : intPart, - len = intDigits.length; - - if (g2) i = g1, g1 = g2, g2 = i, len -= i; - - if ( g1 > 0 && len > 0 ) { - i = len % g1 || g1; - intPart = intDigits.substr( 0, i ); - - for ( ; i < len; i += g1 ) { - intPart += groupSeparator + intDigits.substr( i, g1 ); - } - - if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); - if (isNeg) intPart = '-' + intPart; - } - - str = fractionPart - ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) - ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), - '$&' + FORMAT.fractionGroupSeparator ) - : fractionPart ) - : intPart; - } - - return str; - }; - - - /* - * Return a string array representing the value of this BigNumber as a simple fraction with - * an integer numerator and an integer denominator. The denominator will be a positive - * non-zero value less than or equal to the specified maximum denominator. If a maximum - * denominator is not specified, the denominator will be the lowest value necessary to - * represent the number exactly. - * - * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. - * - * '[BigNumber Error] Argument {not an integer|out of range} : {md}' - */ - P.toFraction = function (md) { - var arr, d, d0, d1, d2, e, exp, n, n0, n1, q, s, - x = this, - xc = x.c; - - if ( md != null ) { - n = new BigNumber(md); - - if ( !n.isInteger() || n.lt(ONE) ) { - throw Error - ( bignumberError + 'Argument ' + - ( n.isInteger() ? 'out of range: ' : 'not an integer: ' ) + md ); - } - } - - if ( !xc ) return x.toString(); - - d = new BigNumber(ONE); - n1 = d0 = new BigNumber(ONE); - d1 = n0 = new BigNumber(ONE); - s = coeffToString(xc); - - // Determine initial denominator. - // d is a power of 10 and the minimum max denominator that specifies the value exactly. - e = d.e = s.length - x.e - 1; - d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; - md = !md || n.comparedTo(d) > 0 ? ( e > 0 ? d : n1 ) : n; - - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n = new BigNumber(s); - - // n0 = d1 = 0 - n0.c[0] = 0; - - for ( ; ; ) { - q = div( n, d, 0, 1 ); - d2 = d0.plus( q.times(d1) ); - if ( d2.comparedTo(md) == 1 ) break; - d0 = d1; - d1 = d2; - n1 = n0.plus( q.times( d2 = n1 ) ); - n0 = d2; - d = n.minus( q.times( d2 = d ) ); - n = d2; - } - - d2 = div( md.minus(d0), d1, 0, 1 ); - n0 = n0.plus( d2.times(n1) ); - d0 = d0.plus( d2.times(d1) ); - n0.s = n1.s = x.s; - e *= 2; - - // Determine which fraction is closer to x, n0/d0 or n1/d1 - arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().comparedTo( - div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 - ? [ n1.toString(), d1.toString() ] - : [ n0.toString(), d0.toString() ]; - - MAX_EXP = exp; - return arr; - }; - - - /* - * Return the value of this BigNumber converted to a number primitive. - */ - P.toNumber = function () { - return +this; - }; - - - /* - * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. - * - * If m is present, return the result modulo m. - * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. - * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. - * - * The modular power operation works efficiently when x, n, and m are positive integers, - * otherwise it is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. - * - * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. - * [m] {number|string|BigNumber} The modulus. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {n}' - * - * Performs 54 loop iterations for n of 9007199254740991. - */ - P.exponentiatedBy = P.pow = function ( n, m ) { - var i, k, y, z, - x = this; - - intCheck( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER ); - if ( m != null ) m = new BigNumber(m); - - if (m) { - if ( n > 1 && x.gt(ONE) && x.isInteger() && m.gt(ONE) && m.isInteger() ) { - x = x.mod(m); - } else { - z = m; - - // Nullify m so only a single mod operation is performed at the end. - m = null; - } - } else if (POW_PRECISION) { - - // Truncating each coefficient array to a length of k after each multiplication - // equates to truncating significant digits to POW_PRECISION + [28, 41], - // i.e. there will be a minimum of 28 guard digits retained. - //k = mathceil( POW_PRECISION / LOG_BASE + 1.5 ); // gives [9, 21] guard digits. - k = mathceil( POW_PRECISION / LOG_BASE + 2 ); - } - - y = new BigNumber(ONE); - - for ( i = mathfloor( n < 0 ? -n : n ); ; ) { - if ( i % 2 ) { - y = y.times(x); - if ( !y.c ) break; - if (k) { - if ( y.c.length > k ) y.c.length = k; - } else if (m) { - y = y.mod(m); - } - } - - i = mathfloor( i / 2 ); - if ( !i ) break; - x = x.times(x); - if (k) { - if ( x.c && x.c.length > k ) x.c.length = k; - } else if (m) { - x = x.mod(m); - } - } - - if (m) return y; - if ( n < 0 ) y = ONE.div(y); - - return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; - }; - - - /* - * Return a string representing the value of this BigNumber rounded to sd significant digits - * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits - * necessary to represent the integer part of the value in fixed-point notation, then use - * exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' - */ - P.toPrecision = function ( sd, rm ) { - if ( sd != null ) intCheck( sd, 1, MAX ); - return format( this, sd, rm, 2 ); - }; - - - /* - * Return a string representing the value of this BigNumber in base b, or base 10 if b is - * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and - * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent - * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than - * TO_EXP_NEG, return exponential notation. - * - * [b] {number} Integer, 2 to ALPHABET.length inclusive. - * - * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' - */ - P.toString = function (b) { - var str, - n = this, - s = n.s, - e = n.e; - - // Infinity or NaN? - if ( e === null ) { - - if (s) { - str = 'Infinity'; - if ( s < 0 ) str = '-' + str; - } else { - str = 'NaN'; - } - } else { - str = coeffToString( n.c ); - - if ( b == null ) { - str = e <= TO_EXP_NEG || e >= TO_EXP_POS - ? toExponential( str, e ) - : toFixedPoint( str, e, '0' ); - } else { - intCheck( b, 2, ALPHABET.length, 'Base' ); - str = convertBase( toFixedPoint( str, e, '0' ), 10, b, s, true ); - } - - if ( s < 0 && n.c[0] ) str = '-' + str; - } - - return str; - }; - - - /* - * Return as toString, but do not accept a base argument, and include the minus sign for - * negative zero. - */ - P.valueOf = P.toJSON = function () { - var str, - n = this, - e = n.e; - - if ( e === null ) return n.toString(); - - str = coeffToString( n.c ); - - str = e <= TO_EXP_NEG || e >= TO_EXP_POS - ? toExponential( str, e ) - : toFixedPoint( str, e, '0' ); - - return n.s < 0 ? '-' + str : str; - }; - - - P._isBigNumber = true; - - if ( configObject != null ) BigNumber.set(configObject); - - return BigNumber; - } - - - // PRIVATE HELPER FUNCTIONS - - - function bitFloor(n) { - var i = n | 0; - return n > 0 || n === i ? i : i - 1; - } - - - // Return a coefficient array as a string of base 10 digits. - function coeffToString(a) { - var s, z, - i = 1, - j = a.length, - r = a[0] + ''; - - for ( ; i < j; ) { - s = a[i++] + ''; - z = LOG_BASE - s.length; - for ( ; z--; s = '0' + s ); - r += s; - } - - // Determine trailing zeros. - for ( j = r.length; r.charCodeAt(--j) === 48; ); - return r.slice( 0, j + 1 || 1 ); - } - - - // Compare the value of BigNumbers x and y. - function compare( x, y ) { - var a, b, - xc = x.c, - yc = y.c, - i = x.s, - j = y.s, - k = x.e, - l = y.e; - - // Either NaN? - if ( !i || !j ) return null; - - a = xc && !xc[0]; - b = yc && !yc[0]; - - // Either zero? - if ( a || b ) return a ? b ? 0 : -j : i; - - // Signs differ? - if ( i != j ) return i; - - a = i < 0; - b = k == l; - - // Either Infinity? - if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; - - // Compare exponents. - if ( !b ) return k > l ^ a ? 1 : -1; - - j = ( k = xc.length ) < ( l = yc.length ) ? k : l; - - // Compare digit by digit. - for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; - - // Compare lengths. - return k == l ? 0 : k > l ^ a ? 1 : -1; - } - - - /* - * Check that n is a primitive number, an integer, and in range, otherwise throw. - */ - function intCheck( n, min, max, name ) { - if ( n < min || n > max || n !== ( n < 0 ? mathceil(n) : mathfloor(n) ) ) { - throw Error - ( bignumberError + ( name || 'Argument' ) + ( typeof n == 'number' - ? n < min || n > max ? ' out of range: ' : ' not an integer: ' - : ' not a primitive number: ' ) + n ); - } - } - - - function isArray(obj) { - return Object.prototype.toString.call(obj) == '[object Array]'; - } - - - function toExponential( str, e ) { - return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + - ( e < 0 ? 'e' : 'e+' ) + e; - } - - - function toFixedPoint( str, e, z ) { - var len, zs; - - // Negative exponent? - if ( e < 0 ) { - - // Prepend zeros. - for ( zs = z + '.'; ++e; zs += z ); - str = zs + str; - - // Positive exponent - } else { - len = str.length; - - // Append zeros. - if ( ++e > len ) { - for ( zs = z, e -= len; --e; zs += z ); - str += zs; - } else if ( e < len ) { - str = str.slice( 0, e ) + '.' + str.slice(e); - } - } - - return str; - } - - - // EXPORT - - - BigNumber = clone(); - BigNumber['default'] = BigNumber.BigNumber = BigNumber; - - - // AMD. - if ( typeof define == 'function' && define.amd ) { - define( function () { return BigNumber; } ); - - // Node.js and other environments that support module.exports. - } else if ( typeof module != 'undefined' && module.exports ) { - module.exports = BigNumber; - - // Browser. - } else { - if ( !globalObject ) { - globalObject = typeof self != 'undefined' ? self : Function('return this')(); - } - - globalObject.BigNumber = BigNumber; - } -})(this); - -},{}],80:[function(require,module,exports){ -(function (__filename){ + out += ' } '; + } else { + out += ' {} '; + } -/** - * Module dependencies. - */ + var __err = out; + out = $$outStack.pop(); + + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + $valid + ' = true; '; + } + } -var fs = require('fs') - , path = require('path') - , join = path.join - , dirname = path.dirname - , exists = ((fs.accessSync && function (path) { try { fs.accessSync(path); } catch (e) { return false; } return true; }) - || fs.existsSync || path.existsSync) - , defaults = { - arrow: process.env.NODE_BINDINGS_ARROW || ' → ' - , compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled' - , platform: process.platform - , arch: process.arch - , version: process.versions.node - , bindings: 'bindings.node' - , try: [ - // node-gyp's linked version in the "build" dir - [ 'module_root', 'build', 'bindings' ] - // node-waf and gyp_addon (a.k.a node-gyp) - , [ 'module_root', 'build', 'Debug', 'bindings' ] - , [ 'module_root', 'build', 'Release', 'bindings' ] - // Debug files, for development (legacy behavior, remove for node v0.9) - , [ 'module_root', 'out', 'Debug', 'bindings' ] - , [ 'module_root', 'Debug', 'bindings' ] - // Release files, but manually compiled (legacy behavior, remove for node v0.9) - , [ 'module_root', 'out', 'Release', 'bindings' ] - , [ 'module_root', 'Release', 'bindings' ] - // Legacy from node-waf, node <= 0.4.x - , [ 'module_root', 'build', 'default', 'bindings' ] - // Production "Release" buildtype binary (meh...) - , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ] - ] + if (it.isTop) { + out += ' }; return validate; '; } -/** - * The main `bindings()` function loads the compiled bindings for a given module. - * It uses V8's Error API to determine the parent filename that this function is - * being invoked from, which is then used to find the root directory. - */ + return out; + } -function bindings (opts) { + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [undefined]; - // Argument surgery - if (typeof opts == 'string') { - opts = { bindings: opts } - } else if (!opts) { - opts = {} + if (it.schema["default"] !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);else throw new Error($defaultMsg); + } + + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + $lvl + ' = errors;'; } - // maps `defaults` onto `opts` object - Object.keys(defaults).map(function(i) { - if (!(i in opts)) opts[i] = defaults[i]; - }); + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); - // Get the module root - if (!opts.module_root) { - opts.module_root = exports.getRoot(exports.getFileName()) + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } } - // Ensure the given bindings name ends with .node - if (path.extname(opts.bindings) != '.node') { - opts.bindings += '.node' + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; } - var tries = [] - , i = 0 - , l = opts.try.length - , n - , b - , err - - for (; i 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false + out += ')) ' + $coerced + ' = +' + $data + '; '; + } else if ($type == 'boolean') { + out += ' if (' + $data + ' === \'false\' || ' + $data + ' === 0 || ' + $data + ' === null) ' + $coerced + ' = false; else if (' + $data + ' === \'true\' || ' + $data + ' === 1) ' + $coerced + ' = true; '; + } else if ($type == 'null') { + out += ' if (' + $data + ' === \'\' || ' + $data + ' === 0 || ' + $data + ' === false) ' + $coerced + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' if (' + $dataType + ' == \'string\' || ' + $dataType + ' == \'number\' || ' + $dataType + ' == \'boolean\' || ' + $data + ' == null) ' + $coerced + ' = [' + $data + ']; '; + } + } + } - var lenR = buffer[3] - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false + out += ' ' + $bracesCoercion + ' if (' + $coerced + ' === undefined) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ - var lenS = buffer[5 + lenR] - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \''; - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true -} + out += '\' } '; -function decode (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + if (it.opts.messages !== false) { + out += ' , message: \'should be '; - var lenR = buffer[3] - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } - var lenS = buffer[5 + lenR] - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + out += '\' '; + } - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + out += ' } '; + } else { + out += ' {} '; + } - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } -} + var __err = out; + out = $$outStack.pop(); -/* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 -*/ -function encode (r, s) { - var lenR = r.length - var lenS = s.length - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - - var signature = Buffer.allocUnsafe(6 + lenR + lenS) - - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30 - signature[1] = signature.length - 2 - signature[2] = 0x02 - signature[3] = r.length - r.copy(signature, 4) - signature[4 + lenR] = 0x02 - signature[5 + lenR] = s.length - s.copy(signature, 6 + lenR) - - return signature -} + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } -module.exports = { - check: check, - decode: decode, - encode: encode -} + out += ' } else { '; + var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + $data + ' = ' + $coerced + '; '; -},{"safe-buffer":1256}],82:[function(require,module,exports){ -module.exports={ - "OP_FALSE": 0, - "OP_0": 0, - "OP_PUSHDATA1": 76, - "OP_PUSHDATA2": 77, - "OP_PUSHDATA4": 78, - "OP_1NEGATE": 79, - "OP_RESERVED": 80, - "OP_TRUE": 81, - "OP_1": 81, - "OP_2": 82, - "OP_3": 83, - "OP_4": 84, - "OP_5": 85, - "OP_6": 86, - "OP_7": 87, - "OP_8": 88, - "OP_9": 89, - "OP_10": 90, - "OP_11": 91, - "OP_12": 92, - "OP_13": 93, - "OP_14": 94, - "OP_15": 95, - "OP_16": 96, + if (!$dataLvl) { + out += 'if (' + $parentData + ' !== undefined)'; + } - "OP_NOP": 97, - "OP_VER": 98, - "OP_IF": 99, - "OP_NOTIF": 100, - "OP_VERIF": 101, - "OP_VERNOTIF": 102, - "OP_ELSE": 103, - "OP_ENDIF": 104, - "OP_VERIFY": 105, - "OP_RETURN": 106, + out += ' ' + $parentData + '[' + $parentDataProperty + '] = ' + $coerced + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ - "OP_TOALTSTACK": 107, - "OP_FROMALTSTACK": 108, - "OP_2DROP": 109, - "OP_2DUP": 110, - "OP_3DUP": 111, - "OP_2OVER": 112, - "OP_2ROT": 113, - "OP_2SWAP": 114, - "OP_IFDUP": 115, - "OP_DEPTH": 116, - "OP_DROP": 117, - "OP_DUP": 118, - "OP_NIP": 119, - "OP_OVER": 120, - "OP_PICK": 121, - "OP_ROLL": 122, - "OP_ROT": 123, - "OP_SWAP": 124, - "OP_TUCK": 125, + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \''; - "OP_CAT": 126, - "OP_SUBSTR": 127, - "OP_LEFT": 128, - "OP_RIGHT": 129, - "OP_SIZE": 130, + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } - "OP_INVERT": 131, - "OP_AND": 132, - "OP_OR": 133, - "OP_XOR": 134, - "OP_EQUAL": 135, - "OP_EQUALVERIFY": 136, - "OP_RESERVED1": 137, - "OP_RESERVED2": 138, + out += '\' } '; - "OP_1ADD": 139, - "OP_1SUB": 140, - "OP_2MUL": 141, - "OP_2DIV": 142, - "OP_NEGATE": 143, - "OP_ABS": 144, - "OP_NOT": 145, - "OP_0NOTEQUAL": 146, - "OP_ADD": 147, - "OP_SUB": 148, - "OP_MUL": 149, - "OP_DIV": 150, - "OP_MOD": 151, - "OP_LSHIFT": 152, - "OP_RSHIFT": 153, + if (it.opts.messages !== false) { + out += ' , message: \'should be '; - "OP_BOOLAND": 154, - "OP_BOOLOR": 155, - "OP_NUMEQUAL": 156, - "OP_NUMEQUALVERIFY": 157, - "OP_NUMNOTEQUAL": 158, - "OP_LESSTHAN": 159, - "OP_GREATERTHAN": 160, - "OP_LESSTHANOREQUAL": 161, - "OP_GREATERTHANOREQUAL": 162, - "OP_MIN": 163, - "OP_MAX": 164, + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } - "OP_WITHIN": 165, + out += '\' '; + } - "OP_RIPEMD160": 166, - "OP_SHA1": 167, - "OP_SHA256": 168, - "OP_HASH160": 169, - "OP_HASH256": 170, - "OP_CODESEPARATOR": 171, - "OP_CHECKSIG": 172, - "OP_CHECKSIGVERIFY": 173, - "OP_CHECKMULTISIG": 174, - "OP_CHECKMULTISIGVERIFY": 175, + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } - "OP_NOP1": 176, - - "OP_NOP2": 177, - "OP_CHECKLOCKTIMEVERIFY": 177, + out += ' } '; + } else { + out += ' {} '; + } - "OP_NOP3": 178, - "OP_CHECKSEQUENCEVERIFY": 178, - - "OP_NOP4": 179, - "OP_NOP5": 180, - "OP_NOP6": 181, - "OP_NOP7": 182, - "OP_NOP8": 183, - "OP_NOP9": 184, - "OP_NOP10": 185, + var __err = out; + out = $$outStack.pop(); - "OP_PUBKEYHASH": 253, - "OP_PUBKEY": 254, - "OP_INVALIDOPCODE": 255 -} + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } -},{}],83:[function(require,module,exports){ -var OPS = require('./index.json') + out += ' } '; + } + } -var map = {} -for (var op in OPS) { - var code = OPS[op] - map[code] = op -} + if (it.schema.$ref && !$refKeywords) { + out += ' ' + it.RULES.all.$ref.code(it, '$ref') + ' '; -module.exports = map + if ($breakOnError) { + out += ' } if (errors === '; -},{"./index.json":82}],84:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bech32 = require('bech32') -var bs58check = require('bs58check') -var bscript = require('./script') -var btemplates = require('./templates') -var networks = require('./networks') -var typeforce = require('typeforce') -var types = require('./types') + if ($top) { + out += '0'; + } else { + out += 'errs_' + $lvl; + } -function fromBase58Check (address) { - var payload = bs58check.decode(address) + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short') - if (payload.length > 21) throw new TypeError(address + ' is too long') + if (arr2) { + var $rulesGroup, + i2 = -1, + l2 = arr2.length - 1; - var version = payload.readUInt8(0) - var hash = payload.slice(1) + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; - return { version: version, hash: hash } -} + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + it.util.checkDataType($rulesGroup.type, $data) + ') { '; + } -function fromBech32 (address) { - var result = bech32.decode(address) - var data = bech32.fromWords(result.words.slice(1)) + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + + if (arr3) { + var $propertyKey, + i3 = -1, + l3 = arr3.length - 1; + + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + + if ($sch["default"] !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);else throw new Error($defaultMsg); + } + } else { + out += ' if (' + $passData + ' === undefined '; + + if (it.opts.useDefaults == 'empty') { + out += ' || ' + $passData + ' === null || ' + $passData + ' === \'\' '; + } + + out += ' ) ' + $passData + ' = '; + + if (it.opts.useDefaults == 'shared') { + out += ' ' + it.useDefault($sch["default"]) + ' '; + } else { + out += ' ' + JSON.stringify($sch["default"]) + ' '; + } + + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer.from(data) - } -} + if (arr4) { + var $sch, + $i = -1, + l4 = arr4.length - 1; -function toBase58Check (hash, version) { - typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments) + while ($i < l4) { + $sch = arr4[$i += 1]; - var payload = Buffer.allocUnsafe(21) - payload.writeUInt8(version, 0) - hash.copy(payload, 1) + if ($sch["default"] !== undefined) { + var $passData = $data + '[' + $i + ']'; - return bs58check.encode(payload) -} + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);else throw new Error($defaultMsg); + } + } else { + out += ' if (' + $passData + ' === undefined '; -function toBech32 (data, version, prefix) { - var words = bech32.toWords(data) - words.unshift(version) + if (it.opts.useDefaults == 'empty') { + out += ' || ' + $passData + ' === null || ' + $passData + ' === \'\' '; + } - return bech32.encode(prefix, words) -} + out += ' ) ' + $passData + ' = '; -function fromOutputScript (outputScript, network) { - network = network || networks.bitcoin + if (it.opts.useDefaults == 'shared') { + out += ' ' + it.useDefault($sch["default"]) + ' '; + } else { + out += ' ' + JSON.stringify($sch["default"]) + ' '; + } - if (btemplates.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash) - if (btemplates.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash) - if (btemplates.witnessPubKeyHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 22), 0, network.bech32) - if (btemplates.witnessScriptHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 34), 0, network.bech32) + out += '; '; + } + } + } + } + } + } - throw new Error(bscript.toASM(outputScript) + ' has no matching Address') -} + var arr5 = $rulesGroup.rules; -function toOutputScript (address, network) { - network = network || networks.bitcoin + if (arr5) { + var $rule, + i5 = -1, + l5 = arr5.length - 1; - var decode - try { - decode = fromBase58Check(address) - } catch (e) {} + while (i5 < l5) { + $rule = arr5[i5 += 1]; - if (decode) { - if (decode.version === network.pubKeyHash) return btemplates.pubKeyHash.output.encode(decode.hash) - if (decode.version === network.scriptHash) return btemplates.scriptHash.output.encode(decode.hash) - } else { - try { - decode = fromBech32(address) - } catch (e) {} + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); - if (decode) { - if (decode.prefix !== network.bech32) throw new Error(address + ' has an invalid prefix') - if (decode.version === 0) { - if (decode.data.length === 20) return btemplates.witnessPubKeyHash.output.encode(decode.data) - if (decode.data.length === 32) return btemplates.witnessScriptHash.output.encode(decode.data) - } - } - } + if ($code) { + out += ' ' + $code + ' '; - throw new Error(address + ' has no matching Script') -} + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } -module.exports = { - fromBase58Check: fromBase58Check, - fromBech32: fromBech32, - fromOutputScript: fromOutputScript, - toBase58Check: toBase58Check, - toBech32: toBech32, - toOutputScript: toOutputScript -} + if ($breakOnError) { + out += ' ' + $closingBraces1 + ' '; + $closingBraces1 = ''; + } -},{"./networks":93,"./script":94,"./templates":96,"./types":120,"bech32":73,"bs58check":149,"safe-buffer":1256,"typeforce":1318}],85:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bcrypto = require('./crypto') -var fastMerkleRoot = require('merkle-lib/fastRoot') -var typeforce = require('typeforce') -var types = require('./types') -var varuint = require('varuint-bitcoin') + if ($rulesGroup.type) { + out += ' } '; -var Transaction = require('./transaction') + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + /* istanbul ignore else */ -function Block () { - this.version = 1 - this.prevHash = null - this.merkleRoot = null - this.timestamp = 0 - this.bits = 0 - this.nonce = 0 -} + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \''; -Block.fromBuffer = function (buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)') + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } - var offset = 0 - function readSlice (n) { - offset += n - return buffer.slice(offset - n, offset) - } + out += '\' } '; - function readUInt32 () { - var i = buffer.readUInt32LE(offset) - offset += 4 - return i - } + if (it.opts.messages !== false) { + out += ' , message: \'should be '; - function readInt32 () { - var i = buffer.readInt32LE(offset) - offset += 4 - return i - } + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } - var block = new Block() - block.version = readInt32() - block.prevHash = readSlice(32) - block.merkleRoot = readSlice(32) - block.timestamp = readUInt32() - block.bits = readUInt32() - block.nonce = readUInt32() + out += '\' '; + } - if (buffer.length === 80) return block + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } - function readVarInt () { - var vi = varuint.decode(buffer, offset) - offset += varuint.decode.bytes - return vi - } + out += ' } '; + } else { + out += ' {} '; + } - function readTransaction () { - var tx = Transaction.fromBuffer(buffer.slice(offset), true) - offset += tx.byteLength() - return tx - } + var __err = out; + out = $$outStack.pop(); - var nTransactions = readVarInt() - block.transactions = [] + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } - for (var i = 0; i < nTransactions; ++i) { - var tx = readTransaction() - block.transactions.push(tx) - } + out += ' } '; + } + } - return block -} + if ($breakOnError) { + out += ' if (errors === '; -Block.prototype.byteLength = function (headersOnly) { - if (headersOnly || !this.transactions) return 80 + if ($top) { + out += '0'; + } else { + out += 'errs_' + $lvl; + } - return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) { - return a + x.byteLength() - }, 0) -} + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } -Block.fromHex = function (hex) { - return Block.fromBuffer(Buffer.from(hex, 'hex')) -} + if ($breakOnError) { + out += ' ' + $closingBraces2 + ' '; + } -Block.prototype.getHash = function () { - return bcrypto.hash256(this.toBuffer(true)) -} + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } -Block.prototype.getId = function () { - return this.getHash().reverse().toString('hex') -} + out += ' }; return validate;'; + } else { + out += ' var ' + $valid + ' = errors === errs_' + $lvl + ';'; + } -Block.prototype.getUTCDate = function () { - var date = new Date(0) // epoch - date.setUTCSeconds(this.timestamp) + out = it.util.cleanUpCode(out); - return date -} + if ($top) { + out = it.util.finalCleanUpCode(out, $async); + } -// TODO: buffer, offset compatibility -Block.prototype.toBuffer = function (headersOnly) { - var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)) + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; - var offset = 0 - function writeSlice (slice) { - slice.copy(buffer, offset) - offset += slice.length + for (var i = 0; i < rules.length; i++) { + if ($shouldUseRule(rules[i])) return true; + } } - function writeInt32 (i) { - buffer.writeInt32LE(i, offset) - offset += 4 - } - function writeUInt32 (i) { - buffer.writeUInt32LE(i, offset) - offset += 4 + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || $rule["implements"] && $ruleImplementsSomeKeyword($rule); } - writeInt32(this.version) - writeSlice(this.prevHash) - writeSlice(this.merkleRoot) - writeUInt32(this.timestamp) - writeUInt32(this.bits) - writeUInt32(this.nonce) + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule["implements"]; - if (headersOnly || !this.transactions) return buffer + for (var i = 0; i < impl.length; i++) { + if (it.schema[impl[i]] !== undefined) return true; + } + } - varuint.encode(this.transactions.length, buffer, offset) - offset += varuint.encode.bytes + return out; +}; - this.transactions.forEach(function (tx) { - var txSize = tx.byteLength() // TODO: extract from toBuffer? - tx.toBuffer(buffer, offset) - offset += txSize - }) +},{}],73:[function(require,module,exports){ +'use strict'; - return buffer -} +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; -Block.prototype.toHex = function (headersOnly) { - return this.toBuffer(headersOnly).toString('hex') -} +var customRuleCode = require('./dotjs/custom'); -Block.calculateTarget = function (bits) { - var exponent = ((bits & 0xff000000) >> 24) - 3 - var mantissa = bits & 0x007fffff - var target = Buffer.alloc(32, 0) - target.writeUInt32BE(mantissa, 28 - exponent) - return target -} +var metaSchema = require('./refs/json-schema-draft-07.json'); -Block.calculateMerkleRoot = function (transactions) { - typeforce([{ getHash: types.Function }], transactions) - if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions') +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; +var definitionSchema = { + definitions: { + simpleTypes: metaSchema.definitions.simpleTypes + }, + type: 'object', + dependencies: { + schema: ['validate'], + $data: ['validate'], + statements: ['inline'], + valid: { + not: { + required: ['macro'] + } + } + }, + properties: { + type: metaSchema.properties.type, + schema: { + type: 'boolean' + }, + statements: { + type: 'boolean' + }, + dependencies: { + type: 'array', + items: { + type: 'string' + } + }, + metaSchema: { + type: 'object' + }, + modifying: { + type: 'boolean' + }, + valid: { + type: 'boolean' + }, + $data: { + type: 'boolean' + }, + async: { + type: 'boolean' + }, + errors: { + anyOf: [{ + type: 'boolean' + }, { + "const": 'full' + }] + } + } +}; +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ - var hashes = transactions.map(function (transaction) { - return transaction.getHash() - }) +function addKeyword(keyword, definition) { + /* jshint validthis: true */ - return fastMerkleRoot(hashes, bcrypto.hash256) -} + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined'); + if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier'); -Block.prototype.checkMerkleRoot = function () { - if (!this.transactions) return false + if (definition) { + this.validateKeyword(definition, true); + var dataType = definition.type; - var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions) - return this.merkleRoot.compare(actualMerkleRoot) === 0 -} + if (Array.isArray(dataType)) { + for (var i = 0; i < dataType.length; i++) { + _addRule(keyword, dataType[i], definition); + } + } else { + _addRule(keyword, dataType, definition); + } -Block.prototype.checkProofOfWork = function () { - var hash = this.getHash().reverse() - var target = Block.calculateTarget(this.bits) + var metaSchema = definition.metaSchema; - return hash.compare(target) <= 0 -} + if (metaSchema) { + if (definition.$data && this._opts.$data) { + metaSchema = { + anyOf: [metaSchema, { + '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' + }] + }; + } -module.exports = Block + definition.validateSchema = this.compile(metaSchema, true); + } + } -},{"./crypto":87,"./transaction":118,"./types":120,"merkle-lib/fastRoot":947,"safe-buffer":1256,"typeforce":1318,"varuint-bitcoin":1334}],86:[function(require,module,exports){ -var pushdata = require('pushdata-bitcoin') -var varuint = require('varuint-bitcoin') + RULES.keywords[keyword] = RULES.all[keyword] = true; -// https://github.com/feross/buffer/blob/master/index.js#L1127 -function verifuint (value, max) { - if (typeof value !== 'number') throw new Error('cannot write a non-number as a number') - if (value < 0) throw new Error('specified a negative value for writing an unsigned value') - if (value > max) throw new Error('RangeError: value out of range') - if (Math.floor(value) !== value) throw new Error('value has a fractional component') -} + function _addRule(keyword, dataType, definition) { + var ruleGroup; -function readUInt64LE (buffer, offset) { - var a = buffer.readUInt32LE(offset) - var b = buffer.readUInt32LE(offset + 4) - b *= 0x100000000 + for (var i = 0; i < RULES.length; i++) { + var rg = RULES[i]; - verifuint(b + a, 0x001fffffffffffff) + if (rg.type == dataType) { + ruleGroup = rg; + break; + } + } - return b + a -} + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.push(ruleGroup); + } -function writeUInt64LE (buffer, value, offset) { - verifuint(value, 0x001fffffffffffff) + var rule = { + keyword: keyword, + definition: definition, + custom: true, + code: customRuleCode, + "implements": definition["implements"] + }; + ruleGroup.rules.push(rule); + RULES.custom[keyword] = rule; + } - buffer.writeInt32LE(value & -1, offset) - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4) - return offset + 8 + return this; } +/** + * Get keyword + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. + */ -// TODO: remove in 4.0.0? -function readVarInt (buffer, offset) { - var result = varuint.decode(buffer, offset) - return { - number: result, - size: varuint.decode.bytes - } +function getKeyword(keyword) { + /* jshint validthis: true */ + var rule = this.RULES.custom[keyword]; + return rule ? rule.definition : this.RULES.keywords[keyword] || false; } +/** + * Remove keyword + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + * @return {Ajv} this for method chaining + */ -// TODO: remove in 4.0.0? -function writeVarInt (buffer, number, offset) { - varuint.encode(number, buffer, offset) - return varuint.encode.bytes -} -module.exports = { - pushDataSize: pushdata.encodingLength, - readPushDataInt: pushdata.decode, - readUInt64LE: readUInt64LE, - readVarInt: readVarInt, - varIntBuffer: varuint.encode, - varIntSize: varuint.encodingLength, - writePushDataInt: pushdata.encode, - writeUInt64LE: writeUInt64LE, - writeVarInt: writeVarInt -} +function removeKeyword(keyword) { + /* jshint validthis: true */ + var RULES = this.RULES; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + delete RULES.custom[keyword]; -},{"pushdata-bitcoin":1221,"varuint-bitcoin":1334}],87:[function(require,module,exports){ -var createHash = require('create-hash') + for (var i = 0; i < RULES.length; i++) { + var rules = RULES[i].rules; -function ripemd160 (buffer) { - return createHash('rmd160').update(buffer).digest() -} + for (var j = 0; j < rules.length; j++) { + if (rules[j].keyword == keyword) { + rules.splice(j, 1); + break; + } + } + } -function sha1 (buffer) { - return createHash('sha1').update(buffer).digest() + return this; } +/** + * Validate keyword definition + * @this Ajv + * @param {Object} definition keyword definition object. + * @param {Boolean} throwError true to throw exception if definition is invalid + * @return {boolean} validation result + */ -function sha256 (buffer) { - return createHash('sha256').update(buffer).digest() + +function validateKeyword(definition, throwError) { + validateKeyword.errors = null; + var v = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true); + if (v(definition)) return true; + validateKeyword.errors = v.errors; + if (throwError) throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));else return false; } -function hash160 (buffer) { - return ripemd160(sha256(buffer)) +},{"./dotjs/custom":56,"./refs/json-schema-draft-07.json":76}],74:[function(require,module,exports){ +module.exports={ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON Schema extension proposal)", + "type": "object", + "required": [ "$data" ], + "properties": { + "$data": { + "type": "string", + "anyOf": [ + { "format": "relative-json-pointer" }, + { "format": "json-pointer" } + ] + } + }, + "additionalProperties": false } -function hash256 (buffer) { - return sha256(sha256(buffer)) +},{}],75:[function(require,module,exports){ +module.exports={ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "examples": { + "type": "array", + "items": {} + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "propertyNames": { "$ref": "#" }, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": {} } -module.exports = { - hash160: hash160, - hash256: hash256, - ripemd160: ripemd160, - sha1: sha1, - sha256: sha256 +},{}],76:[function(require,module,exports){ +module.exports={ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true } -},{"create-hash":167}],88:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var createHmac = require('create-hmac') -var typeforce = require('typeforce') -var types = require('./types') +},{}],77:[function(require,module,exports){ +'use strict'; +/** + * Expose `arrayFlatten`. + */ + +module.exports = arrayFlatten; +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ -var BigInteger = require('bigi') -var ECSignature = require('./ecsignature') +function flattenWithDepth(array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; -var ZERO = Buffer.alloc(1, 0) -var ONE = Buffer.alloc(1, 1) + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1); + } else { + result.push(value); + } + } -var ecurve = require('ecurve') -var secp256k1 = ecurve.getCurveByName('secp256k1') + return result; +} +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ -// https://tools.ietf.org/html/rfc6979#section-3.2 -function deterministicGenerateK (hash, x, checkSig) { - typeforce(types.tuple( - types.Hash256bit, - types.Buffer256bit, - types.Function - ), arguments) - // Step A, ignored as hash already provided - // Step B - // Step C - var k = Buffer.alloc(32, 0) - var v = Buffer.alloc(32, 1) - - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO) - .update(x) - .update(hash) - .digest() - - // Step E - v = createHmac('sha256', k).update(v).digest() - - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE) - .update(x) - .update(hash) - .digest() - - // Step G - v = createHmac('sha256', k).update(v).digest() - - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest() +function flattenForever(array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; - var T = BigInteger.fromBuffer(v) + if (Array.isArray(value)) { + flattenForever(value, result); + } else { + result.push(value); + } + } - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (T.signum() <= 0 || T.compareTo(secp256k1.n) >= 0 || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO) - .digest() + return result; +} +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ - v = createHmac('sha256', k).update(v).digest() - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest() - T = BigInteger.fromBuffer(v) +function arrayFlatten(array, depth) { + if (depth == null) { + return flattenForever(array, []); } - return T + return flattenWithDepth(array, [], depth); } -var N_OVER_TWO = secp256k1.n.shiftRight(1) - -function sign (hash, d) { - typeforce(types.tuple(types.Hash256bit, types.BigInt), arguments) +},{}],78:[function(require,module,exports){ +'use strict'; - var x = d.toBuffer(32) - var e = BigInteger.fromBuffer(hash) - var n = secp256k1.n - var G = secp256k1.G +var asn1 = exports; +asn1.bignum = require('bn.js'); +asn1.define = require('./asn1/api').define; +asn1.base = require('./asn1/base'); +asn1.constants = require('./asn1/constants'); +asn1.decoders = require('./asn1/decoders'); +asn1.encoders = require('./asn1/encoders'); - var r, s - deterministicGenerateK(hash, x, function (k) { - var Q = G.multiply(k) +},{"./asn1/api":79,"./asn1/base":81,"./asn1/constants":85,"./asn1/decoders":87,"./asn1/encoders":90,"bn.js":237}],79:[function(require,module,exports){ +'use strict'; - if (secp256k1.isInfinity(Q)) return false +var encoders = require('./encoders'); - r = Q.affineX.mod(n) - if (r.signum() === 0) return false +var decoders = require('./decoders'); - s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n) - if (s.signum() === 0) return false +var inherits = require('inherits'); - return true - }) +var api = exports; - // enforce low S values, see bip62: 'low s values in signatures' - if (s.compareTo(N_OVER_TWO) > 0) { - s = n.subtract(s) - } +api.define = function define(name, body) { + return new Entity(name, body); +}; - return new ECSignature(r, s) +function Entity(name, body) { + this.name = name; + this.body = body; + this.decoders = {}; + this.encoders = {}; } -function verify (hash, signature, Q) { - typeforce(types.tuple( - types.Hash256bit, - types.ECSignature, - types.ECPoint - ), arguments) +Entity.prototype._createNamed = function createNamed(Base) { + var name = this.name; - var n = secp256k1.n - var G = secp256k1.G + function Generated(entity) { + this._initNamed(entity, name); + } - var r = signature.r - var s = signature.s + inherits(Generated, Base); - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] - if (r.signum() <= 0 || r.compareTo(n) >= 0) return false - if (s.signum() <= 0 || s.compareTo(n) >= 0) return false + Generated.prototype._initNamed = function _initNamed(entity, name) { + Base.call(this, entity, name); + }; - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - var e = BigInteger.fromBuffer(hash) + return new Generated(this); +}; - // Compute s^-1 - var sInv = s.modInverse(n) +Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || 'der'; // Lazily create decoder - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - var u1 = e.multiply(sInv).mod(n) - var u2 = r.multiply(sInv).mod(n) + if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(decoders[enc]); + return this.decoders[enc]; +}; - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - var R = G.multiplyTwo(u1, Q, u2) +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; - // 1.4.5 (cont.) Enforce R is not at infinity - if (secp256k1.isInfinity(R)) return false +Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || 'der'; // Lazily create encoder - // 1.4.6 Convert the field element R.x to an integer - var xR = R.affineX + if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(encoders[enc]); + return this.encoders[enc]; +}; - // 1.4.7 Set v = xR mod n - var v = xR.mod(n) +Entity.prototype.encode = function encode(data, enc, +/* internal */ +reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.equals(r) -} +},{"./decoders":87,"./encoders":90,"inherits":974}],80:[function(require,module,exports){ +'use strict'; -module.exports = { - deterministicGenerateK: deterministicGenerateK, - sign: sign, - verify: verify, +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - // TODO: remove - __curve: secp256k1 -} +var inherits = require('inherits'); -},{"./ecsignature":90,"./types":120,"bigi":77,"create-hmac":168,"ecurve":205,"safe-buffer":1256,"typeforce":1318}],89:[function(require,module,exports){ -var baddress = require('./address') -var bcrypto = require('./crypto') -var ecdsa = require('./ecdsa') -var randomBytes = require('randombytes') -var typeforce = require('typeforce') -var types = require('./types') -var wif = require('wif') +var Reporter = require('../base/reporter').Reporter; -var NETWORKS = require('./networks') -var BigInteger = require('bigi') +var Buffer = require('buffer').Buffer; -var ecurve = require('ecurve') -var secp256k1 = ecdsa.__curve +function DecoderBuffer(base, options) { + Reporter.call(this, options); -function ECPair (d, Q, options) { - if (options) { - typeforce({ - compressed: types.maybe(types.Boolean), - network: types.maybe(types.Network) - }, options) + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; } - options = options || {} + this.base = base; + this.offset = 0; + this.length = base.length; +} - if (d) { - if (d.signum() <= 0) throw new Error('Private key must be greater than 0') - if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order') - if (Q) throw new TypeError('Unexpected publicKey parameter') +inherits(DecoderBuffer, Reporter); +exports.DecoderBuffer = DecoderBuffer; - this.d = d - } else { - typeforce(types.ECPoint, Q) +DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { + if (data instanceof DecoderBuffer) { + return true; + } // Or accept compatible API - this.__Q = Q - } - this.compressed = options.compressed === undefined ? true : options.compressed - this.network = options.network || NETWORKS.bitcoin -} + var isCompatible = _typeof(data) === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function'; + return isCompatible; +}; -Object.defineProperty(ECPair.prototype, 'Q', { - get: function () { - if (!this.__Q && this.d) { - this.__Q = secp256k1.G.multiply(this.d) - } +DecoderBuffer.prototype.save = function save() { + return { + offset: this.offset, + reporter: Reporter.prototype.save.call(this) + }; +}; - return this.__Q - } -}) +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + return res; +}; -ECPair.fromPublicKeyBuffer = function (buffer, network) { - var Q = ecurve.Point.decodeFrom(secp256k1, buffer) +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; - return new ECPair(null, Q, { - compressed: Q.compressed, - network: network - }) -} +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true);else return this.error(fail || 'DecoderBuffer overrun'); +}; -ECPair.fromWIF = function (string, network) { - var decoded = wif.decode(string) - var version = decoded.version +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); + var res = new DecoderBuffer(this.base); // Share reporter state - // list of networks? - if (types.Array(network)) { - network = network.filter(function (x) { - return version === x.wif - }).pop() + res._reporterState = this._reporterState; + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +}; - if (!network) throw new Error('Unknown network version') +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +}; - // otherwise, assume a network object (or default to bitcoin) +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function (item) { + if (!EncoderBuffer.isEncoderBuffer(item)) item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; } else { - network = network || NETWORKS.bitcoin - - if (version !== network.wif) throw new Error('Invalid network version') + return reporter.error('Unsupported type: ' + _typeof(value)); } - - var d = BigInteger.fromBuffer(decoded.privateKey) - - return new ECPair(d, null, { - compressed: decoded.compressed, - network: network - }) } -ECPair.makeRandom = function (options) { - options = options || {} +exports.EncoderBuffer = EncoderBuffer; - var rng = options.rng || randomBytes +EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { + if (data instanceof EncoderBuffer) { + return true; + } // Or accept compatible API - var d - do { - var buffer = rng(32) - typeforce(types.Buffer256bit, buffer) - d = BigInteger.fromBuffer(buffer) - } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0) + var isCompatible = _typeof(data) === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function'; + return isCompatible; +}; - return new ECPair(d, null, options) -} +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) out = new Buffer(this.length); + if (!offset) offset = 0; + if (this.length === 0) return out; -ECPair.prototype.getAddress = function () { - return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash) -} + if (Array.isArray(this.value)) { + this.value.forEach(function (item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') out[offset] = this.value;else if (typeof this.value === 'string') out.write(this.value, offset);else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset); + offset += this.length; + } -ECPair.prototype.getNetwork = function () { - return this.network -} + return out; +}; -ECPair.prototype.getPublicKeyBuffer = function () { - return this.Q.getEncoded(this.compressed) -} +},{"../base/reporter":83,"buffer":undefined,"inherits":974}],81:[function(require,module,exports){ +'use strict'; -ECPair.prototype.sign = function (hash) { - if (!this.d) throw new Error('Missing private key') +var base = exports; +base.Reporter = require('./reporter').Reporter; +base.DecoderBuffer = require('./buffer').DecoderBuffer; +base.EncoderBuffer = require('./buffer').EncoderBuffer; +base.Node = require('./node'); - return ecdsa.sign(hash, this.d) -} +},{"./buffer":80,"./node":82,"./reporter":83}],82:[function(require,module,exports){ +'use strict'; -ECPair.prototype.toWIF = function () { - if (!this.d) throw new Error('Missing private key') +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed) -} +var Reporter = require('../base/reporter').Reporter; -ECPair.prototype.verify = function (hash, signature) { - return ecdsa.verify(hash, signature, this.Q) -} +var EncoderBuffer = require('../base/buffer').EncoderBuffer; -module.exports = ECPair +var DecoderBuffer = require('../base/buffer').DecoderBuffer; -},{"./address":84,"./crypto":87,"./ecdsa":88,"./networks":93,"./types":120,"bigi":77,"ecurve":205,"randombytes":1228,"typeforce":1318,"wif":1336}],90:[function(require,module,exports){ -var bip66 = require('bip66') -var typeforce = require('typeforce') -var types = require('./types') +var assert = require('minimalistic-assert'); // Supported tags -var BigInteger = require('bigi') -function ECSignature (r, s) { - typeforce(types.tuple(types.BigInt, types.BigInt), arguments) +var tags = ['seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr']; // Public methods list - this.r = r - this.s = s -} +var methods = ['key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains'].concat(tags); // Overrided methods list + +var overrided = ['_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool']; -ECSignature.parseCompact = function (buffer) { - typeforce(types.BufferN(65), buffer) +function Node(enc, parent, name) { + var state = {}; + this._baseState = state; + state.name = name; + state.enc = enc; + state.parent = parent || null; + state.children = null; // State - var flagByte = buffer.readUInt8(0) - 27 - if (flagByte !== (flagByte & 7)) throw new Error('Invalid signature parameter') + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; // Should create new instance on each method - var compressed = !!(flagByte & 4) - var recoveryParam = flagByte & 3 - var signature = ECSignature.fromRSBuffer(buffer.slice(1)) + if (!state.parent) { + state.children = []; - return { - compressed: compressed, - i: recoveryParam, - signature: signature + this._wrap(); } } -ECSignature.fromRSBuffer = function (buffer) { - typeforce(types.BufferN(64), buffer) +module.exports = Node; +var stateProps = ['enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains']; - var r = BigInteger.fromBuffer(buffer.slice(0, 32)) - var s = BigInteger.fromBuffer(buffer.slice(32, 64)) - return new ECSignature(r, s) -} +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function (prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; -ECSignature.fromDER = function (buffer) { - var decode = bip66.decode(buffer) - var r = BigInteger.fromDERInteger(decode.r) - var s = BigInteger.fromDERInteger(decode.s) +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function (method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; - return new ECSignature(r, s) -} +Node.prototype._init = function init(body) { + var state = this._baseState; + assert(state.parent === null); + body.call(this); // Filter children -// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) -ECSignature.parseScriptSignature = function (buffer) { - var hashType = buffer.readUInt8(buffer.length - 1) - var hashTypeMod = hashType & ~0x80 + state.children = state.children.filter(function (child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; - if (hashTypeMod <= 0x00 || hashTypeMod >= 0x04) throw new Error('Invalid hashType ' + hashType) +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; // Filter children and args - return { - signature: ECSignature.fromDER(buffer.slice(0, -1)), - hashType: hashType + var children = args.filter(function (arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function (arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; // Replace parent to maintain backward link + + children.forEach(function (child) { + child._baseState.parent = this; + }, this); } -} -ECSignature.prototype.toCompact = function (i, compressed) { - if (compressed) { - i += 4 + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function (arg) { + if (_typeof(arg) !== 'object' || arg.constructor !== Object) return arg; + var res = {}; + Object.keys(arg).forEach(function (key) { + if (key == (key | 0)) key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); } +}; // +// Overrided methods +// - i += 27 - var buffer = Buffer.alloc(65) - buffer.writeUInt8(i, 0) - this.toRSBuffer(buffer, 1) - return buffer -} +overrided.forEach(function (method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); // +// Public methods +// -ECSignature.prototype.toDER = function () { - var r = Buffer.from(this.r.toDERInteger()) - var s = Buffer.from(this.s.toDERInteger()) +tags.forEach(function (tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + assert(state.tag === null); + state.tag = tag; - return bip66.encode(r, s) -} + this._useArgs(args); -ECSignature.prototype.toRSBuffer = function (buffer, offset) { - buffer = buffer || Buffer.alloc(64) - this.r.toBuffer(32).copy(buffer, offset) - this.s.toBuffer(32).copy(buffer, offset + 32) - return buffer -} + return this; + }; +}); -ECSignature.prototype.toScriptSignature = function (hashType) { - var hashTypeMod = hashType & ~0x80 - if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType) +Node.prototype.use = function use(item) { + assert(item); + var state = this._baseState; + assert(state.use === null); + state.use = item; + return this; +}; - var hashTypeBuffer = Buffer.alloc(1) - hashTypeBuffer.writeUInt8(hashType, 0) +Node.prototype.optional = function optional() { + var state = this._baseState; + state.optional = true; + return this; +}; - return Buffer.concat([this.toDER(), hashTypeBuffer]) -} +Node.prototype.def = function def(val) { + var state = this._baseState; + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + return this; +}; -module.exports = ECSignature +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + return this; +}; -},{"./types":120,"bigi":77,"bip66":81,"typeforce":1318}],91:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var base58check = require('bs58check') -var bcrypto = require('./crypto') -var createHmac = require('create-hmac') -var typeforce = require('typeforce') -var types = require('./types') -var NETWORKS = require('./networks') +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + return this; +}; -var BigInteger = require('bigi') -var ECPair = require('./ecpair') +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + state.obj = true; + if (args.length !== 0) this._useArgs(args); + return this; +}; -var ecurve = require('ecurve') -var curve = ecurve.getCurveByName('secp256k1') +Node.prototype.key = function key(newKey) { + var state = this._baseState; + assert(state.key === null); + state.key = newKey; + return this; +}; -function HDNode (keyPair, chainCode) { - typeforce(types.tuple('ECPair', types.Buffer256bit), arguments) +Node.prototype.any = function any() { + var state = this._baseState; + state.any = true; + return this; +}; - if (!keyPair.compressed) throw new TypeError('BIP32 only allows compressed keyPairs') +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + assert(state.choice === null); + state.choice = obj; - this.keyPair = keyPair - this.chainCode = chainCode - this.depth = 0 - this.index = 0 - this.parentFingerprint = 0x00000000 -} + this._useArgs(Object.keys(obj).map(function (key) { + return obj[key]; + })); -HDNode.HIGHEST_BIT = 0x80000000 -HDNode.LENGTH = 78 -HDNode.MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8') + return this; +}; -HDNode.fromSeedBuffer = function (seed, network) { - typeforce(types.tuple(types.Buffer, types.maybe(types.Network)), arguments) +Node.prototype.contains = function contains(item) { + var state = this._baseState; + assert(state.use === null); + state.contains = item; + return this; +}; // +// Decoding +// - if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits') - if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits') - var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest() - var IL = I.slice(0, 32) - var IR = I.slice(32) +Node.prototype._decode = function decode(input, options) { + var state = this._baseState; // Decode root node - // In case IL is 0 or >= n, the master key is invalid - // This is handled by the ECPair constructor - var pIL = BigInteger.fromBuffer(IL) - var keyPair = new ECPair(pIL, null, { - network: network - }) + if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); + var result = state['default']; + var present = true; + var prevKey = null; + if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there - return new HDNode(keyPair, IR) -} + if (state.optional) { + var tag = null; + if (state.explicit !== null) tag = state.explicit;else if (state.implicit !== null) tag = state.implicit;else if (state.tag !== null) tag = state.tag; -HDNode.fromSeedHex = function (hex, network) { - return HDNode.fromSeedBuffer(Buffer.from(hex, 'hex'), network) -} + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); -HDNode.fromBase58 = function (string, networks) { - var buffer = base58check.decode(string) - if (buffer.length !== 78) throw new Error('Invalid buffer length') + try { + if (state.choice === null) this._decodeGeneric(state.tag, input, options);else this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } - // 4 bytes: version bytes - var version = buffer.readUInt32BE(0) - var network + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + if (input.isError(present)) return present; + } + } // Push object on stack - // list of networks? - if (Array.isArray(networks)) { - network = networks.filter(function (x) { - return version === x.bip32.private || - version === x.bip32.public - }).pop() - if (!network) throw new Error('Unknown network version') + var prevObj; + if (state.obj && present) prevObj = input.enterObject(); - // otherwise, assume a network object (or default to bitcoin) - } else { - network = networks || NETWORKS.bitcoin - } + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); - if (version !== network.bip32.private && - version !== network.bip32.public) throw new Error('Invalid network version') + if (input.isError(explicit)) return explicit; + input = explicit; + } - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - var depth = buffer[4] + var start = input.offset; // Unwrap implicit and normal values - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - var parentFingerprint = buffer.readUInt32BE(5) - if (depth === 0) { - if (parentFingerprint !== 0x00000000) throw new Error('Invalid parent fingerprint') - } + if (state.use === null && state.choice === null) { + var _save; - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - var index = buffer.readUInt32BE(9) - if (depth === 0 && index !== 0) throw new Error('Invalid index') + if (state.any) _save = input.save(); - // 32 bytes: the chain code - var chainCode = buffer.slice(13, 45) - var keyPair + var body = this._decodeTag(input, state.implicit !== null ? state.implicit : state.tag, state.any); - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key') + if (input.isError(body)) return body; + if (state.any) result = input.raw(_save);else input = body; + } - var d = BigInteger.fromBuffer(buffer.slice(46, 78)) - keyPair = new ECPair(d, null, { network: network }) + if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); + if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag - // 33 bytes: public key data (0x02 + X or 0x03 + X) - } else { - var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78)) - // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw + if (state.any) {// no-op + } else if (state.choice === null) { + result = this._decodeGeneric(state.tag, input, options); + } else { + result = this._decodeChoice(input, options); + } - // Verify that the X coordinate in the public point corresponds to a point on the curve. - // If not, the extended public key is invalid. - curve.validate(Q) + if (input.isError(result)) return result; // Decode children - keyPair = new ECPair(null, Q, { network: network }) - } + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } // Decode contained/encoded by schema, only in bit or octet strings - var hd = new HDNode(keyPair, chainCode) - hd.depth = depth - hd.index = index - hd.parentFingerprint = parentFingerprint - return hd -} + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj)._decode(data, options); + } + } // Pop object -HDNode.prototype.getAddress = function () { - return this.keyPair.getAddress() -} -HDNode.prototype.getIdentifier = function () { - return bcrypto.hash160(this.keyPair.getPublicKeyBuffer()) -} + if (state.obj && present) result = input.leaveObject(prevObj); // Set key -HDNode.prototype.getFingerprint = function () { - return this.getIdentifier().slice(0, 4) -} + if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result);else if (prevKey !== null) input.exitKey(prevKey); + return result; +}; -HDNode.prototype.getNetwork = function () { - return this.keyPair.getNetwork() -} +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + var state = this._baseState; + if (tag === 'seq' || tag === 'set') return null; + if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options);else if (/str$/.test(tag)) return this._decodeStr(input, tag, options);else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options);else if (tag === 'objid') return this._decodeObjid(input, null, null, options);else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options);else if (tag === 'null_') return this._decodeNull(input, options);else if (tag === 'bool') return this._decodeBool(input, options);else if (tag === 'objDesc') return this._decodeStr(input, tag, options);else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); -HDNode.prototype.getPublicKeyBuffer = function () { - return this.keyPair.getPublicKeyBuffer() -} + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj)._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; -HDNode.prototype.neutered = function () { - var neuteredKeyPair = new ECPair(null, this.keyPair.Q, { - network: this.keyPair.network - }) +Node.prototype._getUse = function _getUse(entity, obj) { + var state = this._baseState; // Create altered use decoder if implicit is set - var neutered = new HDNode(neuteredKeyPair, this.chainCode) - neutered.depth = this.depth - neutered.index = this.index - neutered.parentFingerprint = this.parentFingerprint + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; - return neutered -} + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } -HDNode.prototype.sign = function (hash) { - return this.keyPair.sign(hash) -} + return state.useDecoder; +}; -HDNode.prototype.verify = function (hash, signature) { - return this.keyPair.verify(hash, signature) -} +Node.prototype._decodeChoice = function decodeChoice(input, options) { + var state = this._baseState; + var result = null; + var match = false; + Object.keys(state.choice).some(function (key) { + var save = input.save(); + var node = state.choice[key]; -HDNode.prototype.toBase58 = function (__isPrivate) { - if (__isPrivate !== undefined) throw new TypeError('Unsupported argument in 2.0.0') + try { + var value = node._decode(input, options); - // Version - var network = this.keyPair.network - var version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public - var buffer = Buffer.allocUnsafe(78) + if (input.isError(value)) return false; + result = { + type: key, + value: value + }; + match = true; + } catch (e) { + input.restore(save); + return false; + } - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0) + return true; + }, this); + if (!match) return input.error('Choice not matched'); + return result; +}; // +// Encoding +// - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4) - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5) +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9) +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) return; - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13) + var result = this._encodeValue(data, reporter, parent); - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45) - this.keyPair.d.toBuffer(32).copy(buffer, 46) + if (result === undefined) return; + if (this._skipDefault(result, reporter, parent)) return; + return result; +}; - // 33 bytes: the public key - } else { - // X9.62 encoding for public keys - this.keyPair.getPublicKeyBuffer().copy(buffer, 45) - } +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; // Decode root node - return base58check.encode(buffer) -} + if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); + var result = null; // Set reporter to share it with a child class -// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions -HDNode.prototype.derive = function (index) { - typeforce(types.UInt32, index) + this.reporter = reporter; // Check if data is there - var isHardened = index >= HDNode.HIGHEST_BIT - var data = Buffer.allocUnsafe(37) + if (state.optional && data === undefined) { + if (state['default'] !== null) data = state['default'];else return; + } // Encode children first - // Hardened child - if (isHardened) { - if (this.isNeutered()) throw new TypeError('Could not derive hardened child key') - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00 - this.keyPair.d.toBuffer(32).copy(data, 1) - data.writeUInt32BE(index, 33) + var content = null; + var primitive = false; - // Normal child - } else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.keyPair.getPublicKeyBuffer().copy(data, 0) - data.writeUInt32BE(index, 33) - } + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function (child) { + if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); + if (child._baseState.key === null) return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + if (_typeof(data) !== 'object') return reporter.error('Child expected, but input is not object'); - var I = createHmac('sha512', this.chainCode).update(data).digest() - var IL = I.slice(0, 32) - var IR = I.slice(32) + var res = child._encode(data[child._baseState.key], reporter, data); - var pIL = BigInteger.fromBuffer(IL) + reporter.leaveKey(prevKey); + return res; + }, this).filter(function (child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); + if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function (item) { + var state = this._baseState; + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } // Encode data itself - // In case parse256(IL) >= n, proceed with the next value for i - if (pIL.compareTo(curve.n) >= 0) { - return this.derive(index + 1) - } - // Private parent key -> private child key - var derivedKeyPair - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - var ki = pIL.add(this.keyPair.d).mod(curve.n) + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; - // In case ki == 0, proceed with the next value for i - if (ki.signum() === 0) { - return this.derive(index + 1) + if (tag === null) { + if (state.use === null) reporter.error('Tag could be omitted only for .use()'); + } else { + if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content); } + } // Wrap in explicit - derivedKeyPair = new ECPair(ki, null, { - network: this.keyPair.network - }) - // Public parent key -> public child key - } else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - var Ki = curve.G.multiply(pIL).add(this.keyPair.Q) + if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); + return result; +}; - // In case Ki is the point at infinity, proceed with the next value for i - if (curve.isInfinity(Ki)) { - return this.derive(index + 1) - } +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + var node = state.choice[data.type]; - derivedKeyPair = new ECPair(null, Ki, { - network: this.keyPair.network - }) + if (!node) { + assert(false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice))); } - var hd = new HDNode(derivedKeyPair, IR) - hd.depth = this.depth + 1 - hd.index = index - hd.parentFingerprint = this.getFingerprint().readUInt32BE(0) - - return hd -} - -HDNode.prototype.deriveHardened = function (index) { - typeforce(types.UInt31, index) + return node._encode(data.value, reporter); +}; - // Only derives hardened private keys by default - return this.derive(index + HDNode.HIGHEST_BIT) -} +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + if (/str$/.test(tag)) return this._encodeStr(data, tag);else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);else if (tag === 'objid') return this._encodeObjid(data, null, null);else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag);else if (tag === 'null_') return this._encodeNull();else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]);else if (tag === 'bool') return this._encodeBool(data);else if (tag === 'objDesc') return this._encodeStr(data, tag);else throw new Error('Unsupported tag: ' + tag); +}; -// Private === not neutered -// Public === neutered -HDNode.prototype.isNeutered = function () { - return !(this.keyPair.d) -} +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; -HDNode.prototype.derivePath = function (path) { - typeforce(types.BIP32Path, path) +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); +}; - var splitPath = path.split('/') - if (splitPath[0] === 'm') { - if (this.parentFingerprint) { - throw new Error('Not a master node') - } +},{"../base/buffer":80,"../base/reporter":83,"minimalistic-assert":2303}],83:[function(require,module,exports){ +'use strict'; - splitPath = splitPath.slice(1) - } +var inherits = require('inherits'); - return splitPath.reduce(function (prevHd, indexStr) { - var index - if (indexStr.slice(-1) === "'") { - index = parseInt(indexStr.slice(0, -1), 10) - return prevHd.deriveHardened(index) - } else { - index = parseInt(indexStr, 10) - return prevHd.derive(index) - } - }, this) +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; } -module.exports = HDNode +exports.Reporter = Reporter; -},{"./crypto":87,"./ecpair":89,"./networks":93,"./types":120,"bigi":77,"bs58check":149,"create-hmac":168,"ecurve":205,"safe-buffer":1256,"typeforce":1318}],92:[function(require,module,exports){ -var script = require('./script') +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; -var templates = require('./templates') -for (var key in templates) { - script[key] = templates[key] -} +Reporter.prototype.save = function save() { + var state = this._reporterState; + return { + obj: state.obj, + pathLen: state.path.length + }; +}; -module.exports = { - bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0 +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; - Block: require('./block'), - ECPair: require('./ecpair'), - ECSignature: require('./ecsignature'), - HDNode: require('./hdnode'), - Transaction: require('./transaction'), - TransactionBuilder: require('./transaction_builder'), +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; - address: require('./address'), - crypto: require('./crypto'), - networks: require('./networks'), - opcodes: require('bitcoin-ops'), - script: script -} +Reporter.prototype.exitKey = function exitKey(index) { + var state = this._reporterState; + state.path = state.path.slice(0, index - 1); +}; -},{"./address":84,"./block":85,"./bufferutils":86,"./crypto":87,"./ecpair":89,"./ecsignature":90,"./hdnode":91,"./networks":93,"./script":94,"./templates":96,"./transaction":118,"./transaction_builder":119,"bitcoin-ops":82}],93:[function(require,module,exports){ -// https://en.bitcoin.it/wiki/List_of_address_prefixes -// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + this.exitKey(index); + if (state.obj !== null) state.obj[key] = value; +}; -module.exports = { - bitcoin: { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4 - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80 - }, - testnet: { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394 - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef - }, - litecoin: { - messagePrefix: '\x19Litecoin Signed Message:\n', - bip32: { - public: 0x019da462, - private: 0x019d9cfe - }, - pubKeyHash: 0x30, - scriptHash: 0x32, - wif: 0xb0 - } -} +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; -},{}],94:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bip66 = require('bip66') -var pushdata = require('pushdata-bitcoin') -var typeforce = require('typeforce') -var types = require('./types') -var scriptNumber = require('./script_number') +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + var prev = state.obj; + state.obj = {}; + return prev; +}; -var OPS = require('bitcoin-ops') -var REVERSE_OPS = require('bitcoin-ops/map') -var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + var now = state.obj; + state.obj = prev; + return now; +}; -function isOPInt (value) { - return types.Number(value) && - ((value === OPS.OP_0) || - (value >= OPS.OP_1 && value <= OPS.OP_16) || - (value === OPS.OP_1NEGATE)) -} +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + var inherited = msg instanceof ReporterError; -function isPushOnlyChunk (value) { - return types.Buffer(value) || isOPInt(value) -} + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function (elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } -function isPushOnly (value) { - return types.Array(value) && value.every(isPushOnlyChunk) -} + if (!state.options.partial) throw err; + if (!inherited) state.errors.push(err); + return err; +}; -function asMinimalOP (buffer) { - if (buffer.length === 0) return OPS.OP_0 - if (buffer.length !== 1) return - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0] - if (buffer[0] === 0x81) return OPS.OP_1NEGATE -} +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) return result; + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; -function compile (chunks) { - // TODO: remove me - if (Buffer.isBuffer(chunks)) return chunks +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +} - typeforce(types.Array, chunks) +inherits(ReporterError, Error); - var bufferSize = chunks.reduce(function (accum, chunk) { - // data chunk - if (Buffer.isBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1 - } +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError); - return accum + pushdata.encodingLength(chunk.length) + chunk.length + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; } + } - // opcode - return accum + 1 - }, 0.0) + return this; +}; - var buffer = Buffer.allocUnsafe(bufferSize) - var offset = 0 +},{"inherits":974}],84:[function(require,module,exports){ +'use strict'; // Helper - chunks.forEach(function (chunk) { - // data chunk - if (Buffer.isBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - var opcode = asMinimalOP(chunk) - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset) - offset += 1 - return - } +function reverse(map) { + var res = {}; + Object.keys(map).forEach(function (key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) key = key | 0; + var value = map[key]; + res[value] = key; + }); + return res; +} - offset += pushdata.encode(buffer, chunk.length, offset) - chunk.copy(buffer, offset) - offset += chunk.length +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = reverse(exports.tagClass); +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = reverse(exports.tag); - // opcode - } else { - buffer.writeUInt8(chunk, offset) - offset += 1 - } - }) +},{}],85:[function(require,module,exports){ +'use strict'; - if (offset !== buffer.length) throw new Error('Could not decode chunks') - return buffer -} +var constants = exports; // Helper -function decompile (buffer) { - // TODO: remove me - if (types.Array(buffer)) return buffer +constants._reverse = function reverse(map) { + var res = {}; + Object.keys(map).forEach(function (key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) key = key | 0; + var value = map[key]; + res[value] = key; + }); + return res; +}; - typeforce(types.Buffer, buffer) +constants.der = require('./der'); - var chunks = [] - var i = 0 +},{"./der":84}],86:[function(require,module,exports){ +'use strict'; - while (i < buffer.length) { - var opcode = buffer[i] +var inherits = require('inherits'); - // data chunk - if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) { - var d = pushdata.decode(buffer, i) +var bignum = require('bn.js'); - // did reading a pushDataInt fail? empty script - if (d === null) return [] - i += d.size +var DecoderBuffer = require('../base/buffer').DecoderBuffer; - // attempt to read too much data? empty script - if (i + d.number > buffer.length) return [] +var Node = require('../base/node'); // Import DER constants - var data = buffer.slice(i, i + d.number) - i += d.number - // decompile minimally - var op = asMinimalOP(data) - if (op !== undefined) { - chunks.push(op) - } else { - chunks.push(data) - } +var der = require('../constants/der'); - // opcode - } else { - chunks.push(opcode) +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; // Construct base tree - i += 1 - } - } + this.tree = new DERNode(); - return chunks + this.tree._init(entity.body); } -function toASM (chunks) { - if (Buffer.isBuffer(chunks)) { - chunks = decompile(chunks) - } - - return chunks.map(function (chunk) { - // data? - if (Buffer.isBuffer(chunk)) { - var op = asMinimalOP(chunk) - if (op === undefined) return chunk.toString('hex') - chunk = op - } +module.exports = DERDecoder; - // opcode! - return REVERSE_OPS[chunk] - }).join(' ') -} +DERDecoder.prototype.decode = function decode(data, options) { + if (!DecoderBuffer.isDecoderBuffer(data)) { + data = new DecoderBuffer(data, options); + } -function fromASM (asm) { - typeforce(types.String, asm) + return this.tree._decode(data, options); +}; // Tree methods - return compile(asm.split(' ').map(function (chunkStr) { - // opcode? - if (OPS[chunkStr] !== undefined) return OPS[chunkStr] - typeforce(types.Hex, chunkStr) - // data! - return Buffer.from(chunkStr, 'hex') - })) +function DERNode(parent) { + Node.call(this, 'der', parent); } -function toStack (chunks) { - chunks = decompile(chunks) - typeforce(isPushOnly, chunks) +inherits(DERNode, Node); - return chunks.map(function (op) { - if (Buffer.isBuffer(op)) return op - if (op === OPS.OP_0) return Buffer.allocUnsafe(0) +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) return false; + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) return decodedTag; + buffer.restore(state); + return decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + 'of' === tag || any; +}; - return scriptNumber.encode(op - OP_INT_BASE) - }) -} +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) return decodedTag; + var len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); // Failure -function isCanonicalPubKey (buffer) { - if (!Buffer.isBuffer(buffer)) return false - if (buffer.length < 33) return false + if (buffer.isError(len)) return len; - switch (buffer[0]) { - case 0x02: - case 0x03: - return buffer.length === 33 - case 0x04: - return buffer.length === 65 + if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); } - return false -} + if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); // Indefinite length... find END tag -function isDefinedHashType (hashType) { - var hashTypeMod = hashType & ~0x80 + var state = buffer.save(); -// return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04 -} + var res = this._skipUntilEnd(buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); -function isCanonicalSignature (buffer) { - if (!Buffer.isBuffer(buffer)) return false - if (!isDefinedHashType(buffer[buffer.length - 1])) return false + if (buffer.isError(res)) return res; + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; - return bip66.check(buffer.slice(0, -1)) -} +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + for (;;) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) return len; + var res = void 0; + if (tag.primitive || len !== null) res = buffer.skip(len);else res = this._skipUntilEnd(buffer, fail); // Failure -module.exports = { - compile: compile, - decompile: decompile, - fromASM: fromASM, - toASM: toASM, - toStack: toStack, + if (buffer.isError(res)) return res; + if (tag.tagStr === 'end') break; + } +}; - number: require('./script_number'), +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) { + var result = []; - isCanonicalPubKey: isCanonicalPubKey, - isCanonicalSignature: isCanonicalSignature, - isPushOnly: isPushOnly, - isDefinedHashType: isDefinedHashType -} + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); -},{"./script_number":95,"./types":120,"bip66":81,"bitcoin-ops":82,"bitcoin-ops/map":83,"pushdata-bitcoin":1221,"safe-buffer":1256,"typeforce":1318}],95:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer + if (buffer.isError(possibleEnd)) return possibleEnd; + var res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) break; + result.push(res); + } -function decode (buffer, maxLength, minimal) { - maxLength = maxLength || 4 - minimal = minimal === undefined ? true : minimal + return result; +}; - var length = buffer.length - if (length === 0) return 0 - if (length > maxLength) throw new TypeError('Script number overflow') - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number') +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) return unused; + return { + unused: unused, + data: buffer.raw() + }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch'); + var str = ''; + + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); } - } - // 40-bit - if (length === 5) { - var a = buffer.readUInt32LE(0) - var b = buffer.readUInt8(4) + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); - if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a) - return (b * 0x100000000) + a - } + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + 'numstr unsupported characters'); + } + + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); - var result = 0 + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + 'printstr unsupported characters'); + } - // 32-bit / 24-bit / 16-bit / 8-bit - for (var i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i) + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); } +}; - if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1)))) - return result -} - -function scriptNumSize (i) { - return i > 0x7fffffff ? 5 - : i > 0x7fffff ? 4 - : i > 0x7fff ? 3 - : i > 0x7f ? 2 - : i > 0x00 ? 1 - : 0 -} +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + var subident = 0; -function encode (number) { - var value = Math.abs(number) - var size = scriptNumSize(value) - var buffer = Buffer.allocUnsafe(size) - var negative = number < 0 + while (!buffer.isEmpty()) { + subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; - for (var i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i) - value >>= 8 + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } } - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1) - } else if (negative) { - buffer[size - 1] |= 0x80 + if (subident & 0x80) identifiers.push(ident); + var first = identifiers[0] / 40 | 0; + var second = identifiers[0] % 40; + if (relative) result = identifiers;else result = [first, second].concat(identifiers.slice(1)); + + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) tmp = values[result.join('.')]; + if (tmp !== undefined) result = tmp; } - return buffer -} + return result; +}; -module.exports = { - decode: decode, - encode: encode -} +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + var year; + var mon; + var day; + var hour; + var min; + var sec; -},{"safe-buffer":1256}],96:[function(require,module,exports){ -var decompile = require('../script').decompile -var multisig = require('./multisig') -var nullData = require('./nulldata') -var pubKey = require('./pubkey') -var pubKeyHash = require('./pubkeyhash') -var scriptHash = require('./scripthash') -var witnessPubKeyHash = require('./witnesspubkeyhash') -var witnessScriptHash = require('./witnessscripthash') -var witnessCommitment = require('./witnesscommitment') + if (tag === 'gentime') { + year = str.slice(0, 4) | 0; + mon = str.slice(4, 6) | 0; + day = str.slice(6, 8) | 0; + hour = str.slice(8, 10) | 0; + min = str.slice(10, 12) | 0; + sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + year = str.slice(0, 2) | 0; + mon = str.slice(2, 4) | 0; + day = str.slice(4, 6) | 0; + hour = str.slice(6, 8) | 0; + min = str.slice(8, 10) | 0; + sec = str.slice(10, 12) | 0; + if (year < 70) year = 2000 + year;else year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } -var types = { - MULTISIG: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment' -} + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; -function classifyOutput (script) { - if (witnessPubKeyHash.output.check(script)) return types.P2WPKH - if (witnessScriptHash.output.check(script)) return types.P2WSH - if (pubKeyHash.output.check(script)) return types.P2PKH - if (scriptHash.output.check(script)) return types.P2SH +DERNode.prototype._decodeNull = function decodeNull() { + return null; +}; - // XXX: optimization, below functions .decompile before use - var chunks = decompile(script) - if (multisig.output.check(chunks)) return types.MULTISIG - if (pubKey.output.check(chunks)) return types.P2PK - if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT - if (nullData.output.check(chunks)) return types.NULLDATA +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) return res;else return res !== 0; +}; - return types.NONSTANDARD -} +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); + if (values) res = values[res.toString(10)] || res; + return res; +}; -function classifyInput (script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - var chunks = decompile(script) +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') entity = entity(obj); + return entity._getDecoder('der').tree; +}; // Utility methods - if (pubKeyHash.input.check(chunks)) return types.P2PKH - if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH - if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG - if (pubKey.input.check(chunks)) return types.P2PK - return types.NONSTANDARD -} +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) return tag; + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; // Multi-octet tag - load -function classifyWitness (script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - var chunks = decompile(script) + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; - if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH - if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) return oct; + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } - return types.NONSTANDARD + var tagStr = der.tag[tag]; + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; } -module.exports = { - classifyInput: classifyInput, - classifyOutput: classifyOutput, - classifyWitness: classifyWitness, - multisig: multisig, - nullData: nullData, - pubKey: pubKey, - pubKeyHash: pubKeyHash, - scriptHash: scriptHash, - witnessPubKeyHash: witnessPubKeyHash, - witnessScriptHash: witnessScriptHash, - witnessCommitment: witnessCommitment, - types: types -} - -},{"../script":94,"./multisig":97,"./nulldata":100,"./pubkey":101,"./pubkeyhash":104,"./scripthash":107,"./witnesscommitment":110,"./witnesspubkeyhash":112,"./witnessscripthash":115}],97:[function(require,module,exports){ -module.exports = { - input: require('./input'), - output: require('./output') -} +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) return len; // Indefinite form -},{"./input":98,"./output":99}],98:[function(require,module,exports){ -// OP_0 [signatures ...] + if (!primitive && len === 0x80) return null; // Definite form -var Buffer = require('safe-buffer').Buffer -var bscript = require('../../script') -var p2mso = require('./output') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') + if ((len & 0x80) === 0) { + // Short form + return len; + } // Long form -function partialSignature (value) { - return value === OPS.OP_0 || bscript.isCanonicalSignature(value) -} -function check (script, allowIncomplete) { - var chunks = bscript.decompile(script) - if (chunks.length < 2) return false - if (chunks[0] !== OPS.OP_0) return false + var num = len & 0x7f; + if (num > 4) return buf.error('length octect is too long'); + len = 0; - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature) + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) return j; + len |= j; } - return chunks.slice(1).every(bscript.isCanonicalSignature) + return len; } -check.toJSON = function () { return 'multisig input' } -var EMPTY_BUFFER = Buffer.allocUnsafe(0) +},{"../base/buffer":80,"../base/node":82,"../constants/der":84,"bn.js":237,"inherits":974}],87:[function(require,module,exports){ +'use strict'; -function encodeStack (signatures, scriptPubKey) { - typeforce([partialSignature], signatures) +var decoders = exports; +decoders.der = require('./der'); +decoders.pem = require('./pem'); - if (scriptPubKey) { - var scriptData = p2mso.decode(scriptPubKey) +},{"./der":86,"./pem":88}],88:[function(require,module,exports){ +'use strict'; - if (signatures.length < scriptData.m) { - throw new TypeError('Not enough signatures provided') - } +var inherits = require('inherits'); - if (signatures.length > scriptData.pubKeys.length) { - throw new TypeError('Too many signatures provided') - } - } +var Buffer = require('buffer').Buffer; - return [].concat(EMPTY_BUFFER, signatures.map(function (sig) { - if (sig === OPS.OP_0) { - return EMPTY_BUFFER - } - return sig - })) -} +var DERDecoder = require('./der'); -function encode (signatures, scriptPubKey) { - return bscript.compile(encodeStack(signatures, scriptPubKey)) +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; } -function decodeStack (stack, allowIncomplete) { - typeforce(typeforce.Array, stack) - typeforce(check, stack, allowIncomplete) - return stack.slice(1) -} +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; -function decode (buffer, allowIncomplete) { - var stack = bscript.decompile(buffer) - return decodeStack(stack, allowIncomplete) -} +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); + var label = options.label.toUpperCase(); + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; -module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) continue; + if (match[2] !== label) continue; -},{"../../script":94,"./output":99,"bitcoin-ops":82,"safe-buffer":1256,"typeforce":1318}],99:[function(require,module,exports){ -// m [pubKeys ...] n OP_CHECKMULTISIG + if (start === -1) { + if (match[1] !== 'BEGIN') break; + start = i; + } else { + if (match[1] !== 'END') break; + end = i; + break; + } + } -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') -var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 + if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label); + var base64 = lines.slice(start + 1, end).join(''); // Remove excessive symbols -function check (script, allowIncomplete) { - var chunks = bscript.decompile(script) + base64.replace(/[^a-z0-9+/=]+/gi, ''); + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; - if (chunks.length < 4) return false - if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false - if (!types.Number(chunks[0])) return false - if (!types.Number(chunks[chunks.length - 2])) return false - var m = chunks[0] - OP_INT_BASE - var n = chunks[chunks.length - 2] - OP_INT_BASE +},{"./der":86,"buffer":undefined,"inherits":974}],89:[function(require,module,exports){ +'use strict'; - if (m <= 0) return false - if (n > 16) return false - if (m > n) return false - if (n !== chunks.length - 3) return false - if (allowIncomplete) return true +var inherits = require('inherits'); - var keys = chunks.slice(1, -2) - return keys.every(bscript.isCanonicalPubKey) -} -check.toJSON = function () { return 'multi-sig output' } +var Buffer = require('buffer').Buffer; -function encode (m, pubKeys) { - typeforce({ - m: types.Number, - pubKeys: [bscript.isCanonicalPubKey] - }, { - m: m, - pubKeys: pubKeys - }) +var Node = require('../base/node'); // Import DER constants - var n = pubKeys.length - if (n < m) throw new TypeError('Not enough pubKeys provided') - return bscript.compile([].concat( - OP_INT_BASE + m, - pubKeys, - OP_INT_BASE + n, - OPS.OP_CHECKMULTISIG - )) -} +var der = require('../constants/der'); -function decode (buffer, allowIncomplete) { - var chunks = bscript.decompile(buffer) - typeforce(check, chunks, allowIncomplete) +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; // Construct base tree - return { - m: chunks[0] - OP_INT_BASE, - pubKeys: chunks.slice(1, -2) - } -} + this.tree = new DERNode(); -module.exports = { - check: check, - decode: decode, - encode: encode + this.tree._init(entity.body); } -},{"../../script":94,"../../types":120,"bitcoin-ops":82,"typeforce":1318}],100:[function(require,module,exports){ -// OP_RETURN {data} +module.exports = DEREncoder; -var bscript = require('../script') -var types = require('../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; // Tree methods -function check (script) { - var buffer = bscript.compile(script) - return buffer.length > 1 && - buffer[0] === OPS.OP_RETURN +function DERNode(parent) { + Node.call(this, 'der', parent); } -check.toJSON = function () { return 'null data output' } - -function encode (data) { - typeforce(types.Buffer, data) - return bscript.compile([OPS.OP_RETURN, data]) -} +inherits(DERNode, Node); -function decode (buffer) { - typeforce(check, buffer) +DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); // Short form - return buffer.slice(2) -} + if (content.length < 0x80) { + var _header = new Buffer(2); -module.exports = { - output: { - check: check, - decode: decode, - encode: encode - } -} + _header[0] = encodedTag; + _header[1] = content.length; + return this._createEncoderBuffer([_header, content]); + } // Long form + // Count octets required to store length -},{"../script":94,"../types":120,"bitcoin-ops":82,"typeforce":1318}],101:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./input":102,"./output":103,"dup":97}],102:[function(require,module,exports){ -// {signature} -var bscript = require('../../script') -var typeforce = require('typeforce') + var lenOctets = 1; -function check (script) { - var chunks = bscript.decompile(script) + for (var i = content.length; i >= 0x100; i >>= 8) { + lenOctets++; + } - return chunks.length === 1 && - bscript.isCanonicalSignature(chunks[0]) -} -check.toJSON = function () { return 'pubKey input' } + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; -function encodeStack (signature) { - typeforce(bscript.isCanonicalSignature, signature) - return [signature] -} + for (var _i = 1 + lenOctets, j = content.length; j > 0; _i--, j >>= 8) { + header[_i] = j & 0xff; + } -function encode (signature) { - return bscript.compile(encodeStack(signature)) -} + return this._createEncoderBuffer([header, content]); +}; -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) - return stack[0] -} +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([str.unused | 0, str.data]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); -function decode (buffer) { - var stack = bscript.decompile(buffer) - return decodeStack(stack) -} + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } -module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + 'only digits and space'); + } -},{"../../script":94,"typeforce":1318}],103:[function(require,module,exports){ -// {pubKey} OP_CHECKSIG + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + 'only latin upper and lower case letters, ' + 'digits, space, apostrophe, left and rigth ' + 'parenthesis, plus sign, comma, hyphen, ' + 'dot, slash, colon, equal sign, ' + 'question mark'); + } -var bscript = require('../../script') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + ' unsupported'); + } +}; -function check (script) { - var chunks = bscript.decompile(script) +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s.]+/g); - return chunks.length === 2 && - bscript.isCanonicalPubKey(chunks[0]) && - chunks[1] === OPS.OP_CHECKSIG -} -check.toJSON = function () { return 'pubKey output' } + for (var i = 0; i < id.length; i++) { + id[i] |= 0; + } + } else if (Array.isArray(id)) { + id = id.slice(); -function encode (pubKey) { - typeforce(bscript.isCanonicalPubKey, pubKey) + for (var _i2 = 0; _i2 < id.length; _i2++) { + id[_i2] |= 0; + } + } - return bscript.compile([pubKey, OPS.OP_CHECKSIG]) -} + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id)); + } -function decode (buffer) { - var chunks = bscript.decompile(buffer) - typeforce(check, chunks) + if (!relative) { + if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } // Count number of octets - return chunks[0] -} -module.exports = { - check: check, - decode: decode, - encode: encode -} + var size = 0; -},{"../../script":94,"bitcoin-ops":82,"typeforce":1318}],104:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./input":105,"./output":106,"dup":97}],105:[function(require,module,exports){ -// {signature} {pubKey} + for (var _i3 = 0; _i3 < id.length; _i3++) { + var ident = id[_i3]; -var bscript = require('../../script') -var typeforce = require('typeforce') + for (size++; ident >= 0x80; ident >>= 7) { + size++; + } + } -function check (script) { - var chunks = bscript.decompile(script) + var objid = new Buffer(size); + var offset = objid.length - 1; - return chunks.length === 2 && - bscript.isCanonicalSignature(chunks[0]) && - bscript.isCanonicalPubKey(chunks[1]) -} -check.toJSON = function () { return 'pubKeyHash input' } + for (var _i4 = id.length - 1; _i4 >= 0; _i4--) { + var _ident = id[_i4]; + objid[offset--] = _ident & 0x7f; -function encodeStack (signature, pubKey) { - typeforce({ - signature: bscript.isCanonicalSignature, - pubKey: bscript.isCanonicalPubKey - }, { - signature: signature, - pubKey: pubKey - }) + while ((_ident >>= 7) > 0) { + objid[offset--] = 0x80 | _ident & 0x7f; + } + } - return [signature, pubKey] -} + return this._createEncoderBuffer(objid); +}; -function encode (signature, pubKey) { - return bscript.compile(encodeStack(signature, pubKey)) +function two(num) { + if (num < 10) return '0' + num;else return num; } -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); - return { - signature: stack[0], - pubKey: stack[1] + if (tag === 'gentime') { + str = [two(date.getUTCFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z'].join(''); + } else if (tag === 'utctime') { + str = [two(date.getUTCFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z'].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } -} -function decode (buffer) { - var stack = bscript.decompile(buffer) - return decodeStack(stack) -} + return this._encodeStr(str, 'octstr'); +}; -module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; -},{"../../script":94,"typeforce":1318}],106:[function(require,module,exports){ -// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) return this.reporter.error('String int or enum given, but no values map'); -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + JSON.stringify(num)); + } -function check (script) { - var buffer = bscript.compile(script) + num = values[num]; + } // Bignum, assume big endian - return buffer.length === 25 && - buffer[0] === OPS.OP_DUP && - buffer[1] === OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === OPS.OP_EQUALVERIFY && - buffer[24] === OPS.OP_CHECKSIG -} -check.toJSON = function () { return 'pubKeyHash output' } -function encode (pubKeyHash) { - typeforce(types.Hash160bit, pubKeyHash) + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); - return bscript.compile([ - OPS.OP_DUP, - OPS.OP_HASH160, - pubKeyHash, - OPS.OP_EQUALVERIFY, - OPS.OP_CHECKSIG - ]) -} + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } -function decode (buffer) { - typeforce(check, buffer) + num = new Buffer(numArray); + } - return buffer.slice(3, 23) -} + if (Buffer.isBuffer(num)) { + var _size = num.length; + if (num.length === 0) _size++; -module.exports = { - check: check, - decode: decode, - encode: encode -} + var _out = new Buffer(_size); -},{"../../script":94,"../../types":120,"bitcoin-ops":82,"typeforce":1318}],107:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./input":108,"./output":109,"dup":97}],108:[function(require,module,exports){ -// {serialized scriptPubKey script} + num.copy(_out); + if (num.length === 0) _out[0] = 0; + return this._createEncoderBuffer(_out); + } -var Buffer = require('safe-buffer').Buffer -var bscript = require('../../script') -var typeforce = require('typeforce') + if (num < 0x80) return this._createEncoderBuffer(num); + if (num < 0x100) return this._createEncoderBuffer([0, num]); + var size = 1; -var p2ms = require('../multisig/') -var p2pk = require('../pubkey/') -var p2pkh = require('../pubkeyhash/') -var p2wpkho = require('../witnesspubkeyhash/output') -var p2wsho = require('../witnessscripthash/output') + for (var i = num; i >= 0x100; i >>= 8) { + size++; + } -function check (script, allowIncomplete) { - var chunks = bscript.decompile(script) - if (chunks.length < 1) return false + var out = new Array(size); - var lastChunk = chunks[chunks.length - 1] - if (!Buffer.isBuffer(lastChunk)) return false + for (var _i5 = out.length - 1; _i5 >= 0; _i5--) { + out[_i5] = num & 0xff; + num >>= 8; + } + + if (out[0] & 0x80) { + out.unshift(0); + } - var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1))) - var redeemScriptChunks = bscript.decompile(lastChunk) + return this._createEncoderBuffer(new Buffer(out)); +}; - // is redeemScript a valid script? - if (redeemScriptChunks.length === 0) return false +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; - // is redeemScriptSig push only? - if (!bscript.isPushOnly(scriptSigChunks)) return false +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') entity = entity(obj); + return entity._getEncoder('der').tree; +}; - // is witness? - if (chunks.length === 1) { - return p2wsho.check(redeemScriptChunks) || - p2wpkho.check(redeemScriptChunks) - } +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) return false; + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + if (data.length !== state.defaultBuffer.length) return false; - // match types - if (p2pkh.input.check(scriptSigChunks) && - p2pkh.output.check(redeemScriptChunks)) return true + for (i = 0; i < data.length; i++) { + if (data[i] !== state.defaultBuffer[i]) return false; + } - if (p2ms.input.check(scriptSigChunks, allowIncomplete) && - p2ms.output.check(redeemScriptChunks)) return true + return true; +}; // Utility methods - if (p2pk.input.check(scriptSigChunks) && - p2pk.output.check(redeemScriptChunks)) return true - return false +function encodeTag(tag, primitive, cls, reporter) { + var res; + if (tag === 'seqof') tag = 'seq';else if (tag === 'setof') tag = 'set'; + if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag];else if (typeof tag === 'number' && (tag | 0) === tag) res = tag;else return reporter.error('Unknown tag: ' + tag); + if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported'); + if (!primitive) res |= 0x20; + res |= der.tagClassByName[cls || 'universal'] << 6; + return res; } -check.toJSON = function () { return 'scriptHash input' } -function encodeStack (redeemScriptStack, redeemScript) { - var serializedScriptPubKey = bscript.compile(redeemScript) +},{"../base/node":82,"../constants/der":84,"buffer":undefined,"inherits":974}],90:[function(require,module,exports){ +'use strict'; - return [].concat(redeemScriptStack, serializedScriptPubKey) -} +var encoders = exports; +encoders.der = require('./der'); +encoders.pem = require('./pem'); + +},{"./der":89,"./pem":91}],91:[function(require,module,exports){ +'use strict'; + +var inherits = require('inherits'); -function encode (redeemScriptSig, redeemScript) { - var redeemScriptStack = bscript.decompile(redeemScriptSig) +var DEREncoder = require('./der'); - return bscript.compile(encodeStack(redeemScriptStack, redeemScript)) +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; } -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; - return { - redeemScriptStack: stack.slice(0, -1), - redeemScript: stack[stack.length - 1] +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + var p = buf.toString('base64'); + var out = ['-----BEGIN ' + options.label + '-----']; + + for (var i = 0; i < p.length; i += 64) { + out.push(p.slice(i, i + 64)); } -} -function decode (buffer) { - var stack = bscript.decompile(buffer) - var result = decodeStack(stack) - result.redeemScriptSig = bscript.compile(result.redeemScriptStack) - delete result.redeemScriptStack - return result -} + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; + +},{"./der":89,"inherits":974}],92:[function(require,module,exports){ +"use strict"; +// Copyright 2011 Mark Cavage All rights reserved. module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} + newInvalidAsn1Error: function newInvalidAsn1Error(msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } +}; -},{"../../script":94,"../multisig/":97,"../pubkey/":101,"../pubkeyhash/":104,"../witnesspubkeyhash/output":114,"../witnessscripthash/output":117,"safe-buffer":1256,"typeforce":1318}],109:[function(require,module,exports){ -// OP_HASH160 {scriptHash} OP_EQUAL +},{}],93:[function(require,module,exports){ +"use strict"; -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') +// Copyright 2011 Mark Cavage All rights reserved. +var errors = require('./errors'); -function check (script) { - var buffer = bscript.compile(script) +var types = require('./types'); - return buffer.length === 23 && - buffer[0] === OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === OPS.OP_EQUAL -} -check.toJSON = function () { return 'scriptHash output' } +var Reader = require('./reader'); -function encode (scriptHash) { - typeforce(types.Hash160bit, scriptHash) +var Writer = require('./writer'); // --- Exports - return bscript.compile([OPS.OP_HASH160, scriptHash, OPS.OP_EQUAL]) -} -function decode (buffer) { - typeforce(check, buffer) +module.exports = { + Reader: Reader, + Writer: Writer +}; - return buffer.slice(2, 22) +for (var t in types) { + if (types.hasOwnProperty(t)) module.exports[t] = types[t]; } -module.exports = { - check: check, - decode: decode, - encode: encode +for (var e in errors) { + if (errors.hasOwnProperty(e)) module.exports[e] = errors[e]; } -},{"../../script":94,"../../types":120,"bitcoin-ops":82,"typeforce":1318}],110:[function(require,module,exports){ -module.exports = { - output: require('./output') -} +},{"./errors":92,"./reader":94,"./types":95,"./writer":96}],94:[function(require,module,exports){ +"use strict"; + +// Copyright 2011 Mark Cavage All rights reserved. +var assert = require('assert'); + +var Buffer = require('safer-buffer').Buffer; -},{"./output":111}],111:[function(require,module,exports){ -// OP_RETURN {aa21a9ed} {commitment} +var ASN1 = require('./types'); -var Buffer = require('safe-buffer').Buffer -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') +var errors = require('./errors'); // --- Globals -var HEADER = Buffer.from('aa21a9ed', 'hex') -function check (script) { - var buffer = bscript.compile(script) +var newInvalidAsn1Error = errors.newInvalidAsn1Error; // --- API - return buffer.length > 37 && - buffer[0] === OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) throw new TypeError('data must be a node Buffer'); + this._buf = data; + this._size = data.length; // These hold the "current" state + + this._len = 0; + this._offset = 0; } -check.toJSON = function () { return 'Witness commitment output' } +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function get() { + return this._len; + } +}); +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function get() { + return this._offset; + } +}); +Object.defineProperty(Reader.prototype, 'remain', { + get: function get() { + return this._size - this._offset; + } +}); +Object.defineProperty(Reader.prototype, 'buffer', { + get: function get() { + return this._buf.slice(this._offset); + } +}); +/** + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. + */ -function encode (commitment) { - typeforce(types.Hash256bit, commitment) +Reader.prototype.readByte = function (peek) { + if (this._size - this._offset < 1) return null; + var b = this._buf[this._offset] & 0xff; + if (!peek) this._offset += 1; + return b; +}; - var buffer = Buffer.allocUnsafe(36) - HEADER.copy(buffer, 0) - commitment.copy(buffer, 4) +Reader.prototype.peek = function () { + return this.readByte(true); +}; +/** + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 + */ - return bscript.compile([OPS.OP_RETURN, buffer]) -} -function decode (buffer) { - typeforce(check, buffer) +Reader.prototype.readLength = function (offset) { + if (offset === undefined) offset = this._offset; + if (offset >= this._size) return null; + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) return null; - return bscript.decompile(buffer)[1].slice(4, 36) -} + if ((lenB & 0x80) === 0x80) { + lenB &= 0x7f; + if (lenB === 0) throw newInvalidAsn1Error('Indefinite length not supported'); + if (lenB > 4) throw newInvalidAsn1Error('encoding too long'); + if (this._size - offset < lenB) return null; + this._len = 0; -module.exports = { - check: check, - decode: decode, - encode: encode -} + for (var i = 0; i < lenB; i++) { + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); + } + } else { + // Wasn't a variable length + this._len = lenB; + } -},{"../../script":94,"../../types":120,"bitcoin-ops":82,"safe-buffer":1256,"typeforce":1318}],112:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./input":113,"./output":114,"dup":97}],113:[function(require,module,exports){ -// {signature} {pubKey} + return offset; +}; +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ -var bscript = require('../../script') -var typeforce = require('typeforce') -function isCompressedCanonicalPubKey (pubKey) { - return bscript.isCanonicalPubKey(pubKey) && pubKey.length === 33 -} +Reader.prototype.readSequence = function (tag) { + var seq = this.peek(); + if (seq === null) return null; + if (tag !== undefined && tag !== seq) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + seq.toString(16)); + var o = this.readLength(this._offset + 1); // stored in `length` -function check (script) { - var chunks = bscript.decompile(script) + if (o === null) return null; + this._offset = o; + return seq; +}; - return chunks.length === 2 && - bscript.isCanonicalSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) -} -check.toJSON = function () { return 'witnessPubKeyHash input' } +Reader.prototype.readInt = function () { + return this._readTag(ASN1.Integer); +}; -function encodeStack (signature, pubKey) { - typeforce({ - signature: bscript.isCanonicalSignature, - pubKey: isCompressedCanonicalPubKey - }, { - signature: signature, - pubKey: pubKey - }) +Reader.prototype.readBoolean = function () { + return this._readTag(ASN1.Boolean) === 0 ? false : true; +}; - return [signature, pubKey] -} +Reader.prototype.readEnumeration = function () { + return this._readTag(ASN1.Enumeration); +}; -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) +Reader.prototype.readString = function (tag, retbuf) { + if (!tag) tag = ASN1.OctetString; + var b = this.peek(); + if (b === null) return null; + if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); + var o = this.readLength(this._offset + 1); // stored in `length` - return { - signature: stack[0], - pubKey: stack[1] - } -} + if (o === null) return null; + if (this.length > this._size - o) return null; + this._offset = o; + if (this.length === 0) return retbuf ? Buffer.alloc(0) : ''; -module.exports = { - check: check, - decodeStack: decodeStack, - encodeStack: encodeStack -} + var str = this._buf.slice(this._offset, this._offset + this.length); -},{"../../script":94,"typeforce":1318}],114:[function(require,module,exports){ -// OP_0 {pubKeyHash} + this._offset += this.length; + return retbuf ? str : str.toString('utf8'); +}; -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') +Reader.prototype.readOID = function (tag) { + if (!tag) tag = ASN1.OID; + var b = this.readString(tag, true); + if (b === null) return null; + var values = []; + var value = 0; -function check (script) { - var buffer = bscript.compile(script) + for (var i = 0; i < b.length; i++) { + var _byte = b[i] & 0xff; - return buffer.length === 22 && - buffer[0] === OPS.OP_0 && - buffer[1] === 0x14 -} -check.toJSON = function () { return 'Witness pubKeyHash output' } + value <<= 7; + value += _byte & 0x7f; -function encode (pubKeyHash) { - typeforce(types.Hash160bit, pubKeyHash) + if ((_byte & 0x80) === 0) { + values.push(value); + value = 0; + } + } - return bscript.compile([OPS.OP_0, pubKeyHash]) -} + value = values.shift(); + values.unshift(value % 40); + values.unshift(value / 40 >> 0); + return values.join('.'); +}; -function decode (buffer) { - typeforce(check, buffer) +Reader.prototype._readTag = function (tag) { + assert.ok(tag !== undefined); + var b = this.peek(); + if (b === null) return null; + if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); + var o = this.readLength(this._offset + 1); // stored in `length` - return buffer.slice(2) -} + if (o === null) return null; + if (this.length > 4) throw newInvalidAsn1Error('Integer too long: ' + this.length); + if (this.length > this._size - o) return null; + this._offset = o; + var fb = this._buf[this._offset]; + var value = 0; -module.exports = { - check: check, - decode: decode, - encode: encode -} + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= this._buf[this._offset++] & 0xff; + } + + if ((fb & 0x80) === 0x80 && i !== 4) value -= 1 << i * 8; + return value >> 0; +}; // --- Exported API -},{"../../script":94,"../../types":120,"bitcoin-ops":82,"typeforce":1318}],115:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./input":116,"./output":117,"dup":97}],116:[function(require,module,exports){ -// {serialized scriptPubKey script} -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') +module.exports = Reader; + +},{"./errors":92,"./types":95,"assert":undefined,"safer-buffer":2813}],95:[function(require,module,exports){ +"use strict"; -var p2ms = require('../multisig/') -var p2pk = require('../pubkey/') -var p2pkh = require('../pubkeyhash/') +// Copyright 2011 Mark Cavage All rights reserved. +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, + // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; + +},{}],96:[function(require,module,exports){ +"use strict"; -function check (chunks, allowIncomplete) { - typeforce(types.Array, chunks) - if (chunks.length < 1) return false +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - var witnessScript = chunks[chunks.length - 1] - if (!Buffer.isBuffer(witnessScript)) return false +// Copyright 2011 Mark Cavage All rights reserved. +var assert = require('assert'); - var witnessScriptChunks = bscript.decompile(witnessScript) +var Buffer = require('safer-buffer').Buffer; - // is witnessScript a valid script? - if (witnessScriptChunks.length === 0) return false +var ASN1 = require('./types'); - var witnessRawScriptSig = bscript.compile(chunks.slice(0, -1)) +var errors = require('./errors'); // --- Globals - // match types - if (p2pkh.input.check(witnessRawScriptSig) && - p2pkh.output.check(witnessScriptChunks)) return true - if (p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks)) return true +var newInvalidAsn1Error = errors.newInvalidAsn1Error; +var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; // --- Helpers - if (p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks)) return true +function merge(from, to) { + assert.ok(from); + assert.equal(_typeof(from), 'object'); + assert.ok(to); + assert.equal(_typeof(to), 'object'); + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function (key) { + if (to[key]) return; + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); + }); + return to; +} // --- API - return false -} -check.toJSON = function () { return 'witnessScriptHash input' } -function encodeStack (witnessData, witnessScript) { - typeforce({ - witnessData: [types.Buffer], - witnessScript: types.Buffer - }, { - witnessData: witnessData, - witnessScript: witnessScript - }) +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); + this._buf = Buffer.alloc(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. - return [].concat(witnessData, witnessScript) + this._seq = []; } -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) - return { - witnessData: stack.slice(0, -1), - witnessScript: stack[stack.length - 1] +Object.defineProperty(Writer.prototype, 'buffer', { + get: function get() { + if (this._seq.length) throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); + return this._buf.slice(0, this._offset); } -} +}); -module.exports = { - check: check, - decodeStack: decodeStack, - encodeStack: encodeStack -} +Writer.prototype.writeByte = function (b) { + if (typeof b !== 'number') throw new TypeError('argument must be a Number'); -},{"../../script":94,"../../types":120,"../multisig/":97,"../pubkey/":101,"../pubkeyhash/":104,"typeforce":1318}],117:[function(require,module,exports){ -// OP_0 {scriptHash} + this._ensure(1); -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') + this._buf[this._offset++] = b; +}; -function check (script) { - var buffer = bscript.compile(script) +Writer.prototype.writeInt = function (i, tag) { + if (typeof i !== 'number') throw new TypeError('argument must be a Number'); + if (typeof tag !== 'number') tag = ASN1.Integer; + var sz = 4; - return buffer.length === 34 && - buffer[0] === OPS.OP_0 && - buffer[1] === 0x20 -} -check.toJSON = function () { return 'Witness scriptHash output' } + while (((i & 0xff800000) === 0 || (i & 0xff800000) === 0xff800000 >> 0) && sz > 1) { + sz--; + i <<= 8; + } -function encode (scriptHash) { - typeforce(types.Hash256bit, scriptHash) + if (sz > 4) throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - return bscript.compile([OPS.OP_0, scriptHash]) -} + this._ensure(2 + sz); -function decode (buffer) { - typeforce(check, buffer) + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; - return buffer.slice(2) -} + while (sz-- > 0) { + this._buf[this._offset++] = (i & 0xff000000) >>> 24; + i <<= 8; + } +}; -module.exports = { - check: check, - decode: decode, - encode: encode -} +Writer.prototype.writeNull = function () { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; -},{"../../script":94,"../../types":120,"bitcoin-ops":82,"typeforce":1318}],118:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bcrypto = require('./crypto') -var bscript = require('./script') -var bufferutils = require('./bufferutils') -var opcodes = require('bitcoin-ops') -var typeforce = require('typeforce') -var types = require('./types') -var varuint = require('varuint-bitcoin') +Writer.prototype.writeEnumeration = function (i, tag) { + if (typeof i !== 'number') throw new TypeError('argument must be a Number'); + if (typeof tag !== 'number') tag = ASN1.Enumeration; + return this.writeInt(i, tag); +}; -function varSliceSize (someScript) { - var length = someScript.length +Writer.prototype.writeBoolean = function (b, tag) { + if (typeof b !== 'boolean') throw new TypeError('argument must be a Boolean'); + if (typeof tag !== 'number') tag = ASN1.Boolean; - return varuint.encodingLength(length) + length -} + this._ensure(3); -function vectorSize (someVector) { - var length = someVector.length + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; - return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) { - return sum + varSliceSize(witness) - }, 0) -} - -function Transaction () { - this.version = 1 - this.locktime = 0 - this.ins = [] - this.outs = [] -} - -Transaction.DEFAULT_SEQUENCE = 0xffffffff -Transaction.SIGHASH_ALL = 0x01 -Transaction.SIGHASH_NONE = 0x02 -Transaction.SIGHASH_SINGLE = 0x03 -Transaction.SIGHASH_ANYONECANPAY = 0x80 -Transaction.ADVANCED_TRANSACTION_MARKER = 0x00 -Transaction.ADVANCED_TRANSACTION_FLAG = 0x01 - -var EMPTY_SCRIPT = Buffer.allocUnsafe(0) -var EMPTY_WITNESS = [] -var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex') -var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex') -var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex') -var BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX -} +Writer.prototype.writeString = function (s, tag) { + if (typeof s !== 'string') throw new TypeError('argument must be a string (was: ' + _typeof(s) + ')'); + if (typeof tag !== 'number') tag = ASN1.OctetString; + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); -Transaction.fromBuffer = function (buffer, __noStrict) { - var offset = 0 - function readSlice (n) { - offset += n - return buffer.slice(offset - n, offset) - } + if (len) { + this._ensure(len); - function readUInt32 () { - var i = buffer.readUInt32LE(offset) - offset += 4 - return i - } + this._buf.write(s, this._offset); - function readInt32 () { - var i = buffer.readInt32LE(offset) - offset += 4 - return i + this._offset += len; } +}; - function readUInt64 () { - var i = bufferutils.readUInt64LE(buffer, offset) - offset += 8 - return i - } +Writer.prototype.writeBuffer = function (buf, tag) { + if (typeof tag !== 'number') throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) throw new TypeError('argument must be a buffer'); + this.writeByte(tag); + this.writeLength(buf.length); - function readVarInt () { - var vi = varuint.decode(buffer, offset) - offset += varuint.decode.bytes - return vi - } + this._ensure(buf.length); - function readVarSlice () { - return readSlice(readVarInt()) - } + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; - function readVector () { - var count = readVarInt() - var vector = [] - for (var i = 0; i < count; i++) vector.push(readVarSlice()) - return vector +Writer.prototype.writeStringArray = function (strings) { + if (!strings instanceof Array) throw new TypeError('argument must be an Array[String]'); + var self = this; + strings.forEach(function (s) { + self.writeString(s); + }); +}; // This is really to solve DER cases, but whatever for now + + +Writer.prototype.writeOID = function (s, tag) { + if (typeof s !== 'string') throw new TypeError('argument must be a string'); + if (typeof tag !== 'number') tag = ASN1.OID; + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) throw new Error('argument is not a valid OID string'); + + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push(octet >>> 7 | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push(octet >>> 14 | 0x80); + bytes.push((octet >>> 7 | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push(octet >>> 21 | 0x80); + bytes.push((octet >>> 14 | 0x80) & 0xFF); + bytes.push((octet >>> 7 | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push((octet >>> 28 | 0x80) & 0xFF); + bytes.push((octet >>> 21 | 0x80) & 0xFF); + bytes.push((octet >>> 14 | 0x80) & 0xFF); + bytes.push((octet >>> 7 | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } } - var tx = new Transaction() - tx.version = readInt32() + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function (b) { + encodeOctet(bytes, parseInt(b, 10)); + }); + var self = this; - var marker = buffer.readUInt8(offset) - var flag = buffer.readUInt8(offset + 1) + this._ensure(2 + bytes.length); - var hasWitnesses = false - if (marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG) { - offset += 2 - hasWitnesses = true - } + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function (b) { + self.writeByte(b); + }); +}; - var vinLen = readVarInt() - for (var i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: readSlice(32), - index: readUInt32(), - script: readVarSlice(), - sequence: readUInt32(), - witness: EMPTY_WITNESS - }) +Writer.prototype.writeLength = function (len) { + if (typeof len !== 'number') throw new TypeError('argument must be a Number'); + + this._ensure(4); + + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw newInvalidAsn1Error('Length too long (> 4 bytes)'); } +}; - var voutLen = readVarInt() - for (i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: readUInt64(), - script: readVarSlice() - }) - } +Writer.prototype.startSequence = function (tag) { + if (typeof tag !== 'number') tag = ASN1.Sequence | ASN1.Constructor; + this.writeByte(tag); - if (hasWitnesses) { - for (i = 0; i < vinLen; ++i) { - tx.ins[i].witness = readVector() - } + this._seq.push(this._offset); - // was this pointless? - if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data') - } + this._ensure(3); - tx.locktime = readUInt32() + this._offset += 3; +}; - if (__noStrict) return tx - if (offset !== buffer.length) throw new Error('Transaction has unexpected data') +Writer.prototype.endSequence = function () { + var seq = this._seq.pop(); - return tx -} + var start = seq + 3; + var len = this._offset - start; -Transaction.fromHex = function (hex) { - return Transaction.fromBuffer(Buffer.from(hex, 'hex')) -} + if (len <= 0x7f) { + this._shift(start, len, -2); -Transaction.isCoinbaseHash = function (buffer) { - typeforce(types.Hash256bit, buffer) - for (var i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw newInvalidAsn1Error('Sequence too long'); } - return true -} +}; -Transaction.prototype.isCoinbase = function () { - return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) -} +Writer.prototype._shift = function (start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); + + this._buf.copy(this._buf, start + shift, start, start + len); -Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) { - typeforce(types.tuple( - types.Hash256bit, - types.UInt32, - types.maybe(types.UInt32), - types.maybe(types.Buffer) - ), arguments) + this._offset += shift; +}; + +Writer.prototype._ensure = function (len) { + assert.ok(len); + + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) sz += len; + var buf = Buffer.alloc(sz); + + this._buf.copy(buf, 0, 0, this._offset); - if (types.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE + this._buf = buf; + this._size = sz; } +}; // --- Exported API - // Add the input and return the input's index - return (this.ins.push({ - hash: hash, - index: index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS - }) - 1) -} -Transaction.prototype.addOutput = function (scriptPubKey, value) { - typeforce(types.tuple(types.Buffer, types.Satoshi), arguments) +module.exports = Writer; - // Add the output and return the output's index - return (this.outs.push({ - script: scriptPubKey, - value: value - }) - 1) -} +},{"./errors":92,"./types":95,"assert":undefined,"safer-buffer":2813}],97:[function(require,module,exports){ +"use strict"; -Transaction.prototype.hasWitnesses = function () { - return this.ins.some(function (x) { - return x.witness.length !== 0 - }) -} +// Copyright 2011 Mark Cavage All rights reserved. +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc +var Ber = require('./ber/index'); // --- Exported API -Transaction.prototype.weight = function () { - var base = this.__byteLength(false) - var total = this.__byteLength(true) - return base * 3 + total -} -Transaction.prototype.virtualSize = function () { - return Math.ceil(this.weight() / 4) -} +module.exports = { + Ber: Ber, + BerReader: Ber.Reader, + BerWriter: Ber.Writer +}; -Transaction.prototype.byteLength = function () { - return this.__byteLength(true) -} +},{"./ber/index":93}],98:[function(require,module,exports){ +"use strict"; -Transaction.prototype.__byteLength = function (__allowWitness) { - var hasWitnesses = __allowWitness && this.hasWitnesses() +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - return ( - (hasWitnesses ? 10 : 8) + - varuint.encodingLength(this.ins.length) + - varuint.encodingLength(this.outs.length) + - this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) + - this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) + - (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0) - ) +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var hasBigInt64 = typeof BigUint64Array !== "undefined"; +var thisPtr = Symbol(); +/** Gets a string from an U32 and an U16 view on a memory. */ + +function getStringImpl(U32, U16, ptr) { + var dataLength = U32[ptr >>> 2]; + var dataOffset = ptr + 4 >>> 1; + var dataRemain = dataLength; + var parts = []; + var chunkSize = 1024; + + while (dataRemain > chunkSize) { + var last = U16[dataOffset + chunkSize - 1]; + var size = last >= 0xD800 && last < 0xDC00 ? chunkSize - 1 : chunkSize; + var part = U16.subarray(dataOffset, dataOffset += size); + parts.push(String.fromCharCode.apply(String, part)); + dataRemain -= size; + } + + return parts.join("") + String.fromCharCode.apply(String, U16.subarray(dataOffset, dataOffset + dataRemain)); } +/** Prepares the base module prior to instantiation. */ -Transaction.prototype.clone = function () { - var newTx = new Transaction() - newTx.version = this.version - newTx.locktime = this.locktime - newTx.ins = this.ins.map(function (txIn) { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness - } - }) +function preInstantiate(imports) { + var baseModule = {}; - newTx.outs = this.outs.map(function (txOut) { - return { - script: txOut.script, - value: txOut.value - } - }) + function getString(memory, ptr) { + if (!memory) return ""; + var buffer = memory.buffer; + return getStringImpl(new Uint32Array(buffer), new Uint16Array(buffer), ptr); + } // add common imports used by stdlib for convenience - return newTx + + var env = imports.env = imports.env || {}; + + env.abort = env.abort || function abort(mesg, file, line, colm) { + var memory = baseModule.memory || env.memory; // prefer exported, otherwise try imported + + throw Error("abort: " + getString(memory, mesg) + " at " + getString(memory, file) + ":" + line + ":" + colm); + }; + + env.trace = env.trace || function trace(mesg, n) { + var memory = baseModule.memory || env.memory; + console.log("trace: " + getString(memory, mesg) + (n ? " " : "") + Array.prototype.slice.call(arguments, 2, 2 + n).join(", ")); + }; + + imports.Math = imports.Math || Math; + imports.Date = imports.Date || Date; + return baseModule; } +/** Prepares the final module once instantiation is complete. */ -/** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ -Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) { - typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments) - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE +function postInstantiate(baseModule, instance) { + var rawExports = instance.exports; + var memory = rawExports.memory; + var memory_allocate = rawExports["memory.allocate"]; + var memory_fill = rawExports["memory.fill"]; + var memory_free = rawExports["memory.free"]; + var table = rawExports.table; - // ignore OP_CODESEPARATOR - var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) { - return x !== opcodes.OP_CODESEPARATOR - })) + var setargc = rawExports._setargc || function () {}; // Provide views for all sorts of basic values - var txTmp = this.clone() - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = [] + var buffer, I8, U8, I16, U16, I32, U32, F32, F64, I64, U64; + /** Updates memory views if memory has grown meanwhile. */ - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach(function (input, i) { - if (i === inIndex) return + function checkMem() { + // see: https://github.com/WebAssembly/design/issues/1210 + if (buffer !== memory.buffer) { + buffer = memory.buffer; + I8 = new Int8Array(buffer); + U8 = new Uint8Array(buffer); + I16 = new Int16Array(buffer); + U16 = new Uint16Array(buffer); + I32 = new Int32Array(buffer); + U32 = new Uint32Array(buffer); - input.sequence = 0 - }) + if (hasBigInt64) { + I64 = new BigInt64Array(buffer); + U64 = new BigUint64Array(buffer); + } - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE + F32 = new Float32Array(buffer); + F64 = new Float64Array(buffer); + } + } - // truncate outputs after - txTmp.outs.length = inIndex + 1 + checkMem(); + /** Allocates a new string in the module's memory and returns its pointer. */ - // "blank" outputs before - for (var i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT + function newString(str) { + var dataLength = str.length; + var ptr = memory_allocate(4 + (dataLength << 1)); + var dataOffset = 4 + ptr >>> 1; + checkMem(); + U32[ptr >>> 2] = dataLength; + + for (var i = 0; i < dataLength; ++i) { + U16[dataOffset + i] = str.charCodeAt(i); } - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach(function (input, y) { - if (y === inIndex) return + return ptr; + } + + baseModule.newString = newString; + /** Gets a string from the module's memory by its pointer. */ - input.sequence = 0 - }) + function getString(ptr) { + checkMem(); + return getStringImpl(U32, U16, ptr); } - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]] - txTmp.ins[0].script = ourScript + baseModule.getString = getString; - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT }) - txTmp.ins[inIndex].script = ourScript + function computeBufferSize(byteLength) { + var HEADER_SIZE = 8; + return 1 << 32 - Math.clz32(byteLength + HEADER_SIZE - 1); } + /** Creates a new typed array in the module's memory and returns its pointer. */ - // serialize and hash - var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4) - buffer.writeInt32LE(hashType, buffer.length - 4) - txTmp.__toBuffer(buffer, 0, false) - return bcrypto.hash256(buffer) -} + function newArray(view, length, unsafe) { + var ctor = view.constructor; + + if (ctor === Function) { + // TypedArray constructor created in memory + ctor = view; + view = null; + } else { + // TypedArray instance copied into memory + if (length === undefined) length = view.length; + } + + var elementSize = ctor.BYTES_PER_ELEMENT; + if (!elementSize) throw Error("not a typed array"); + var byteLength = elementSize * length; + var ptr = memory_allocate(12); // TypedArray header -Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) { - typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments) + var buf = memory_allocate(computeBufferSize(byteLength)); // ArrayBuffer + + checkMem(); + U32[ptr >>> 2] = buf; // .buffer + + U32[ptr + 4 >>> 2] = 0; // .byteOffset + + U32[ptr + 8 >>> 2] = byteLength; // .byteLength + + U32[buf >>> 2] = byteLength; // .byteLength + + U32[buf + 4 >>> 2] = 0; // 0 + + if (view) { + new ctor(buffer, buf + 8, length).set(view); + + if (view.length < length && !unsafe) { + var setLength = elementSize * view.length; + memory_fill(buf + 8 + setLength, 0, byteLength - setLength); + } + } else if (!unsafe) { + memory_fill(buf + 8, 0, byteLength); + } - var tbuffer, toffset - function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) } - function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) } - function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) } - function writeVarInt (i) { - varuint.encode(i, tbuffer, toffset) - toffset += varuint.encode.bytes + return ptr; } - function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } - var hashOutputs = ZERO - var hashPrevouts = ZERO - var hashSequence = ZERO + baseModule.newArray = newArray; + /** Gets a view on a typed array in the module's memory by its pointer. */ - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer.allocUnsafe(36 * this.ins.length) - toffset = 0 + function getArray(ctor, ptr) { + var elementSize = ctor.BYTES_PER_ELEMENT; + if (!elementSize) throw Error("not a typed array"); + checkMem(); + var buf = U32[ptr >>> 2]; + var byteOffset = U32[ptr + 4 >>> 2]; + var byteLength = U32[ptr + 8 >>> 2]; + return new ctor(buffer, buf + 8 + byteOffset, (byteLength - byteOffset) / elementSize); + } - this.ins.forEach(function (txIn) { - writeSlice(txIn.hash) - writeUInt32(txIn.index) - }) + baseModule.getArray = getArray; + /** Frees a typed array in the module's memory. Must not be accessed anymore afterwards. */ - hashPrevouts = bcrypto.hash256(tbuffer) + function freeArray(ptr) { + checkMem(); + var buf = U32[ptr >>> 2]; + memory_free(buf); + memory_free(ptr); } - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { - tbuffer = Buffer.allocUnsafe(4 * this.ins.length) - toffset = 0 + baseModule.freeArray = freeArray; + /** + * Creates a new function in the module's table and returns its pointer. Note that only actual + * WebAssembly functions, i.e. as exported by the module, are supported. + */ - this.ins.forEach(function (txIn) { - writeUInt32(txIn.sequence) - }) + function newFunction(fn) { + if (typeof fn.original === "function") fn = fn.original; + var index = table.length; + table.grow(1); + table.set(index, fn); + return index; + } - hashSequence = bcrypto.hash256(tbuffer) + baseModule.newFunction = newFunction; + /** Gets a function by its pointer. */ + + function getFunction(ptr) { + return wrapFunction(table.get(ptr), setargc); } - if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { - var txOutsSize = this.outs.reduce(function (sum, output) { - return sum + 8 + varSliceSize(output.script) - }, 0) + baseModule.getFunction = getFunction; // Pull basic exports to baseModule so code in preInstantiate can use them - tbuffer = Buffer.allocUnsafe(txOutsSize) - toffset = 0 + baseModule.memory = baseModule.memory || memory; + baseModule.table = baseModule.table || table; // Demangle exports and provide the usual utility on the prototype - this.outs.forEach(function (out) { - writeUInt64(out.value) - writeVarSlice(out.script) - }) + return demangle(rawExports, Object.defineProperties(baseModule, { + I8: { + get: function get() { + checkMem(); + return I8; + } + }, + U8: { + get: function get() { + checkMem(); + return U8; + } + }, + I16: { + get: function get() { + checkMem(); + return I16; + } + }, + U16: { + get: function get() { + checkMem(); + return U16; + } + }, + I32: { + get: function get() { + checkMem(); + return I32; + } + }, + U32: { + get: function get() { + checkMem(); + return U32; + } + }, + I64: { + get: function get() { + checkMem(); + return I64; + } + }, + U64: { + get: function get() { + checkMem(); + return U64; + } + }, + F32: { + get: function get() { + checkMem(); + return F32; + } + }, + F64: { + get: function get() { + checkMem(); + return F64; + } + } + })); +} +/** Wraps a WebAssembly function while also taking care of variable arguments. */ - hashOutputs = bcrypto.hash256(tbuffer) - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) { - var output = this.outs[inIndex] - tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)) - toffset = 0 - writeUInt64(output.value) - writeVarSlice(output.script) +function wrapFunction(fn, setargc) { + var wrap = function wrap() { + setargc(arguments.length); + return fn.apply(void 0, arguments); + }; // adding a function to the table with `newFunction` is limited to actual WebAssembly functions, + // hence we can't use the wrapper and instead need to provide a reference to the original - hashOutputs = bcrypto.hash256(tbuffer) - } - tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)) - toffset = 0 + wrap.original = fn; + return wrap; +} +/** Instantiates an AssemblyScript module using the specified imports. */ + - var input = this.ins[inIndex] - writeUInt32(this.version) - writeSlice(hashPrevouts) - writeSlice(hashSequence) - writeSlice(input.hash) - writeUInt32(input.index) - writeVarSlice(prevOutScript) - writeUInt64(value) - writeUInt32(input.sequence) - writeSlice(hashOutputs) - writeUInt32(this.locktime) - writeUInt32(hashType) - return bcrypto.hash256(tbuffer) +function instantiate(module, imports) { + return postInstantiate(preInstantiate(imports || (imports = {})), new WebAssembly.Instance(module, imports)); } -Transaction.prototype.getHash = function () { - return bcrypto.hash256(this.__toBuffer(undefined, undefined, false)) +exports.instantiate = instantiate; +/** Instantiates an AssemblyScript module from a buffer using the specified imports. */ + +function instantiateBuffer(buffer, imports) { + return instantiate(new WebAssembly.Module(buffer), imports); } -Transaction.prototype.getId = function () { - // transaction hash's are displayed in reverse order - return this.getHash().reverse().toString('hex') +exports.instantiateBuffer = instantiateBuffer; +/** Instantiates an AssemblyScript module from a response using the specified imports. */ + +function instantiateStreaming(_x, _x2) { + return _instantiateStreaming.apply(this, arguments); } -Transaction.prototype.toBuffer = function (buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true) +function _instantiateStreaming() { + _instantiateStreaming = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(response, imports) { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.t0 = postInstantiate; + _context.t1 = preInstantiate(imports || (imports = {})); + _context.next = 4; + return WebAssembly.instantiateStreaming(response, imports); + + case 4: + _context.t2 = _context.sent.instance; + return _context.abrupt("return", (0, _context.t0)(_context.t1, _context.t2)); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _instantiateStreaming.apply(this, arguments); } -Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) { - if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness)) +exports.instantiateStreaming = instantiateStreaming; +/** Demangles an AssemblyScript module's exports to a friendly object structure. */ + +function demangle(exports, baseModule) { + var module = baseModule ? Object.create(baseModule) : {}; + + var setargc = exports._setargc || function () {}; - var offset = initialOffset || 0 - function writeSlice (slice) { offset += slice.copy(buffer, offset) } - function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) } - function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) } - function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) } - function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) } - function writeVarInt (i) { - varuint.encode(i, buffer, offset) - offset += varuint.encode.bytes + function hasOwnProperty(elem, prop) { + return Object.prototype.hasOwnProperty.call(elem, prop); } - function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } - function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) } - writeInt32(this.version) + var _loop = function _loop(internalName) { + if (!hasOwnProperty(exports, internalName)) return "continue"; + var elem = exports[internalName]; + var parts = internalName.split("."); + var curr = module; - var hasWitnesses = __allowWitness && this.hasWitnesses() + while (parts.length > 1) { + var part = parts.shift(); + if (!hasOwnProperty(curr, part)) curr[part] = {}; + curr = curr[part]; + } - if (hasWitnesses) { - writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER) - writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG) - } + var name = parts[0]; + var hash = name.indexOf("#"); - writeVarInt(this.ins.length) + if (hash >= 0) { + var className = name.substring(0, hash); + var classElem = curr[className]; - this.ins.forEach(function (txIn) { - writeSlice(txIn.hash) - writeUInt32(txIn.index) - writeVarSlice(txIn.script) - writeUInt32(txIn.sequence) - }) + if (typeof classElem === "undefined" || !classElem.prototype) { + var ctor = function ctor() { + var _ctor$prototype; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return ctor.wrap((_ctor$prototype = ctor.prototype).constructor.apply(_ctor$prototype, [0].concat(args))); + }; + + ctor.prototype = {}; + + ctor.wrap = function (thisValue) { + return Object.create(ctor.prototype, _defineProperty({}, thisPtr, { + value: thisValue, + writable: false + })); + }; + + if (classElem) Object.getOwnPropertyNames(classElem).forEach(function (name) { + return Object.defineProperty(ctor, name, Object.getOwnPropertyDescriptor(classElem, name)); + }); + curr[className] = ctor; + } + + name = name.substring(hash + 1); + curr = curr[className].prototype; + + if (/^(get|set):/.test(name)) { + if (!hasOwnProperty(curr, name = name.substring(4))) { + var getter = exports[internalName.replace("set:", "get:")]; + var setter = exports[internalName.replace("get:", "set:")]; + Object.defineProperty(curr, name, { + get: function get() { + return getter(this[thisPtr]); + }, + set: function set(value) { + setter(this[thisPtr], value); + }, + enumerable: true + }); + } + } else { + if (name === 'constructor') { + curr[name] = wrapFunction(elem, setargc); + } else { + // for methods + Object.defineProperty(curr, name, { + value: function value() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } - writeVarInt(this.outs.length) - this.outs.forEach(function (txOut) { - if (!txOut.valueBuffer) { - writeUInt64(txOut.value) + setargc(args.length); + return elem.apply(void 0, [this[thisPtr]].concat(args)); + } + }); + } + } } else { - writeSlice(txOut.valueBuffer) + if (/^(get|set):/.test(name)) { + if (!hasOwnProperty(curr, name = name.substring(4))) { + Object.defineProperty(curr, name, { + get: exports[internalName.replace("set:", "get:")], + set: exports[internalName.replace("get:", "set:")], + enumerable: true + }); + } + } else if (typeof elem === "function") { + curr[name] = wrapFunction(elem, setargc); + } else { + curr[name] = elem; + } } + }; - writeVarSlice(txOut.script) - }) + for (var internalName in exports) { + var _ret = _loop(internalName); - if (hasWitnesses) { - this.ins.forEach(function (input) { - writeVector(input.witness) - }) + if (_ret === "continue") continue; } - writeUInt32(this.locktime) - - // avoid slicing unless necessary - if (initialOffset !== undefined) return buffer.slice(initialOffset, offset) - return buffer + return module; } -Transaction.prototype.toHex = function () { - return this.toBuffer().toString('hex') -} +exports.demangle = demangle; -Transaction.prototype.setInputScript = function (index, scriptSig) { - typeforce(types.tuple(types.Number, types.Buffer), arguments) +},{}],99:[function(require,module,exports){ +"use strict"; - this.ins[index].script = scriptSig -} +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -Transaction.prototype.setWitness = function (index, witness) { - typeforce(types.tuple(types.Number, [types.Buffer]), arguments) +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. +var assert = require('assert'); - this.ins[index].witness = witness -} +var Stream = require('stream').Stream; -module.exports = Transaction +var util = require('util'); ///--- Globals -},{"./bufferutils":86,"./crypto":87,"./script":94,"./types":120,"bitcoin-ops":82,"safe-buffer":1256,"typeforce":1318,"varuint-bitcoin":1334}],119:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var baddress = require('./address') -var bcrypto = require('./crypto') -var bscript = require('./script') -var btemplates = require('./templates') -var networks = require('./networks') -var ops = require('bitcoin-ops') -var typeforce = require('typeforce') -var types = require('./types') -var scriptTypes = btemplates.types -var SIGNABLE = [btemplates.types.P2PKH, btemplates.types.P2PK, btemplates.types.MULTISIG] -var P2SH = SIGNABLE.concat([btemplates.types.P2WPKH, btemplates.types.P2WSH]) +/* JSSTYLED */ -var ECPair = require('./ecpair') -var ECSignature = require('./ecsignature') -var Transaction = require('./transaction') -function supportedType (type) { - return SIGNABLE.indexOf(type) !== -1 +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; ///--- Internal + +function _capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1); } -function supportedP2SHType (type) { - return P2SH.indexOf(type) !== -1 +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: actual === undefined ? _typeof(arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); } -function extractChunks (type, chunks, script) { - var pubKeys = [] - var signatures = [] - switch (type) { - case scriptTypes.P2PKH: - // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)') - pubKeys = chunks.slice(1) - signatures = chunks.slice(0, 1) - break +function _getClass(arg) { + return Object.prototype.toString.call(arg).slice(8, -1); +} - case scriptTypes.P2PK: - pubKeys[0] = script ? btemplates.pubKey.output.decode(script) : undefined - signatures = chunks.slice(0, 1) - break +function noop() {} // Why even bother with asserts? +///--- Exports - case scriptTypes.MULTISIG: - if (script) { - var multisig = btemplates.multisig.output.decode(script) - pubKeys = multisig.pubKeys - } - signatures = chunks.slice(1).map(function (chunk) { - return chunk.length === 0 ? undefined : chunk - }) - break +var types = { + bool: { + check: function check(arg) { + return typeof arg === 'boolean'; + } + }, + func: { + check: function check(arg) { + return typeof arg === 'function'; + } + }, + string: { + check: function check(arg) { + return typeof arg === 'string'; + } + }, + object: { + check: function check(arg) { + return _typeof(arg) === 'object' && arg !== null; + } + }, + number: { + check: function check(arg) { + return typeof arg === 'number' && !isNaN(arg); + } + }, + finite: { + check: function check(arg) { + return typeof arg === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function check(arg) { + return Buffer.isBuffer(arg); + }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function check(arg) { + return Array.isArray(arg); + }, + operator: 'Array.isArray' + }, + stream: { + check: function check(arg) { + return arg instanceof Stream; + }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function check(arg) { + return arg instanceof Date; + }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function check(arg) { + return arg instanceof RegExp; + }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function check(arg) { + return typeof arg === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' } +}; - return { - pubKeys: pubKeys, - signatures: signatures +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; + /* re-export standard assert */ + + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function out(arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; } -} -function expandInput (scriptSig, witnessStack) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {} + /* standard checks */ - var prevOutScript - var prevOutType - var scriptType - var script - var redeemScript - var witnessScript - var witnessScriptType - var redeemScriptType - var witness = false - var p2wsh = false - var p2sh = false - var witnessProgram - var chunks - var scriptSigChunks = bscript.decompile(scriptSig) - var sigType = btemplates.classifyInput(scriptSigChunks, true) - if (sigType === scriptTypes.P2SH) { - p2sh = true - redeemScript = scriptSigChunks[scriptSigChunks.length - 1] - redeemScriptType = btemplates.classifyOutput(redeemScript) - prevOutScript = btemplates.scriptHash.output.encode(bcrypto.hash160(redeemScript)) - prevOutType = scriptTypes.P2SH - script = redeemScript - } + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; + } + + var type = types[k]; - var classifyWitness = btemplates.classifyWitness(witnessStack, true) - if (classifyWitness === scriptTypes.P2WSH) { - witnessScript = witnessStack[witnessStack.length - 1] - witnessScriptType = btemplates.classifyOutput(witnessScript) - p2wsh = true - witness = true - if (scriptSig.length === 0) { - prevOutScript = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript)) - prevOutType = scriptTypes.P2WSH - if (redeemScript !== undefined) { - throw new Error('Redeem script given when unnecessary') + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); } - // bare witness - } else { - if (!redeemScript) { - throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty') + }; + }); + /* optional checks */ + + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + + if (ndebug) { + out[name] = noop; + return; + } + + var type = types[k]; + + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; } - witnessProgram = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript)) - if (!redeemScript.equals(witnessProgram)) { - throw new Error('Redeem script didn\'t match witnessScript') + + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); } + }; + }); + /* arrayOf checks */ + + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + + if (ndebug) { + out[name] = noop; + return; } - if (!supportedType(btemplates.classifyOutput(witnessScript))) { - throw new Error('unsupported witness script') + var type = types[k]; + var expected = '[' + k + ']'; + + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + + var i; + + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + /* optionalArrayOf checks */ + + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + + if (ndebug) { + out[name] = noop; + return; } - script = witnessScript - scriptType = witnessScriptType - chunks = witnessStack.slice(0, -1) - } else if (classifyWitness === scriptTypes.P2WPKH) { - witness = true - var key = witnessStack[witnessStack.length - 1] - var keyHash = bcrypto.hash160(key) - if (scriptSig.length === 0) { - prevOutScript = btemplates.witnessPubKeyHash.output.encode(keyHash) - prevOutType = scriptTypes.P2WPKH - if (typeof redeemScript !== 'undefined') { - throw new Error('Redeem script given when unnecessary') + var type = types[k]; + var expected = '[' + k + ']'; + + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; } - } else { - if (!redeemScript) { - throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty') + + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); } - witnessProgram = btemplates.witnessPubKeyHash.output.encode(keyHash) - if (!redeemScript.equals(witnessProgram)) { - throw new Error('Redeem script did not have the right witness program') + + var i; + + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } } + }; + }); + /* re-export built-in assertions */ + + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; } - scriptType = scriptTypes.P2PKH - chunks = witnessStack - } else if (redeemScript) { - if (!supportedP2SHType(redeemScriptType)) { - throw new Error('Bad redeemscript!') + if (ndebug) { + out[k] = noop; + return; } - script = redeemScript - scriptType = redeemScriptType - chunks = scriptSigChunks.slice(0, -1) - } else { - prevOutType = scriptType = btemplates.classifyInput(scriptSig) - chunks = scriptSigChunks - } + out[k] = assert[k]; + }); + /* export ourselves (for unit tests _only_) */ - var expanded = extractChunks(scriptType, chunks, script) + out._setExports = _setExports; + return out; +} - var result = { - pubKeys: expanded.pubKeys, - signatures: expanded.signatures, - prevOutScript: prevOutScript, - prevOutType: prevOutType, - signType: scriptType, - signScript: script, - witness: Boolean(witness) - } +module.exports = _setExports(process.env.NODE_NDEBUG); - if (p2sh) { - result.redeemScript = redeemScript - result.redeemScriptType = redeemScriptType - } +},{"assert":undefined,"stream":undefined,"util":undefined}],100:[function(require,module,exports){ +'use strict'; - if (p2wsh) { - result.witnessScript = witnessScript - result.witnessScriptType = witnessScriptType - } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +function _asyncIterator(iterable) { var method; if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator]; if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); } + +var toArray = +/*#__PURE__*/ +function () { + var _ref = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(iterator) { + var arr, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, entry; + + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + arr = []; + _iteratorNormalCompletion = true; + _didIteratorError = false; + _context.prev = 3; + _iterator = _asyncIterator(iterator); + + case 5: + _context.next = 7; + return _iterator.next(); + + case 7: + _step = _context.sent; + _iteratorNormalCompletion = _step.done; + _context.next = 11; + return _step.value; + + case 11: + _value = _context.sent; + + if (_iteratorNormalCompletion) { + _context.next = 18; + break; + } - return result -} + entry = _value; + arr.push(entry); -// could be done in expandInput, but requires the original Transaction for hashForSignature -function fixMultisigOrder (input, transaction, vin) { - if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return - if (input.pubKeys.length === input.signatures.length) return + case 15: + _iteratorNormalCompletion = true; + _context.next = 5; + break; - var unmatched = input.signatures.concat() + case 18: + _context.next = 24; + break; - input.signatures = input.pubKeys.map(function (pubKey) { - var keyPair = ECPair.fromPublicKeyBuffer(pubKey) - var match + case 20: + _context.prev = 20; + _context.t0 = _context["catch"](3); + _didIteratorError = true; + _iteratorError = _context.t0; - // check for a signature - unmatched.some(function (signature, i) { - // skip if undefined || OP_0 - if (!signature) return false + case 24: + _context.prev = 24; + _context.prev = 25; - // TODO: avoid O(n) hashForSignature - var parsed = ECSignature.parseScriptSignature(signature) - var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType) + if (!(!_iteratorNormalCompletion && _iterator["return"] != null)) { + _context.next = 29; + break; + } - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false + _context.next = 29; + return _iterator["return"](); - // remove matched signature from unmatched - unmatched[i] = undefined - match = signature + case 29: + _context.prev = 29; - return true - }) + if (!_didIteratorError) { + _context.next = 32; + break; + } - return match - }) -} + throw _iteratorError; -function expandOutput (script, scriptType, ourPubKey) { - typeforce(types.Buffer, script) + case 32: + return _context.finish(29); - var scriptChunks = bscript.decompile(script) - if (!scriptType) { - scriptType = btemplates.classifyOutput(script) - } + case 33: + return _context.finish(24); - var pubKeys = [] + case 34: + return _context.abrupt("return", arr); - switch (scriptType) { - // does our hash160(pubKey) match the output scripts? - case scriptTypes.P2PKH: - if (!ourPubKey) break + case 35: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[3, 20, 24, 34], [25,, 29, 33]]); + })); - var pkh1 = scriptChunks[2] - var pkh2 = bcrypto.hash160(ourPubKey) - if (pkh1.equals(pkh2)) pubKeys = [ourPubKey] - break + return function toArray(_x) { + return _ref.apply(this, arguments); + }; +}(); - // does our hash160(pubKey) match the output scripts? - case scriptTypes.P2WPKH: - if (!ourPubKey) break +module.exports = toArray; - var wpkh1 = scriptChunks[1] - var wpkh2 = bcrypto.hash160(ourPubKey) - if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey] - break +},{}],101:[function(require,module,exports){ +'use strict'; - case scriptTypes.P2PK: - pubKeys = scriptChunks.slice(0, 1) - break +function _awaitAsyncGenerator(value) { return new _AwaitValue(value); } - case scriptTypes.MULTISIG: - pubKeys = scriptChunks.slice(1, -2) - break +function _wrapAsyncGenerator(fn) { return function () { return new _AsyncGenerator(fn.apply(this, arguments)); }; } - default: return { scriptType: scriptType } - } +function _AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; var wrappedAwait = value instanceof _AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { if (wrappedAwait) { resume("next", arg); return; } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen["return"] !== "function") { this["return"] = undefined; } } - return { - pubKeys: pubKeys, - scriptType: scriptType, - signatures: pubKeys.map(function () { return undefined }) - } -} +if (typeof Symbol === "function" && Symbol.asyncIterator) { _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } -function checkP2SHInput (input, redeemScriptHash) { - if (input.prevOutType) { - if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH') +_AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; - var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1] - if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)') - } -} +_AsyncGenerator.prototype["throw"] = function (arg) { return this._invoke("throw", arg); }; -function checkP2WSHInput (input, witnessScriptHash) { - if (input.prevOutType) { - if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH') +_AsyncGenerator.prototype["return"] = function (arg) { return this._invoke("return", arg); }; - var scriptHash = bscript.decompile(input.prevOutScript)[1] - if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)') - } +function _AwaitValue(value) { this.wrapped = value; } + +function _asyncIterator(iterable) { var method; if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator]; if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); } + +function batch(_x, _x2) { + return _batch.apply(this, arguments); } -function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) { - var expanded - var prevOutType - var prevOutScript +function _batch() { + _batch = _wrapAsyncGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(source, size) { + var things, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, set; - var p2sh = false - var p2shType - var redeemScriptHash + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + things = []; + _iteratorNormalCompletion = true; + _didIteratorError = false; + _context.prev = 3; + _iterator = _asyncIterator(source); - var witness = false - var p2wsh = false - var witnessType - var witnessScriptHash + case 5: + _context.next = 7; + return _awaitAsyncGenerator(_iterator.next()); - var signType - var signScript + case 7: + _step = _context.sent; + _iteratorNormalCompletion = _step.done; + _context.next = 11; + return _awaitAsyncGenerator(_step.value); - if (redeemScript && witnessScript) { - redeemScriptHash = bcrypto.hash160(redeemScript) - witnessScriptHash = bcrypto.sha256(witnessScript) - checkP2SHInput(input, redeemScriptHash) - - if (!redeemScript.equals(btemplates.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script') - - expanded = expandOutput(witnessScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"') - - prevOutType = btemplates.types.P2SH - prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash) - p2sh = witness = p2wsh = true - p2shType = btemplates.types.P2WSH - signType = witnessType = expanded.scriptType - signScript = witnessScript - } else if (redeemScript) { - redeemScriptHash = bcrypto.hash160(redeemScript) - checkP2SHInput(input, redeemScriptHash) - - expanded = expandOutput(redeemScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"') - - prevOutType = btemplates.types.P2SH - prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash) - p2sh = true - signType = p2shType = expanded.scriptType - signScript = redeemScript - witness = signType === btemplates.types.P2WPKH - } else if (witnessScript) { - witnessScriptHash = bcrypto.sha256(witnessScript) - checkP2WSHInput(input, witnessScriptHash) - - expanded = expandOutput(witnessScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"') - - prevOutType = btemplates.types.P2WSH - prevOutScript = btemplates.witnessScriptHash.output.encode(witnessScriptHash) - witness = p2wsh = true - signType = witnessType = expanded.scriptType - signScript = witnessScript - } else if (input.prevOutType) { - // embedded scripts are not possible without a redeemScript - if (input.prevOutType === scriptTypes.P2SH || - input.prevOutType === scriptTypes.P2WSH) { - throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript') - } - - prevOutType = input.prevOutType - prevOutScript = input.prevOutScript - expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey) - if (!expanded.pubKeys) return - - witness = (input.prevOutType === scriptTypes.P2WPKH) - signType = prevOutType - signScript = prevOutScript - } else { - prevOutScript = btemplates.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey)) - expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey) - - prevOutType = scriptTypes.P2PKH - witness = false - signType = prevOutType - signScript = prevOutScript - } - - if (signType === scriptTypes.P2WPKH) { - signScript = btemplates.pubKeyHash.output.encode(btemplates.witnessPubKeyHash.output.decode(signScript)) - } - - if (p2sh) { - input.redeemScript = redeemScript - input.redeemScriptType = p2shType - } - - if (p2wsh) { - input.witnessScript = witnessScript - input.witnessScriptType = witnessType - } - - input.pubKeys = expanded.pubKeys - input.signatures = expanded.signatures - input.signScript = signScript - input.signType = signType - input.prevOutScript = prevOutScript - input.prevOutType = prevOutType - input.witness = witness -} - -function buildStack (type, signatures, pubKeys, allowIncomplete) { - if (type === scriptTypes.P2PKH) { - if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return btemplates.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0]) - } else if (type === scriptTypes.P2PK) { - if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return btemplates.pubKey.input.encodeStack(signatures[0]) - } else if (type === scriptTypes.MULTISIG) { - if (signatures.length > 0) { - signatures = signatures.map(function (signature) { - return signature || ops.OP_0 - }) - if (!allowIncomplete) { - // remove blank signatures - signatures = signatures.filter(function (x) { return x !== ops.OP_0 }) - } + case 11: + _value = _context.sent; - return btemplates.multisig.input.encodeStack(signatures) - } - } else { - throw new Error('Not yet supported') - } + if (_iteratorNormalCompletion) { + _context.next = 24; + break; + } - if (!allowIncomplete) throw new Error('Not enough signatures provided') - return [] -} + set = _value; + things = things.concat(set); -function buildInput (input, allowIncomplete) { - var scriptType = input.prevOutType - var sig = [] - var witness = [] + case 15: + if (!(things.length >= size)) { + _context.next = 21; + break; + } - if (supportedType(scriptType)) { - sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete) - } + _context.next = 18; + return things.slice(0, size); - var p2sh = false - if (scriptType === btemplates.types.P2SH) { - // We can remove this error later when we have a guarantee prepareInput - // rejects unsignable scripts - it MUST be signable at this point. - if (!allowIncomplete && !supportedP2SHType(input.redeemScriptType)) { - throw new Error('Impossible to sign this type') - } + case 18: + things = things.slice(size); + _context.next = 15; + break; - if (supportedType(input.redeemScriptType)) { - sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete) - } + case 21: + _iteratorNormalCompletion = true; + _context.next = 5; + break; - // If it wasn't SIGNABLE, it's witness, defer to that - if (input.redeemScriptType) { - p2sh = true - scriptType = input.redeemScriptType - } - } + case 24: + _context.next = 30; + break; - switch (scriptType) { - // P2WPKH is a special case of P2PKH - case btemplates.types.P2WPKH: - witness = buildStack(btemplates.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete) - break + case 26: + _context.prev = 26; + _context.t0 = _context["catch"](3); + _didIteratorError = true; + _iteratorError = _context.t0; - case btemplates.types.P2WSH: - // We can remove this check later - if (!allowIncomplete && !supportedType(input.witnessScriptType)) { - throw new Error('Impossible to sign this type') - } + case 30: + _context.prev = 30; + _context.prev = 31; - if (supportedType(input.witnessScriptType)) { - witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete) - witness.push(input.witnessScript) - scriptType = input.witnessScriptType - } + if (!(!_iteratorNormalCompletion && _iterator["return"] != null)) { + _context.next = 35; + break; + } - break - } + _context.next = 35; + return _awaitAsyncGenerator(_iterator["return"]()); - // append redeemScript if necessary - if (p2sh) { - sig.push(input.redeemScript) - } + case 35: + _context.prev = 35; - return { - type: scriptType, - script: bscript.compile(sig), - witness: witness - } -} + if (!_didIteratorError) { + _context.next = 38; + break; + } -function TransactionBuilder (network, maximumFeeRate) { - this.prevTxMap = {} - this.network = network || networks.bitcoin + throw _iteratorError; - // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth) - this.maximumFeeRate = maximumFeeRate || 2500 + case 38: + return _context.finish(35); - this.inputs = [] - this.tx = new Transaction() -} + case 39: + return _context.finish(30); -TransactionBuilder.prototype.setLockTime = function (locktime) { - typeforce(types.UInt32, locktime) + case 40: + if (!things.length) { + _context.next = 46; + break; + } - // if any signatures exist, throw - if (this.inputs.some(function (input) { - if (!input.signatures) return false + _context.next = 43; + return things.slice(0, size); - return input.signatures.some(function (s) { return s }) - })) { - throw new Error('No, this would invalidate signatures') - } + case 43: + things = things.slice(size); + _context.next = 40; + break; - this.tx.locktime = locktime + case 46: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[3, 26, 30, 40], [31,, 35, 39]]); + })); + return _batch.apply(this, arguments); } -TransactionBuilder.prototype.setVersion = function (version) { - typeforce(types.UInt32, version) +module.exports = batch; - // XXX: this might eventually become more complex depending on what the versions represent - this.tx.version = version -} +},{}],102:[function(require,module,exports){ +'use strict'; -TransactionBuilder.fromTransaction = function (transaction, network) { - var txb = new TransactionBuilder(network) +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - // Copy transaction fields - txb.setVersion(transaction.version) - txb.setLockTime(transaction.locktime) +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(function (txOut) { - txb.addOutput(txOut.script, txOut.value) - }) +function _asyncIterator(iterable) { var method; if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator]; if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); } - // Copy inputs - transaction.ins.forEach(function (txIn) { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness - }) - }) +var first = +/*#__PURE__*/ +function () { + var _ref = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(iterator) { + var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, entry; - // fix some things not possible through the public API - txb.inputs.forEach(function (input, i) { - fixMultisigOrder(input, transaction, i) - }) + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _iteratorNormalCompletion = true; + _didIteratorError = false; + _context.prev = 2; + _iterator = _asyncIterator(iterator); - return txb -} + case 4: + _context.next = 6; + return _iterator.next(); -TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures') - } + case 6: + _step = _context.sent; + _iteratorNormalCompletion = _step.done; + _context.next = 10; + return _step.value; - var value + case 10: + _value = _context.sent; - // is it a hex string? - if (typeof txHash === 'string') { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = Buffer.from(txHash, 'hex').reverse() + if (_iteratorNormalCompletion) { + _context.next = 17; + break; + } - // is it a Transaction object? - } else if (txHash instanceof Transaction) { - var txOut = txHash.outs[vout] - prevOutScript = txOut.script - value = txOut.value + entry = _value; + return _context.abrupt("return", entry); - txHash = txHash.getHash() - } + case 14: + _iteratorNormalCompletion = true; + _context.next = 4; + break; - return this.__addInputUnsafe(txHash, vout, { - sequence: sequence, - prevOutScript: prevOutScript, - value: value - }) -} + case 17: + _context.next = 23; + break; -TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) { - if (Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported') - } + case 19: + _context.prev = 19; + _context.t0 = _context["catch"](2); + _didIteratorError = true; + _iteratorError = _context.t0; - var prevTxOut = txHash.toString('hex') + ':' + vout - if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut) + case 23: + _context.prev = 23; + _context.prev = 24; - var input = {} + if (!(!_iteratorNormalCompletion && _iterator["return"] != null)) { + _context.next = 28; + break; + } - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []) - } + _context.next = 28; + return _iterator["return"](); - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value - } + case 28: + _context.prev = 28; - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - var prevOutType + if (!_didIteratorError) { + _context.next = 31; + break; + } - if (!input.pubKeys && !input.signatures) { - var expanded = expandOutput(options.prevOutScript) + throw _iteratorError; - if (expanded.pubKeys) { - input.pubKeys = expanded.pubKeys - input.signatures = expanded.signatures - } + case 31: + return _context.finish(28); - prevOutType = expanded.scriptType - } + case 32: + return _context.finish(23); - input.prevOutScript = options.prevOutScript - input.prevOutType = prevOutType || btemplates.classifyOutput(options.prevOutScript) - } + case 33: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[2, 19, 23, 33], [24,, 28, 32]]); + })); - var vin = this.tx.addInput(txHash, vout, options.sequence, options.scriptSig) - this.inputs[vin] = input - this.prevTxMap[prevTxOut] = vin - return vin -} + return function first(_x) { + return _ref.apply(this, arguments); + }; +}(); -TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures') - } +module.exports = first; - // Attempt to get a script if it's a base58 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network) - } +},{}],103:[function(require,module,exports){ +'use strict'; - return this.tx.addOutput(scriptPubKey, value) -} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -TransactionBuilder.prototype.build = function () { - return this.__build(false) -} -TransactionBuilder.prototype.buildIncomplete = function () { - return this.__build(true) -} +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -TransactionBuilder.prototype.__build = function (allowIncomplete) { - if (!allowIncomplete) { - if (!this.tx.ins.length) throw new Error('Transaction has no inputs') - if (!this.tx.outs.length) throw new Error('Transaction has no outputs') - } +function _asyncIterator(iterable) { var method; if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator]; if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); } - var tx = this.tx.clone() - // Create script signatures from inputs - this.inputs.forEach(function (input, i) { - var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType - if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete') - var result = buildInput(input, allowIncomplete) +var last = +/*#__PURE__*/ +function () { + var _ref = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(iterator) { + var res, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, entry; - // skip if no result - if (!allowIncomplete) { - if (!supportedType(result.type) && result.type !== btemplates.types.P2WPKH) { - throw new Error(result.type + ' not supported') - } - } + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _iteratorNormalCompletion = true; + _didIteratorError = false; + _context.prev = 2; + _iterator = _asyncIterator(iterator); - tx.setInputScript(i, result.script) - tx.setWitness(i, result.witness) - }) + case 4: + _context.next = 6; + return _iterator.next(); - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees') - } - } + case 6: + _step = _context.sent; + _iteratorNormalCompletion = _step.done; + _context.next = 10; + return _step.value; - return tx -} + case 10: + _value = _context.sent; -function canSign (input) { - return input.prevOutScript !== undefined && - input.signScript !== undefined && - input.pubKeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubKeys.length && - input.pubKeys.length > 0 && - ( - input.witness === false || - (input.witness === true && input.value !== undefined) - ) -} + if (_iteratorNormalCompletion) { + _context.next = 17; + break; + } -TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) { - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network') - if (!this.inputs[vin]) throw new Error('No input at index: ' + vin) - hashType = hashType || Transaction.SIGHASH_ALL + entry = _value; + res = entry; - var input = this.inputs[vin] + case 14: + _iteratorNormalCompletion = true; + _context.next = 4; + break; - // if redeemScript was previously provided, enforce consistency - if (input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript)) { - throw new Error('Inconsistent redeemScript') - } + case 17: + _context.next = 23; + break; - var kpPubKey = keyPair.publicKey || keyPair.getPublicKeyBuffer() - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input didn\'t match witnessValue') - typeforce(types.Satoshi, witnessValue) - input.value = witnessValue - } + case 19: + _context.prev = 19; + _context.t0 = _context["catch"](2); + _didIteratorError = true; + _iteratorError = _context.t0; - if (!canSign(input)) prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript) - if (!canSign(input)) throw Error(input.prevOutType + ' not supported') - } + case 23: + _context.prev = 23; + _context.prev = 24; - // ready to sign - var signatureHash - if (input.witness) { - signatureHash = this.tx.hashForWitnessV0(vin, input.signScript, input.value, hashType) - } else { - signatureHash = this.tx.hashForSignature(vin, input.signScript, hashType) - } + if (!(!_iteratorNormalCompletion && _iterator["return"] != null)) { + _context.next = 28; + break; + } - // enforce in order signing of public keys - var signed = input.pubKeys.some(function (pubKey, i) { - if (!kpPubKey.equals(pubKey)) return false - if (input.signatures[i]) throw new Error('Signature already exists') - if (kpPubKey.length !== 33 && - input.signType === scriptTypes.P2WPKH) throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH') + _context.next = 28; + return _iterator["return"](); - var signature = keyPair.sign(signatureHash) - if (Buffer.isBuffer(signature)) signature = ECSignature.fromRSBuffer(signature) + case 28: + _context.prev = 28; - input.signatures[i] = signature.toScriptSignature(hashType) - return true - }) + if (!_didIteratorError) { + _context.next = 31; + break; + } - if (!signed) throw new Error('Key pair cannot sign for this input') -} + throw _iteratorError; -function signatureHashType (buffer) { - return buffer.readUInt8(buffer.length - 1) -} + case 31: + return _context.finish(28); -TransactionBuilder.prototype.__canModifyInputs = function () { - return this.inputs.every(function (input) { - // any signatures? - if (input.signatures === undefined) return true + case 32: + return _context.finish(23); - return input.signatures.every(function (signature) { - if (!signature) return true - var hashType = signatureHashType(signature) + case 33: + return _context.abrupt("return", res); - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return hashType & Transaction.SIGHASH_ANYONECANPAY - }) - }) -} + case 34: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[2, 19, 23, 33], [24,, 28, 32]]); + })); -TransactionBuilder.prototype.__canModifyOutputs = function () { - var nInputs = this.tx.ins.length - var nOutputs = this.tx.outs.length + return function last(_x) { + return _ref.apply(this, arguments); + }; +}(); - return this.inputs.every(function (input) { - if (input.signatures === undefined) return true +module.exports = last; - return input.signatures.every(function (signature) { - if (!signature) return true - var hashType = signatureHashType(signature) +},{}],104:[function(require,module,exports){ +"use strict"; - var hashTypeMod = hashType & 0x1f - if (hashTypeMod === Transaction.SIGHASH_NONE) return true - if (hashTypeMod === Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs - } - }) - }) -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -TransactionBuilder.prototype.__overMaximumFees = function (bytes) { - // not all inputs will have .value defined - var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0) +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0) - var fee = incoming - outgoing - var feeRate = fee / bytes +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - return feeRate > this.maximumFeeRate -} +var getIterator = require('get-iterator'); -module.exports = TransactionBuilder +var toIterable = require('pull-stream-to-async-iterator'); -},{"./address":84,"./crypto":87,"./ecpair":89,"./ecsignature":90,"./networks":93,"./script":94,"./templates":96,"./transaction":118,"./types":120,"bitcoin-ops":82,"safe-buffer":1256,"typeforce":1318}],120:[function(require,module,exports){ -var typeforce = require('typeforce') +function toPull(source) { + source = getIterator(source); + return ( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(end, cb) { + var next; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!end) { + _context.next = 11; + break; + } -var UINT31_MAX = Math.pow(2, 31) - 1 -function UInt31 (value) { - return typeforce.UInt32(value) && value <= UINT31_MAX -} + if (!source["return"]) { + _context.next = 10; + break; + } -function BIP32Path (value) { - return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) -} -BIP32Path.toJSON = function () { return 'BIP32 derivation path' } + _context.prev = 2; + _context.next = 5; + return source["return"](); -var SATOSHI_MAX = 21 * 1e14 -function Satoshi (value) { - return typeforce.UInt53(value) && value <= SATOSHI_MAX -} + case 5: + _context.next = 10; + break; -// external dependent types -var BigInt = typeforce.quacksLike('BigInteger') -var ECPoint = typeforce.quacksLike('Point') + case 7: + _context.prev = 7; + _context.t0 = _context["catch"](2); + return _context.abrupt("return", cb(_context.t0)); -// exposed, external API -var ECSignature = typeforce.compile({ r: BigInt, s: BigInt }) -var Network = typeforce.compile({ - messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String), - bip32: { - public: typeforce.UInt32, - private: typeforce.UInt32 - }, - pubKeyHash: typeforce.UInt8, - scriptHash: typeforce.UInt8, - wif: typeforce.UInt8 -}) + case 10: + return _context.abrupt("return", cb(end)); -// extend typeforce types with ours -var types = { - BigInt: BigInt, - BIP32Path: BIP32Path, - Buffer256bit: typeforce.BufferN(32), - ECPoint: ECPoint, - ECSignature: ECSignature, - Hash160bit: typeforce.BufferN(20), - Hash256bit: typeforce.BufferN(32), - Network: Network, - Satoshi: Satoshi, - UInt31: UInt31 -} + case 11: + _context.prev = 11; + _context.next = 14; + return source.next(); -for (var typeName in typeforce) { - types[typeName] = typeforce[typeName] -} + case 14: + next = _context.sent; + _context.next = 20; + break; -module.exports = types + case 17: + _context.prev = 17; + _context.t1 = _context["catch"](11); + return _context.abrupt("return", cb(_context.t1)); -},{"typeforce":1318}],121:[function(require,module,exports){ -// Blake2B in pure Javascript -// Adapted from the reference implementation in RFC7693 -// Ported to Javascript by DC - https://github.com/dcposch + case 20: + if (!next.done) { + _context.next = 22; + break; + } -var util = require('./util') + return _context.abrupt("return", cb(true)); -// 64-bit unsigned addition -// Sets v[a,a+1] += v[b,b+1] -// v should be a Uint32Array -function ADD64AA (v, a, b) { - var o0 = v[a] + v[b] - var o1 = v[a + 1] + v[b + 1] - if (o0 >= 0x100000000) { - o1++ - } - v[a] = o0 - v[a + 1] = o1 -} + case 22: + // eslint-disable-line + cb(null, next.value); -// 64-bit unsigned addition -// Sets v[a,a+1] += b -// b0 is the low 32 bits of b, b1 represents the high 32 bits -function ADD64AC (v, a, b0, b1) { - var o0 = v[a] + b0 - if (b0 < 0) { - o0 += 0x100000000 - } - var o1 = v[a + 1] + b1 - if (o0 >= 0x100000000) { - o1++ - } - v[a] = o0 - v[a + 1] = o1 -} + case 23: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[2, 7], [11, 17]]); + })); -// Little-endian byte access -function B2B_GET32 (arr, i) { - return (arr[i] ^ - (arr[i + 1] << 8) ^ - (arr[i + 2] << 16) ^ - (arr[i + 3] << 24)) + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; + }() + ); } -// G Mixing function -// The ROTRs are inlined for speed -function B2B_G (a, b, c, d, ix, iy) { - var x0 = m[ix] - var x1 = m[ix + 1] - var y0 = m[iy] - var y1 = m[iy + 1] +toPull.source = toPull; - ADD64AA(v, a, b) // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s - ADD64AC(v, a, x0, x1) // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits +toPull.transform = toPull.through = function (source) { + return function (read) { + return toPull(source(toIterable(read))); + }; +}; - // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits - var xor0 = v[d] ^ v[a] - var xor1 = v[d + 1] ^ v[a + 1] - v[d] = xor1 - v[d + 1] = xor0 - - ADD64AA(v, c, d) - - // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits - xor0 = v[b] ^ v[c] - xor1 = v[b + 1] ^ v[c + 1] - v[b] = (xor0 >>> 24) ^ (xor1 << 8) - v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8) - - ADD64AA(v, a, b) - ADD64AC(v, a, y0, y1) - - // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits - xor0 = v[d] ^ v[a] - xor1 = v[d + 1] ^ v[a + 1] - v[d] = (xor0 >>> 16) ^ (xor1 << 16) - v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16) - - ADD64AA(v, c, d) - - // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits - xor0 = v[b] ^ v[c] - xor1 = v[b + 1] ^ v[c + 1] - v[b] = (xor1 >>> 31) ^ (xor0 << 1) - v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1) -} - -// Initialization Vector -var BLAKE2B_IV32 = new Uint32Array([ - 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, - 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, - 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, - 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 -]) - -var SIGMA8 = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, - 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, - 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, - 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, - 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, - 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, - 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, - 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, - 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 -] +toPull.duplex = function (duplex) { + return { + sink: toPull.sink(duplex.sink), + source: toPull(duplex.source) + }; +}; -// These are offsets into a uint64 buffer. -// Multiply them all by 2 to make them offsets into a uint32 buffer, -// because this is Javascript and we don't have uint64s -var SIGMA82 = new Uint8Array(SIGMA8.map(function (x) { return x * 2 })) +toPull.sink = function (sink) { + return function (read) { + var _sink; -// Compression function. 'last' flag indicates last block. -// Note we're representing 16 uint64s as 32 uint32s -var v = new Uint32Array(32) -var m = new Uint32Array(32) -function blake2bCompress (ctx, last) { - var i = 0 + sink((_sink = {}, _defineProperty(_sink, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_sink, "next", function next() { + return new Promise(function (resolve, reject) { + read(null, function (end, value) { + if (end === true) return resolve({ + done: true, + value: value + }); + if (end) return reject(end); + resolve({ + done: false, + value: value + }); + }); + }); + }), _defineProperty(_sink, "return", function _return() { + return new Promise(function (resolve, reject) { + read(true, function (end, value) { + if (end && end !== true) return reject(end); + resolve({ + done: true, + value: value + }); + }); + }); + }), _defineProperty(_sink, "throw", function _throw(err) { + return new Promise(function (resolve, reject) { + read(err, function (end, value) { + if (end && end !== true) return reject(end); + resolve({ + done: true, + value: value + }); + }); + }); + }), _sink)); + }; +}; - // init work variables - for (i = 0; i < 16; i++) { - v[i] = ctx.h[i] - v[i + 16] = BLAKE2B_IV32[i] - } +module.exports = toPull; - // low 64 bits of offset - v[24] = v[24] ^ ctx.t - v[25] = v[25] ^ (ctx.t / 0x100000000) - // high 64 bits not supported, offset may not be higher than 2**53-1 +},{"get-iterator":860,"pull-stream-to-async-iterator":2660}],105:[function(require,module,exports){ +"use strict"; - // last block flag set ? - if (last) { - v[28] = ~v[28] - v[29] = ~v[29] - } +function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - // get little-endian words - for (i = 0; i < 32; i++) { - m[i] = B2B_GET32(ctx.b, 4 * i) - } + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } - // twelve rounds of mixing - // uncomment the DebugPrint calls to log the computation - // and match the RFC sample documentation - // util.debugPrint(' m[16]', m, 64) - for (i = 0; i < 12; i++) { - // util.debugPrint(' (i=' + (i < 10 ? ' ' : '') + i + ') v[16]', v, 64) - B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]) - B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]) - B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]) - B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]) - B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]) - B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]) - B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]) - B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]) - } - // util.debugPrint(' (i=12) v[16]', v, 64) + return target; + }; - for (i = 0; i < 16; i++) { - ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16] - } - // util.debugPrint('h[8]', ctx.h, 64) + return _extends.apply(this, arguments); } -// Creates a BLAKE2b hashing context -// Requires an output length between 1 and 64 bytes -// Takes an optional Uint8Array key -function blake2bInit (outlen, key) { - if (outlen === 0 || outlen > 64) { - throw new Error('Illegal output length, expected 0 < length <= 64') - } - if (key && key.length > 64) { - throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64') +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; } - // state, 'param block' - var ctx = { - b: new Uint8Array(128), - h: new Uint32Array(16), - t: 0, // input count - c: 0, // pointer within buffer - outlen: outlen // output length in bytes + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); } +} - // initialize hash state - for (var i = 0; i < 16; i++) { - ctx.h[i] = BLAKE2B_IV32[i] - } - var keylen = key ? key.length : 0 - ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen +function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); - // key the hash, if applicable - if (key) { - blake2bUpdate(ctx, key) - // at the end - ctx.c = 128 - } + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } - return ctx -} + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } -// Updates a BLAKE2b streaming hash -// Requires hash context and Uint8Array (byte array) -function blake2bUpdate (ctx, input) { - for (var i = 0; i < input.length; i++) { - if (ctx.c === 128) { // buffer full ? - ctx.t += ctx.c // add counters - blake2bCompress(ctx, false) // compress (not last) - ctx.c = 0 // counter to zero - } - ctx.b[ctx.c++] = input[i] - } + _next(undefined); + }); + }; } -// Completes a BLAKE2b streaming hash -// Returns a Uint8Array containing the message digest -function blake2bFinal (ctx) { - ctx.t += ctx.c // mark last block offset +var _require = require("readable-stream"), + Readable = _require.Readable; + +var getSymbol = typeof Symbol === "function" ? function (name) { + var symbol = Symbol[name]; + return symbol !== undefined ? symbol : "@@".concat(name); +} : function (name) { + return "@@".concat(name); +}; +var $$asyncIterator = asyncIteratorToStream.$$asyncIterator = getSymbol("asyncIterator"); +var $$iterator = asyncIteratorToStream.$$iterator = getSymbol("iterator"); + +var resolveToIterator = function resolveToIterator(value) { + var tmp; - while (ctx.c < 128) { // fill up with zeros - ctx.b[ctx.c++] = 0 + if (typeof (tmp = value[$$asyncIterator]) === "function") { + return tmp.call(value); } - blake2bCompress(ctx, true) // final block flag = 1 - // little endian convert and store - var out = new Uint8Array(ctx.outlen) - for (var i = 0; i < ctx.outlen; i++) { - out[i] = ctx.h[i >> 2] >> (8 * (i & 3)) + if (typeof (tmp = value[$$iterator]) === "function") { + return tmp.call(value); } - return out -} -// Computes the BLAKE2B hash of a string or byte array, and returns a Uint8Array -// -// Returns a n-byte Uint8Array -// -// Parameters: -// - input - the input bytes, as a string, Buffer or Uint8Array -// - key - optional key Uint8Array, up to 64 bytes -// - outlen - optional output length in bytes, default 64 -function blake2b (input, key, outlen) { - // preprocess inputs - outlen = outlen || 64 - input = util.normalizeInput(input) + return value; +}; - // do the math - var ctx = blake2bInit(outlen, key) - blake2bUpdate(ctx, input) - return blake2bFinal(ctx) -} +function asyncIteratorToStream(iterable, options) { + if (typeof iterable === "function") { + return function () { + return asyncIteratorToStream(iterable.apply(this, arguments), options); + }; + } -// Computes the BLAKE2B hash of a string or byte array -// -// Returns an n-byte hash in hex, all lowercase -// -// Parameters: -// - input - the input bytes, as a string, Buffer, or Uint8Array -// - key - optional key Uint8Array, up to 64 bytes -// - outlen - optional output length in bytes, default 64 -function blake2bHex (input, key, outlen) { - var output = blake2b(input, key, outlen) - return util.toHex(output) -} + var then = iterable.then; -module.exports = { - blake2b: blake2b, - blake2bHex: blake2bHex, - blake2bInit: blake2bInit, - blake2bUpdate: blake2bUpdate, - blake2bFinal: blake2bFinal -} + if (typeof then === "function") { + return then.call(iterable, function (iterable) { + return asyncIteratorToStream(iterable, options); + }); + } -},{"./util":124}],122:[function(require,module,exports){ -// BLAKE2s hash function in pure Javascript -// Adapted from the reference implementation in RFC7693 -// Ported to Javascript by DC - https://github.com/dcposch + var iterator = resolveToIterator(iterable); + var isGenerator = "return" in iterator; + var readable = options instanceof Readable ? options : new Readable(options); + + if (isGenerator) { + readable._destroy = function () { + var _ref = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(error, cb) { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return error != null ? iterator["throw"](error) : iterator["return"](); + + case 3: + _context.next = 8; + break; -var util = require('./util') + case 5: + _context.prev = 5; + _context.t0 = _context["catch"](0); + return _context.abrupt("return", cb(_context.t0)); -// Little-endian byte access. -// Expects a Uint8Array and an index -// Returns the little-endian uint32 at v[i..i+3] -function B2S_GET32 (v, i) { - return v[i] ^ (v[i + 1] << 8) ^ (v[i + 2] << 16) ^ (v[i + 3] << 24) -} + case 8: + cb(error); -// Mixing function G. -function B2S_G (a, b, c, d, x, y) { - v[a] = v[a] + v[b] + x - v[d] = ROTR32(v[d] ^ v[a], 16) - v[c] = v[c] + v[d] - v[b] = ROTR32(v[b] ^ v[c], 12) - v[a] = v[a] + v[b] + y - v[d] = ROTR32(v[d] ^ v[a], 8) - v[c] = v[c] + v[d] - v[b] = ROTR32(v[b] ^ v[c], 7) -} + case 9: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 5]]); + })); -// 32-bit right rotation -// x should be a uint32 -// y must be between 1 and 31, inclusive -function ROTR32 (x, y) { - return (x >>> y) ^ (x << (32 - y)) -} + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + } + + var running = false; + + readable._read = function () { + var _ref2 = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee2(size) { + var value, cursor; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!running) { + _context2.next = 2; + break; + } -// Initialization Vector. -var BLAKE2S_IV = new Uint32Array([ - 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, - 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19]) + return _context2.abrupt("return"); -var SIGMA = new Uint8Array([ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, - 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, - 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, - 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, - 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, - 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, - 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, - 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, - 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0]) + case 2: + running = true; + _context2.prev = 3; -// Compression function. "last" flag indicates last block -var v = new Uint32Array(16) -var m = new Uint32Array(16) -function blake2sCompress (ctx, last) { - var i = 0 - for (i = 0; i < 8; i++) { // init work variables - v[i] = ctx.h[i] - v[i + 8] = BLAKE2S_IV[i] - } + case 4: + cursor = iterator.next(size); - v[12] ^= ctx.t // low 32 bits of offset - v[13] ^= (ctx.t / 0x100000000) // high 32 bits - if (last) { // last block flag set ? - v[14] = ~v[14] - } + if (!(typeof cursor.then === "function")) { + _context2.next = 11; + break; + } - for (i = 0; i < 16; i++) { // get little-endian words - m[i] = B2S_GET32(ctx.b, 4 * i) - } + _context2.next = 8; + return cursor; - // ten rounds of mixing - // uncomment the DebugPrint calls to log the computation - // and match the RFC sample documentation - // util.debugPrint(' m[16]', m, 32) - for (i = 0; i < 10; i++) { - // util.debugPrint(' (i=' + i + ') v[16]', v, 32) - B2S_G(0, 4, 8, 12, m[SIGMA[i * 16 + 0]], m[SIGMA[i * 16 + 1]]) - B2S_G(1, 5, 9, 13, m[SIGMA[i * 16 + 2]], m[SIGMA[i * 16 + 3]]) - B2S_G(2, 6, 10, 14, m[SIGMA[i * 16 + 4]], m[SIGMA[i * 16 + 5]]) - B2S_G(3, 7, 11, 15, m[SIGMA[i * 16 + 6]], m[SIGMA[i * 16 + 7]]) - B2S_G(0, 5, 10, 15, m[SIGMA[i * 16 + 8]], m[SIGMA[i * 16 + 9]]) - B2S_G(1, 6, 11, 12, m[SIGMA[i * 16 + 10]], m[SIGMA[i * 16 + 11]]) - B2S_G(2, 7, 8, 13, m[SIGMA[i * 16 + 12]], m[SIGMA[i * 16 + 13]]) - B2S_G(3, 4, 9, 14, m[SIGMA[i * 16 + 14]], m[SIGMA[i * 16 + 15]]) - } - // util.debugPrint(' (i=10) v[16]', v, 32) + case 8: + cursor = _context2.sent; + _context2.next = 25; + break; - for (i = 0; i < 8; i++) { - ctx.h[i] ^= v[i] ^ v[i + 8] - } - // util.debugPrint('h[8]', ctx.h, 32) -} + case 11: + if (!(!cursor.done && (value = cursor.value) != null && typeof value.then === "function")) { + _context2.next = 25; + break; + } -// Creates a BLAKE2s hashing context -// Requires an output length between 1 and 32 bytes -// Takes an optional Uint8Array key -function blake2sInit (outlen, key) { - if (!(outlen > 0 && outlen <= 32)) { - throw new Error('Incorrect output length, should be in [1, 32]') - } - var keylen = key ? key.length : 0 - if (key && !(keylen > 0 && keylen <= 32)) { - throw new Error('Incorrect key length, should be in [1, 32]') - } + _context2.prev = 12; + _context2.next = 15; + return value; - var ctx = { - h: new Uint32Array(BLAKE2S_IV), // hash state - b: new Uint32Array(64), // input block - c: 0, // pointer within block - t: 0, // input count - outlen: outlen // output length in bytes - } - ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen + case 15: + value = _context2.sent; + _context2.next = 22; + break; - if (keylen > 0) { - blake2sUpdate(ctx, key) - ctx.c = 64 // at the end - } + case 18: + _context2.prev = 18; + _context2.t0 = _context2["catch"](12); + cursor = iterator["throw"](_context2.t0); + return _context2.abrupt("continue", 11); - return ctx -} + case 22: + cursor = iterator.next(value); + _context2.next = 11; + break; -// Updates a BLAKE2s streaming hash -// Requires hash context and Uint8Array (byte array) -function blake2sUpdate (ctx, input) { - for (var i = 0; i < input.length; i++) { - if (ctx.c === 64) { // buffer full ? - ctx.t += ctx.c // add counters - blake2sCompress(ctx, false) // compress (not last) - ctx.c = 0 // counter to zero - } - ctx.b[ctx.c++] = input[i] - } -} + case 25: + if (!cursor.done) { + _context2.next = 27; + break; + } -// Completes a BLAKE2s streaming hash -// Returns a Uint8Array containing the message digest -function blake2sFinal (ctx) { - ctx.t += ctx.c // mark last block offset - while (ctx.c < 64) { // fill up with zeros - ctx.b[ctx.c++] = 0 - } - blake2sCompress(ctx, true) // final block flag = 1 + return _context2.abrupt("return", readable.push(null)); - // little endian convert and store - var out = new Uint8Array(ctx.outlen) - for (var i = 0; i < ctx.outlen; i++) { - out[i] = (ctx.h[i >> 2] >> (8 * (i & 3))) & 0xFF - } - return out -} + case 27: + value = cursor.value; -// Computes the BLAKE2S hash of a string or byte array, and returns a Uint8Array -// -// Returns a n-byte Uint8Array -// -// Parameters: -// - input - the input bytes, as a string, Buffer, or Uint8Array -// - key - optional key Uint8Array, up to 32 bytes -// - outlen - optional output length in bytes, default 64 -function blake2s (input, key, outlen) { - // preprocess inputs - outlen = outlen || 32 - input = util.normalizeInput(input) + case 28: + if (value === undefined || readable.push(value)) { + _context2.next = 4; + break; + } - // do the math - var ctx = blake2sInit(outlen, key) - blake2sUpdate(ctx, input) - return blake2sFinal(ctx) -} + case 29: + _context2.next = 34; + break; -// Computes the BLAKE2S hash of a string or byte array -// -// Returns an n-byte hash in hex, all lowercase -// -// Parameters: -// - input - the input bytes, as a string, Buffer, or Uint8Array -// - key - optional key Uint8Array, up to 32 bytes -// - outlen - optional output length in bytes, default 64 -function blake2sHex (input, key, outlen) { - var output = blake2s(input, key, outlen) - return util.toHex(output) -} + case 31: + _context2.prev = 31; + _context2.t1 = _context2["catch"](3); + process.nextTick(readable.emit.bind(readable, "error", _context2.t1)); -module.exports = { - blake2s: blake2s, - blake2sHex: blake2sHex, - blake2sInit: blake2sInit, - blake2sUpdate: blake2sUpdate, - blake2sFinal: blake2sFinal -} + case 34: + _context2.prev = 34; + running = false; + return _context2.finish(34); -},{"./util":124}],123:[function(require,module,exports){ -var b2b = require('./blake2b') -var b2s = require('./blake2s') + case 37: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[3, 31, 34, 37], [12, 18]]); + })); -module.exports = { - blake2b: b2b.blake2b, - blake2bHex: b2b.blake2bHex, - blake2bInit: b2b.blake2bInit, - blake2bUpdate: b2b.blake2bUpdate, - blake2bFinal: b2b.blake2bFinal, - blake2s: b2s.blake2s, - blake2sHex: b2s.blake2sHex, - blake2sInit: b2s.blake2sInit, - blake2sUpdate: b2s.blake2sUpdate, - blake2sFinal: b2s.blake2sFinal + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }(); + + return readable; } -},{"./blake2b":121,"./blake2s":122}],124:[function(require,module,exports){ -var ERROR_MSG_INPUT = 'Input must be an string, Buffer or Uint8Array' +module.exports = asyncIteratorToStream; -// For convenience, let people hash a string, not just a Uint8Array -function normalizeInput (input) { - var ret - if (input instanceof Uint8Array) { - ret = input - } else if (input instanceof Buffer) { - ret = new Uint8Array(input) - } else if (typeof (input) === 'string') { - ret = new Uint8Array(Buffer.from(input, 'utf8')) - } else { - throw new Error(ERROR_MSG_INPUT) - } - return ret -} +asyncIteratorToStream.obj = function (iterable, options) { + return asyncIteratorToStream(iterable, _extends({ + objectMode: true + }, options)); +}; -// Converts a Uint8Array to a hexadecimal string -// For example, toHex([255, 0, 255]) returns "ff00ff" -function toHex (bytes) { - return Array.prototype.map.call(bytes, function (n) { - return (n < 16 ? '0' : '') + n.toString(16) - }).join('') -} +},{"readable-stream":120}],106:[function(require,module,exports){ +'use strict'; -// Converts any value in [0...2^32-1] to an 8-character hex string -function uint32ToHex (val) { - return (0x100000000 + val).toString(16).substring(1) -} +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -// For debugging: prints out hash state in the same format as the RFC -// sample computation exactly, so that you can diff -function debugPrint (label, arr, size) { - var msg = '\n' + label + ' = ' - for (var i = 0; i < arr.length; i += 2) { - if (size === 32) { - msg += uint32ToHex(arr[i]).toUpperCase() - msg += ' ' - msg += uint32ToHex(arr[i + 1]).toUpperCase() - } else if (size === 64) { - msg += uint32ToHex(arr[i + 1]).toUpperCase() - msg += uint32ToHex(arr[i]).toUpperCase() - } else throw new Error('Invalid size ' + size) - if (i % 6 === 4) { - msg += '\n' + new Array(label.length + 4).join(' ') - } else if (i < arr.length - 2) { - msg += ' ' - } - } - console.log(msg) -} +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -// For performance testing: generates N bytes of input, hashes M times -// Measures and prints MB/second hash performance each time -function testSpeed (hashFn, N, M) { - var startMs = new Date().getTime() +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - var input = new Uint8Array(N) - for (var i = 0; i < N; i++) { - input[i] = i % 256 - } - var genMs = new Date().getTime() - console.log('Generated random input in ' + (genMs - startMs) + 'ms') - startMs = genMs +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - for (i = 0; i < M; i++) { - var hashHex = hashFn(input) - var hashMs = new Date().getTime() - var ms = hashMs - startMs - startMs = hashMs - console.log('Hashed in ' + ms + 'ms: ' + hashHex.substring(0, 20) + '...') - console.log(Math.round(N / (1 << 20) / (ms / 1000) * 100) / 100 + ' MB PER SECOND') - } -} +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -module.exports = { - normalizeInput: normalizeInput, - toHex: toHex, - debugPrint: debugPrint, - testSpeed: testSpeed -} +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } -},{}],125:[function(require,module,exports){ -(function (module, exports) { - 'use strict'; +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; } - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } } - // BN + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inherits(NodeError, _Base); - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; + function NodeError(arg1, arg2, arg3) { + _classCallCheck(this, NodeError); + + return _possibleConstructorReturn(this, _getPrototypeOf(NodeError).call(this, getMessage(arg1, arg2, arg3))); } - this.negative = 0; - this.words = null; - this.length = 0; + return NodeError; + }(Base); - // Reduction context - this.red = null; + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - this._init(number || 0, base || 10, endian || 'be'); +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); } - } - if (typeof module === 'object') { - module.exports = BN; } else { - exports.BN = BN; + return "of ".concat(thing, " ").concat(String(expected)); } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - Buffer = require('buffer').Buffer; - } catch (e) { - } - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - if (number[0] === '-') { - this.negative = 1; - } + var msg; - this.strip(); + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } - if (endian !== 'le') return; + msg += ". Received type ".concat(_typeof(actual)); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; + +},{}],107:[function(require,module,exports){ +'use strict'; - this._initArray(this.toArray(), base, endian); - }; +var experimentalWarnings = new Set(); - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} - if (endian !== 'le') return; +function noop() {} - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; +module.exports.emitExperimentalWarning = process.emitWarning ? emitExperimentalWarning : noop; - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } +},{}],108:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. +'use strict'; +/**/ - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } +var objectKeys = Object.keys || function (obj) { + var keys = []; - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; + for (var key in obj) { + keys.push(key); + } - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; + return keys; +}; +/**/ - r <<= 4; - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; +module.exports = Duplex; - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; +var Readable = require('./_stream_readable'); - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; +var Writable = require('./_stream_writable'); + +require('inherits')(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } +} - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); } - this.strip(); - }; + } +} - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer - r *= mul; +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; + process.nextTick(onEndNT, this); +} - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; +function onEndNT(self) { + self.end(); +} - // '0' - '9' - } else { - r += c; - } +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; } - return r; + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; } +}); - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; +},{"./_stream_readable":110,"./_stream_writable":112,"inherits":974}],109:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. +'use strict'; - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; +module.exports = PassThrough; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; +var Transform = require('./_stream_transform'); - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); +require('inherits')(PassThrough, Transform); - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; - for (i = 0; i < mod; i++) { - pow *= base; - } +},{"./_stream_transform":111,"inherits":974}],110:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +'use strict'; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; +module.exports = Readable; +/**/ - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; +var Duplex; +/**/ - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; +Readable.ReadableState = ReadableState; +/**/ - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; +var EE = require('events').EventEmitter; - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; +/**/ - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - /* +var Stream = require('./internal/streams/stream'); +/**/ - var zeros = []; - var groupSizes = []; - var groupBases = []; - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } +var Buffer = require('buffer').Buffer; - */ +var OurUint8Array = global.Uint8Array || function () {}; - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } +var debugUtil = require('util'); - assert(false, 'Base should be between 2 and 36'); - }; +var debug; - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; +var BufferList = require('./internal/streams/buffer_list'); - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; +var destroyImpl = require('./internal/streams/destroy'); - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } +var _require2 = require('../experimentalWarning'), + emitExperimentalWarning = _require2.emitExperimentalWarning; // Lazy loaded to improve the startup performance. - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); +var StringDecoder; +var createReadableStreamAsyncIterator; - res[i] = b; - } +require('inherits')(Readable, Stream); - for (; i < reqLength; i++) { - res[i] = 0; - } - } +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - return res; - }; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" - function toBitArray (num) { - var w = new Array(num.bitLength()); + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - return w; - } + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + this.emitClose = options.emitClose !== false; // has it been destroyed - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; + this.readingMore = false; + this.decoder = null; + this.encoding = null; - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy - return this; - }; + this.readable = true; - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; } - return this.strip(); - }; + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; } + } else { + skipChunkCheck = true; + } - this.length = b.length; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() - return this.strip(); - }; - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } + if (addToFront) { + if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - this.length = a.length; - return this.strip(); - }; + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; + maybeReadMore(stream, state); +} - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; +function chunkInvalid(state, chunk) { + var er; - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + return er; +} - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. - if (bitsLeft > 0) { - bytesNeeded--; - } - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); // if setEncoding(null), decoder.encoding equals utf8 - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } + this._readableState.encoding = this._readableState.decoder.encoding; + return this; +}; // Don't raise the hwm > 8MB - // And remove leading zeroes - return this.strip(); - }; - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; +var MAX_HWM = 0x800000; - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } - var off = (bit / 26) | 0; - var wbit = bit % 26; + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. - this._expand(off + 1); - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; - return this.strip(); - }; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } + if (!state.ended) { + state.needReadable = true; + return 0; + } - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + return state.length; +} // you can override either this method, or the async _read(n) below. - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. - return this; - }; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - if (this.length > num.length) return this.clone().iadd(num); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. - return num.clone().iadd(this); - }; - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - // At this point both numbers are positive - var cmp = this.cmp(num); - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + if (state.length === 0) state.needReadable = true; // call internal read method - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } + this._read(state.highWaterMark); - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. - this.length = Math.max(this.length, i); + if (!state.reading) n = howMuchToRead(nOrig, state); + } - if (a !== this) { - this.negative = 1; - } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - return this.strip(); - }; + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; + if (nOrig !== n && state.ended) endReadable(this); + } - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; + if (ret !== null) this.emit('data', ret); + return ret; +}; - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; +function onEofChunk(stream, state) { + if (state.ended) return; - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } + if (state.decoder) { + var chunk = state.decoder.end(); - return out.strip(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; + state.ended = true; - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); } +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; - function FFTM (x, y) { - this.x = x; - this.y = y; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); } +} - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - return rb; - }; + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; +Readable.prototype._read = function (n) { + this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - var rx = rtwdf_ * ro - itwdf_ * io; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; + case 1: + state.pipes = [state.pipes, dest]; + break; - rtws[p + j] = re + ro; - itws[p + j] = ie + io; + default: + state.pipes.push(dest); + break; + } - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); } } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } + } - return 1 << i + 1 + odd; - }; + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken - t = iws[i]; + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; + src.on('data', ondata); - ws[i] = w & 0x3ffffff; + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; } - } - - return ws; - }; - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + src.pause(); } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } // Make sure our error handler is attached before userland ones. - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - return ph; - }; + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } - var rbt = this.makeRBT(N); + dest.once('close', onclose); - var _ = this.stub(N); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); + dest.once('finish', onfinish); - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to - var rmws = out.words; - rmws.length = N; - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); + dest.emit('pipe', src); // start the flow if it hasn't been started already. - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } + return dest; +}; - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } }; +} - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; + if (state.pipesCount === 0) return this; // just one destination. most common case. - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); } return this; - }; + } // try to find the right one. - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); - res = res.mul(q); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); } } + } - return res; - }; + return res; +}; - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; +Readable.prototype.addListener = Readable.prototype.on; - if (r !== 0) { - var carry = 0; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } - if (carry) { - this.words[i] = carry; - this.length++; - } - } + return res; +}; - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); - for (i = 0; i < s; i++) { - this.words[i] = 0; - } + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } - this.length += s; - } + return res; +}; - return this.strip(); - }; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - h -= s; - h = Math.max(0, h); +Readable.prototype.resume = function () { + var state = this._readableState; - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } + state.flowing = !state.readableListening; + resume(this, state); + } - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } + state.paused = false; + return this; +}; - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } +function resume_(stream, state) { + debug('resume', state.reading); - return this.strip(); - }; + if (!state.reading) { + stream.read(0); + } - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; + this._readableState.paused = true; + return this; +}; - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - // Check bit and return - var w = this.words[s]; +Readable.prototype.wrap = function (stream) { + var _this = this; - return !!(w & q); - }; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } - assert(this.negative === 0, 'imaskn works only with positive numbers'); + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - if (this.length <= s) { - return this; - } + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - if (r !== 0) { - s++; + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); } - this.length = Math.min(s, this.length); + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); } + } // proxy certain important events. - return this.strip(); - }; - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } + this._read = function (n) { + debug('wrapped _read', n); - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; + if (paused) { + paused = false; + stream.resume(); } - - // Add without checks - return this._iaddn(num); }; - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; + return this; +}; - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + emitExperimentalWarning('Readable[Symbol.asyncIterator]'); + + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); } - this.length = Math.max(this.length, i + 1); - return this; + return createReadableStreamAsyncIterator(this); }; +} - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; } + } +}); // exposed for testing purposes only. - this.words[0] -= num; +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} - return this.strip(); - }; +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - BN.prototype.iabs = function iabs () { - this.negative = 0; + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} - return this; - }; +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + return -1; +} - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; +},{"../errors":106,"../experimentalWarning":107,"./_stream_duplex":108,"./internal/streams/async_iterator":113,"./internal/streams/buffer_list":114,"./internal/streams/destroy":115,"./internal/streams/state":118,"./internal/streams/stream":119,"buffer":undefined,"events":undefined,"inherits":974,"string_decoder/":2900,"util":undefined}],111:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. +'use strict'; - this._expand(len); +module.exports = Transform; - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - if (carry === 0) return this.strip(); +var Duplex = require('./_stream_duplex'); - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; +require('inherits')(Transform, Duplex); - return this.strip(); - }; +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } - var a = this.clone(); - var b = num; + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} - // Initialize quotient - var m = a.length - b.length; - var q; +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); + this._readableState.sync = false; - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - return { - div: q || null, - mod: a - }; - }; + this.on('prefinish', prefinish); +} - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); +function prefinish() { + var _this = this; - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. - if (mode !== 'mod') { - div = res.div.neg(); - } - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; - return { - div: div, - mod: mod - }; - } +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. - if (mode !== 'mod') { - div = res.div.neg(); - } - return { - div: div, - mod: res.mod - }; - } +Transform.prototype._read = function (n) { + var ts = this._transformState; - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; - return { - div: res.div, - mod: mod - }; - } +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; - // Both numbers are positive at this point +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } +},{"../errors":106,"./_stream_duplex":108,"inherits":974}],112:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. +'use strict'; - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } +module.exports = Writable; +/* */ - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream - return this._wordDiv(num, mode); - }; - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; +function CorkedRequest(state) { + var _this = this; - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; + this.next = null; + this.entry = null; - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; + this.finish = function () { + onCorkedFinish(_this, state); }; +} +/* */ - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); +/**/ - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; +var Duplex; +/**/ - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; +Writable.WritableState = WritableState; +/**/ - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ - return acc; - }; +/**/ - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); +var Stream = require('./internal/streams/stream'); +/**/ - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - return this.strip(); - }; +var Buffer = require('buffer').Buffer; - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; +var OurUint8Array = global.Uint8Array || function () {}; - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} - var x = this; - var y = p.clone(); +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } +var destroyImpl = require('./internal/streams/destroy'); - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - var g = 0; +require('inherits')(Writable, Stream); - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } +function nop() {} - var yp = y.clone(); - var xp = x.clone(); +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - A.iushrn(1); - B.iushrn(1); - } - } + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - C.iushrn(1); - D.iushrn(1); - } - } + this.finalCalled = false; // drain event flag. - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } + this.needDrain = false; // at the start of calling end() - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; + this.ending = false; // when end() has been called, and returned - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); + this.ended = false; // when 'finish' is emitted - var a = this; - var b = p.clone(); + this.finished = false; // has it been destroyed - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. - var x1 = new BN(1); - var x2 = new BN(0); + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - var delta = b.clone(); + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } + this.length = 0; // a flag to see when we're in the middle of a write. - x1.iushrn(1); - } - } + this.writing = false; // when true all writes will be buffered until .uncork() call - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. - x2.iushrn(1); - } - } + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - if (res.cmpn(0) < 0) { - res.iadd(p); - } - return res; - }; + this.writecb = null; // the amount that is being written when _write is called. - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } + this.prefinished = false; // True if the error was already emitted and should not be thrown again - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } + this.emitClose = options.emitClose !== false; // count buffered requests - a.isub(b); - } while (true); + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - return b.iushln(shift); - }; + this.corkedRequestsFree = new CorkedRequest(this); +} - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; + while (current) { + out.push(current); + current = current.next; + } - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; + return out; +}; - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } +var realHasInstance; - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; }; +} - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. - assert(num <= 0x3ffffff, 'Number is too big'); + this.writable = true; - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options["final"] === 'function') this._final = options["final"]; + } - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; +Writable.prototype.pipe = function () { + this.emit('error', new ERR_STREAM_CANNOT_PIPE()); +}; - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; + stream.emit('error', er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; +function validChunk(stream, state, chunk, cb) { + var er; - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; + if (er) { + stream.emit('error', er); + process.nextTick(cb, er); + return false; + } - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; + return true; +} - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; + var isBuf = !state.objectMode && _isUint8Array(chunk); - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; +Writable.prototype.uncork = function () { + var state = this._writableState; - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + return chunk; +} - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; + if (!ret) state.needDrain = true; - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; + return ret; +} - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); // this can emit finish, but finish must + // always follow error - this.tmp = this._tmp(); + finishMaybe(stream, state); } +} - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); } else { - r.strip(); + afterWrite(stream, state, finished, cb); } + } +} - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } - inherits(K256, MPrime); +} // if there's something in the buffer waiting, then process it - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; } else { - input.length -= 9; + state.corkedRequestsFree = new CorkedRequest(state); } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; + if (state.writing) { + break; } } - return num; - }; - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + if (entry === null) state.lastBufferedRequest = null; } - inherits(P224, MPrime); - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); + state.bufferedRequest = entry; + state.bufferProcessing = false; +} - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; +Writable.prototype._writev = null; - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - return prime; - }; + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + if (!state.ending) endWritable(this, state, cb); + return this; +}; - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + stream.emit('error', err); } - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); } - return res._forceRed(this); - }; + } +} - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); +function finishMaybe(stream, state) { + var need = needFinish(state); - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); + if (need) { + prefinish(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); } - return res; - }; + } - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); + return need; +} - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; + state.ended = true; + stream.writable = false; +} - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + state.corkedRequestsFree.next = corkReq; +} - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); +},{"../errors":106,"./_stream_duplex":108,"./internal/streams/destroy":115,"./internal/streams/state":118,"./internal/streams/stream":119,"buffer":undefined,"inherits":974,"util-deprecate":2957}],113:[function(require,module,exports){ +'use strict'; - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); +var _Object$setPrototypeO; - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); + return obj; +} - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } +var finished = require('./end-of-stream'); - return r; +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +function createIterResult(value, done) { + return { + value: value, + done: done }; +} - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); }; +} - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); + next: function next() { + var _this = this; // if we have detected an error in the meanwhile + // reject straight away + + + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); } - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); } - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + var lastPromise = this[kLastPromise]; + var promise; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); - return res; - }; + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); + promise = new Promise(this[kHandlePromise]); + } - return r === num ? r.clone() : r; - }; + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - // - // Montgomery method engine - // + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } - BN.mont = function mont (num) { - return new Mont(num); - }; + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); - function Mont (m) { - Red.call(this, m); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; + iterator[kError] = err; + return; + } - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; + var resolve = iterator[kLastResolve]; - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); } - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } +module.exports = createReadableStreamAsyncIterator; - return res._forceRed(this); - }; +},{"./end-of-stream":116}],114:[function(require,module,exports){ +'use strict'; - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); +function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + var ownKeys = Object.keys(source); - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); } - return res._forceRed(this); - }; + ownKeys.forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(typeof module === 'undefined' || module, this); + return target; +} -},{"buffer":undefined}],126:[function(require,module,exports){ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } -'use strict' + return obj; +} -/** - * Module dependencies. - * @private - */ +var _require = require('buffer'), + Buffer = _require.Buffer; -var deprecate = require('depd')('body-parser') +var _require2 = require('util'), + inspect = _require2.inspect; -/** - * Cache of loaded parsers. - * @private - */ +var custom = inspect && inspect.custom || 'inspect'; -var parsers = Object.create(null) +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} -/** - * @typedef Parsers - * @type {function} - * @property {function} json - * @property {function} raw - * @property {function} text - * @property {function} urlencoded - */ +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } -/** - * Module exports. - * @type {Parsers} - */ + var _proto = BufferList.prototype; -exports = module.exports = deprecate.function(bodyParser, - 'bodyParser: use individual json/urlencoded middlewares') + _proto.push = function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; -/** - * JSON parser. - * @public - */ + _proto.unshift = function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; -Object.defineProperty(exports, 'json', { - configurable: true, - enumerable: true, - get: createParserGetter('json') -}) + _proto.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; -/** - * Raw parser. - * @public - */ + _proto.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; -Object.defineProperty(exports, 'raw', { - configurable: true, - enumerable: true, - get: createParserGetter('raw') -}) + _proto.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; -/** - * Text parser. - * @public - */ + while (p = p.next) { + ret += s + p.data; + } -Object.defineProperty(exports, 'text', { - configurable: true, - enumerable: true, - get: createParserGetter('text') -}) + return ret; + }; -/** - * URL-encoded parser. - * @public - */ + _proto.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; -Object.defineProperty(exports, 'urlencoded', { - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -}) + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } -/** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public - */ + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + ; -function bodyParser (options) { - var opts = {} + _proto.consume = function consume(n, hasStrings) { + var ret; - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] - } + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); } - } - - var _urlencoded = exports.urlencoded(opts) - var _json = exports.json(opts) - return function bodyParser (req, res, next) { - _json(req, res, function (err) { - if (err) return next(err) - _urlencoded(req, res, next) - }) - } -} + return ret; + }; -/** - * Create a getter for loading a parser. - * @private - */ + _proto.first = function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + ; -function createParserGetter (name) { - return function get () { - return loadParser(name) - } -} + _proto._getString = function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; -/** - * Load a parser module. - * @private - */ + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } -function loadParser (parserName) { - var parser = parsers[parserName] + break; + } - if (parser !== undefined) { - return parser - } + ++c; + } - // this uses a switch for static require analysis - switch (parserName) { - case 'json': - parser = require('./lib/types/json') - break - case 'raw': - parser = require('./lib/types/raw') - break - case 'text': - parser = require('./lib/types/text') - break - case 'urlencoded': - parser = require('./lib/types/urlencoded') - break - } + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + ; - // store to prevent invoking require() - return (parsers[parserName] = parser) -} + _proto._getBuffer = function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; -},{"./lib/types/json":128,"./lib/types/raw":129,"./lib/types/text":130,"./lib/types/urlencoded":131,"depd":192}],127:[function(require,module,exports){ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } -'use strict' + break; + } -/** - * Module dependencies. - * @private - */ + ++c; + } -var createError = require('http-errors') -var getBody = require('raw-body') -var iconv = require('iconv-lite') -var onFinished = require('on-finished') -var zlib = require('zlib') + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + ; -/** - * Module exports. - */ + _proto[custom] = function (_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + }; -module.exports = read + return BufferList; +}(); -/** - * Read a request into a buffer and parse. - * - * @param {object} req - * @param {object} res - * @param {function} next - * @param {function} parse - * @param {function} debug - * @param {object} options - * @private - */ +},{"buffer":undefined,"util":undefined}],115:[function(require,module,exports){ +'use strict'; // undocumented cb() API, needed for core, not for public API -function read (req, res, next, parse, debug, options) { - var length - var opts = options - var stream +function destroy(err, cb) { + var _this = this; - // flag as parsed - req._body = true + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - // read options - var encoding = opts.encoding !== null - ? opts.encoding - : null - var verify = opts.verify + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + process.nextTick(emitErrorNT, this, err); + } - try { - // get the content stream - stream = contentstream(req, debug, opts.inflate) - length = stream.length - stream.length = undefined - } catch (err) { - return next(err) - } + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - // set raw-body options - opts.length = length - opts.encoding = verify - ? null - : encoding - // assert charset is supported - if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { - return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - })) - } + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well - // read body - debug('read body') - getBody(stream, opts, function (error, body) { - if (error) { - var _error - if (error.type === 'encoding.unsupported') { - // echo back charset - _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - }) - } else { - // set status code on error - _error = createError(400, error) - } + if (this._writableState) { + this._writableState.destroyed = true; + } - // read off entire request - stream.resume() - onFinished(req, function onfinished () { - next(createError(400, _error)) - }) - return - } + this._destroy(err || null, function (err) { + if (!cb && err) { + process.nextTick(emitErrorAndCloseNT, _this, err); - // verify - if (verify) { - try { - debug('verify body') - verify(req, res, body, encoding) - } catch (err) { - next(createError(403, err, { - body: body, - type: err.type || 'entity.verify.failed' - })) - return + if (_this._writableState) { + _this._writableState.errorEmitted = true; } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); } + }); - // parse - var str = body - try { - debug('parse body') - str = typeof body !== 'string' && encoding !== null - ? iconv.decode(body, encoding) - : body - req.body = parse(str) - } catch (err) { - next(createError(400, err, { - body: str, - type: err.type || 'entity.parse.failed' - })) - return - } - - next() - }) + return this; } -/** - * Get the content stream of the request. - * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private - */ - -function contentstream (req, debug, inflate) { - var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() - var length = req.headers['content-length'] - var stream +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} - debug('content-encoding "%s"', encoding) +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} - if (inflate === false && encoding !== 'identity') { - throw createError(415, 'content encoding unsupported', { - encoding: encoding, - type: 'encoding.unsupported' - }) +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - switch (encoding) { - case 'deflate': - stream = zlib.createInflate() - debug('inflate body') - req.pipe(stream) - break - case 'gzip': - stream = zlib.createGunzip() - debug('gunzip body') - req.pipe(stream) - break - case 'identity': - stream = req - stream.length = length - break - default: - throw createError(415, 'unsupported content encoding "' + encoding + '"', { - encoding: encoding, - type: 'encoding.unsupported' - }) + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } +} - return stream +function emitErrorNT(self, err) { + self.emit('error', err); } -},{"http-errors":374,"iconv-lite":395,"on-finished":1053,"raw-body":1230,"zlib":undefined}],128:[function(require,module,exports){ -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +module.exports = { + destroy: destroy, + undestroy: undestroy +}; -'use strict' +},{}],116:[function(require,module,exports){ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; -/** - * Module dependencies. - * @private - */ +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; -var bytes = require('bytes') -var contentType = require('content-type') -var createError = require('http-errors') -var debug = require('debug')('body-parser:json') -var read = require('../read') -var typeis = require('type-is') +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; -/** - * Module exports. - */ + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -module.exports = json + callback.apply(this, args); + }; +} -/** - * RegExp to match the first non-space in a string. - * - * Allowed whitespace is defined in RFC 7159: - * - * ws = *( - * %x20 / ; Space - * %x09 / ; Horizontal tab - * %x0A / ; Line feed or New line - * %x0D ) ; Carriage return - */ +function noop() {} -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} -/** - * Create a middleware to parse JSON bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; -function json (options) { - var opts = options || {} + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var inflate = opts.inflate !== false - var reviver = opts.reviver - var strict = opts.strict !== false - var type = opts.type || 'application/json' - var verify = opts.verify || false + var writableEnded = stream._writableState && stream._writableState.finished; - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type + var readableEnded = stream._readableState && stream._readableState.endEmitted; - function parse (body) { - if (body.length === 0) { - // special-case empty json body, as it's a common client-side mistake - // TODO: maybe make this configurable or part of "strict" option - return {} - } + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; - if (strict) { - var first = firstchar(body) + var onerror = function onerror(err) { + callback.call(stream, err); + }; - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) - } - } + var onclose = function onclose() { + var err; - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } - } - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } + }; - req.body = req.body || {} + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } - debug('content-type %j', req.headers['content-type']) + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +module.exports = eos; - // assert charset per RFC 7159 sec 8.1 - var charset = getCharset(req) || 'utf-8' - if (charset.substr(0, 4) !== 'utf-') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } +},{"../../../errors":106}],117:[function(require,module,exports){ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } -/** - * Create strict violation syntax error matching native error. - * - * @param {string} str - * @param {string} char - * @return {Error} - * @private - */ +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; -function createStrictSyntaxError (str, char) { - var index = str.indexOf(char) - var partial = str.substring(0, index) + '#' +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} - try { - JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') - } catch (e) { - return normalizeJsonSyntaxError(e, { - message: e.message.replace('#', char), - stack: e.stack - }) - } +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; } -/** - * Get the first non-whitespace character in a string. - * - * @param {string} str - * @return {function} - * @private - */ +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; } -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } +function call(fn) { + fn(); } -/** - * Normalize a SyntaxError for JSON.parse. - * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} - */ +function pipe(from, to) { + return from.pipe(to); +} -function normalizeJsonSyntaxError (error, obj) { - var keys = Object.getOwnPropertyNames(error) +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key !== 'stack' && key !== 'message') { - delete error[key] - } +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; } - // replace stack before message for Node.js 0.10 and below - error.stack = obj.stack.replace(error.message, obj.message) - error.message = obj.message + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; - return error -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); } -} -},{"../read":127,"bytes":152,"content-type":161,"debug":134,"http-errors":374,"type-is":1315}],129:[function(require,module,exports){ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} -'use strict' +module.exports = pipeline; -/** - * Module dependencies. - */ +},{"../../../errors":106,"./end-of-stream":116}],118:[function(require,module,exports){ +'use strict'; -var bytes = require('bytes') -var debug = require('debug')('body-parser:raw') -var read = require('../read') -var typeis = require('type-is') +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; -/** - * Module exports. - */ +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} -module.exports = raw +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); -/** - * Create a middleware to parse raw bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } -function raw (options) { - var opts = options || {} + return Math.floor(hwm); + } // Default value - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/octet-stream' - var verify = opts.verify || false - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } + return state.objectMode ? 16 : 16 * 1024; +} - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type +module.exports = { + getHighWaterMark: getHighWaterMark +}; - function parse (buf) { - return buf - } +},{"../../../errors":106}],119:[function(require,module,exports){ +"use strict"; - return function rawParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } +module.exports = require('stream'); - req.body = req.body || {} +},{"stream":undefined}],120:[function(require,module,exports){ +"use strict"; - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +var Stream = require('stream'); - debug('content-type %j', req.headers['content-type']) +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +},{"./lib/_stream_duplex.js":108,"./lib/_stream_passthrough.js":109,"./lib/_stream_readable.js":110,"./lib/_stream_transform.js":111,"./lib/_stream_writable.js":112,"./lib/internal/streams/end-of-stream.js":116,"./lib/internal/streams/pipeline.js":117,"stream":undefined}],121:[function(require,module,exports){ +'use strict'; - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) +function Queue(options) { + if (!(this instanceof Queue)) { + return new Queue(options); } + + options = options || {}; + this.concurrency = options.concurrency || Infinity; + this.pending = 0; + this.jobs = []; + this.cbs = []; + this._done = done.bind(this); } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ +var arrayAddMethods = ['push', 'unshift', 'splice']; +arrayAddMethods.forEach(function (method) { + Queue.prototype[method] = function () { + var methodResult = Array.prototype[method].apply(this.jobs, arguments); + + this._run(); -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) + return methodResult; + }; +}); +Object.defineProperty(Queue.prototype, 'length', { + get: function get() { + return this.pending + this.jobs.length; } -} +}); -},{"../read":127,"bytes":152,"debug":134,"type-is":1315}],130:[function(require,module,exports){ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +Queue.prototype._run = function () { + if (this.pending === this.concurrency) { + return; + } -'use strict' + if (this.jobs.length) { + var job = this.jobs.shift(); + this.pending++; + job(this._done); -/** - * Module dependencies. - */ + this._run(); + } -var bytes = require('bytes') -var contentType = require('content-type') -var debug = require('debug')('body-parser:text') -var read = require('../read') -var typeis = require('type-is') + if (this.pending === 0) { + while (this.cbs.length !== 0) { + var cb = this.cbs.pop(); + process.nextTick(cb); + } + } +}; -/** - * Module exports. - */ +Queue.prototype.onDone = function (cb) { + if (typeof cb === 'function') { + this.cbs.push(cb); -module.exports = text + this._run(); + } +}; -/** - * Create a middleware to parse text bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ +function done() { + this.pending--; -function text (options) { - var opts = options || {} + this._run(); +} - var defaultCharset = opts.defaultCharset || 'utf-8' - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'text/plain' - var verify = opts.verify || false +module.exports = Queue; - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } +},{}],122:[function(require,module,exports){ +"use strict"; - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type +function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } - function parse (buf) { - return buf +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; } - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } + return obj; +} - req.body = req.body || {} +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} - debug('content-type %j', req.headers['content-type']) +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); +} - // get charset - var charset = getCharset(req) || defaultCharset +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); +} - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } +function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined + return arr2; } } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ +function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); +} -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -},{"../read":127,"bytes":152,"content-type":161,"debug":134,"type-is":1315}],131:[function(require,module,exports){ -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +function _iterableToArrayLimit(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; -'use strict' + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); -/** - * Module dependencies. - * @private - */ + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } -var bytes = require('bytes') -var contentType = require('content-type') -var createError = require('http-errors') -var debug = require('debug')('body-parser:urlencoded') -var deprecate = require('depd')('body-parser') -var read = require('../read') -var typeis = require('type-is') + return _arr; +} -/** - * Module exports. - */ +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} -module.exports = urlencoded +function _typeof(obj) { + if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj); + }; + } -/** - * Cache of parser modules. - */ + return _typeof(obj); +} -var parsers = Object.create(null) +(function (global, factory) { + (typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory(global.async = {}); +})(void 0, function (exports) { + 'use strict'; + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ -/** - * Create a middleware to parse urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ + function apply(fn) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } -function urlencoded (options) { - var opts = options || {} + return function () { + for (var _len2 = arguments.length, callArgs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + callArgs[_key2] = arguments[_key2]; + } - // notice because option default will flip in next major - if (opts.extended === undefined) { - deprecate('undefined extended: provide extended option') + return fn.apply(void 0, args.concat(callArgs)); + }; } - var extended = opts.extended !== false - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/x-www-form-urlencoded' - var verify = opts.verify || false + function initialParams(fn) { + return function () + /*, callback*/ + { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') + var callback = args.pop(); + return fn.call(this, args, callback); + }; } + /* istanbul ignore file */ - // create the appropriate query parser - var queryparse = extended - ? extendedparser(opts) - : simpleparser(opts) - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = (typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && typeof process.nextTick === 'function'; - function parse (body) { - return body.length - ? queryparse(body) - : {} + function fallback(fn) { + setTimeout(fn, 0); } - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} + function wrap(defer) { + return function (fn) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // assert charset - var charset = getCharset(req) || 'utf-8' - if (charset !== 'utf-8') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } - - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) + return defer(function () { + return fn.apply(void 0, args); + }); + }; } -} -/** - * Get the extended query parser. - * - * @param {object} options - */ - -function extendedparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('qs') + var _defer; - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback; } - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } + var setImmediate$1 = wrap(_defer); + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) + function asyncify(func) { + if (isAsync(func)) { + return function () + /*, callback*/ + { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) + var callback = args.pop(); + var promise = func.apply(this, args); + return handlePromise(promise, callback); + }; } - var arrayLimit = Math.max(100, paramCount) + return initialParams(function (args, callback) { + var result; - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) - } -} + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } // if result is Promise object -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); } -} -/** - * Count the number of parameters, stopping once limit reached - * - * @param {string} body - * @param {number} limit - * @api private - */ - -function parameterCount (body, limit) { - var count = 0 - var index = 0 - - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ - - if (count === limit) { - return undefined - } + function handlePromise(promise, callback) { + return promise.then(function (value) { + invokeCallback(callback, null, value); + }, function (err) { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); } - return count -} - -/** - * Get parser for module name dynamically. - * - * @param {string} name - * @return {function} - * @api private - */ - -function parser (name) { - var mod = parsers[name] - - if (mod !== undefined) { - return mod.parse + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(function (e) { + throw e; + }, err); + } } - // this uses a switch for static require analysis - switch (name) { - case 'qs': - mod = require('qs') - break - case 'querystring': - mod = require('querystring') - break + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; } - // store to prevent invoking require() - parsers[name] = mod - - return mod.parse -} - -/** - * Get the simple query parser. - * - * @param {object} options - */ - -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; } - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; } - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function'); + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } // conditionally promisify a function. + // only return a promise if a callback is omitted - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } - debug('parse urlencoding') - return parse(body, undefined, undefined, {maxKeys: parameterLimit}) - } -} + function awaitify(asyncFn) { + var arity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : asyncFn.length; + if (!arity) throw new Error('arity is undefined'); -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ + function awaitable() { + var _this = this; -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } -},{"../read":127,"bytes":152,"content-type":161,"debug":134,"depd":192,"http-errors":374,"qs":1223,"querystring":undefined,"type-is":1315}],132:[function(require,module,exports){ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args); + } -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + return new Promise(function (resolve, reject) { + args[arity - 1] = function (err) { + if (err) return reject(err); -/** - * Colors. - */ + for (var _len7 = arguments.length, cbArgs = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { + cbArgs[_key7 - 1] = arguments[_key7]; + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + asyncFn.apply(_this, args); + }); + } -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; + Object.defineProperty(awaitable, 'name', { + value: "awaitable(".concat(asyncFn.name, ")") + }); + return awaitable; } - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + function applyEach(eachfn) { + return function applyEach(fns) { + for (var _len8 = arguments.length, callArgs = new Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) { + callArgs[_key8 - 1] = arguments[_key8]; + } -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; + var go = awaitify(function (callback) { + var that = this; + return eachfn(fns, function (fn, cb) { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; } -}; + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + var _iteratee = wrapAsync(iteratee); - if (!useColors) return; + return eachfn(arr, function (value, _, iterCb) { + var index = counter++; - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + _iteratee(value, function (err, v) { + results[index] = v; + iterCb(err); + }); + }, function (err) { + callback(err, results); + }); + } - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + function isArrayLike(value) { + return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0; + } // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 - args.splice(lastC, 0, c); -} -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + var breakLoop = {}; -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} + function once(fn) { + function wrapper() { + if (fn === null) return; + var callFn = fn; + fn = null; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { + args[_key9] = arguments[_key9]; + } -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; + callFn.apply(this, args); } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; + Object.assign(wrapper, fn); + return wrapper; } - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ + function getIterator(coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } -exports.enable(load()); + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { + value: coll[i], + key: i + } : null; + }; + } -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { + value: item.value, + key: i + }; + }; + } -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? { + value: obj[key], + key: key + } : null; + }; + } -},{"./debug":133}],133:[function(require,module,exports){ + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); + function onlyOnce(fn) { + return function () { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; -/** - * The currently active debug mode names, and names to skip. - */ + for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { + args[_key10] = arguments[_key10]; + } -exports.names = []; -exports.skips = []; + callFn.apply(this, args); + }; + } // for async generators -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ -exports.formatters = {}; + function asyncEachOfLimit(generator, limit, iteratee, callback) { + var done = false; + var canceled = false; + var awaiting = false; + var running = 0; + var idx = 0; -/** - * Previous log timestamp. - */ + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return; //console.log('replenish awaiting') -var prevTime; + awaiting = true; + generator.next().then(function (_ref) { + var value = _ref.value, + iterDone = _ref.done; //console.log('got value', value) -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + if (canceled || done) return; + awaiting = false; -function selectColor(namespace) { - var hash = 0, i; + if (iterDone) { + done = true; - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + return; + } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + })["catch"](handleError); + } -function createDebug(namespace) { + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return; + if (err) return handleError(err); - function debug() { - // disabled? - if (!debug.enabled) return; + if (err === false) { + done = true; + canceled = true; + return; + } - var self = debug; + if (result === breakLoop || done && running <= 0) { + done = true; //console.log('done iterCb') - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + return callback(null); + } - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + replenish(); } - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + function handleError(err) { + if (canceled) return; + awaiting = false; + done = true; + callback(err); } - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + replenish(); + } - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + var eachOfLimit = function eachOfLimit(limit) { + return function (obj, iteratee, callback) { + callback = once(callback); - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1'); + } - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + if (!obj) { + return callback(null); + } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback); + } - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback); + } - return debug; -} + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + function iterateeCallback(err, value) { + if (canceled) return; + running -= 1; -function enable(namespaces) { - exports.save(namespaces); + if (err) { + done = true; + callback(err); + } else if (err === false) { + done = true; + canceled = true; + } else if (value === breakLoop || done && running <= 0) { + done = true; + return callback(null); + } else if (!looping) { + replenish(); + } + } - exports.names = []; - exports.skips = []; + function replenish() { + looping = true; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + while (running < limit && !done) { + var elem = nextElem(); - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} + if (elem === null) { + done = true; -/** - * Disable debug output. - * - * @api public - */ + if (running <= 0) { + callback(null); + } -function disable() { - exports.enable(''); -} + return; + } -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} + looping = false; + } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ + replenish(); + }; + }; + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} -},{"ms":966}],134:[function(require,module,exports){ -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + function eachOfLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); + } -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = require('./browser.js'); -} else { - module.exports = require('./node.js'); -} + var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); // eachOf implementation optimized for array-likes -},{"./browser.js":132,"./node.js":135}],135:[function(require,module,exports){ -/** - * Module dependencies. - */ + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + length = coll.length, + canceled = false; -var tty = require('tty'); -var util = require('util'); + if (length === 0) { + callback(null); + } -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } -exports = module.exports = require('./debug'); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; + if (canceled === true) return; -/** - * Colors. - */ + if (err) { + callback(err); + } else if (++completed === length || value === breakLoop) { + callback(null); + } + } -exports.colors = [6, 2, 3, 4, 5, 1]; + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } // a generic version of eachOf which can handle array, object, and iterator cases. -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + function eachOfGeneric(coll, iteratee, callback) { + return eachOfLimit$2(coll, Infinity, iteratee, callback); + } + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - obj[prop] = val; - return obj; -}, {}); + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ + var eachOf$1 = awaitify(eachOf, 3); + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + function map(coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback); + } -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} + var map$1 = awaitify(map, 3); + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + var applyEach$1 = applyEach(map$1); + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$2(coll, 1, iteratee, callback); + } -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ -/** - * Map %o to `util.inspect()`, all on a single line. - */ + function mapSeries(coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback); + } -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; + var mapSeries$1 = awaitify(mapSeries, 3); + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + var applyEachSeries = applyEach(mapSeries$1); + var PROMISE_SYMBOL = Symbol('promiseCallback'); -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + function promiseCallback() { + var resolve, reject; -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + function callback(err) { + if (err) return reject(err); -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + for (var _len11 = arguments.length, args = new Array(_len11 > 1 ? _len11 - 1 : 0), _key11 = 1; _key11 < _len11; _key11++) { + args[_key11 - 1] = arguments[_key11]; + } - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + resolve(args.length > 1 ? args : args[0]); + } - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; + callback[PROMISE_SYMBOL] = new Promise(function (res, rej) { + resolve = res, reject = rej; + }); + return callback; } -} + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} + if (!numTasks) { + return callback(null); + } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + if (!concurrency) { + concurrency = numTasks; + } -function load() { - return process.env.DEBUG; -} + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + var listeners = Object.create(null); + var readyTasks = []; // for cycle detection: -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); + var uncheckedDependencies = {}; + Object.keys(tasks).forEach(function (key) { + var task = tasks[key]; - // Note stream._type is used for test-module-load-list.js + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; } - break; - case 'FILE': - var fs = require('fs'); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + uncheckedDependencies[key] = remainingDependencies; + dependencies.forEach(function (dependencyName) { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); + } - case 'PIPE': - case 'TCP': - var net = require('net'); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true + addListener(dependencyName, function () { + remainingDependencies--; + + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); }); + }); + checkForDeadlocks(); + processQueue(); - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; + function enqueueTask(key, task) { + readyTasks.push(function () { + return runTask(key, task); + }); + } - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + function processQueue() { + if (canceled) return; - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } - // For supporting legacy API we put the FD here. - stream.fd = fd; + while (readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + } - stream._isStdio = true; + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; - return stream; -} + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + taskListeners.push(fn); + } -function init (debug) { - debug.inspectOpts = {}; + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(function (fn) { + return fn(); + }); + processQueue(); + } - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + function runTask(key, task) { + if (hasError) return; + var taskCallback = onlyOnce(function (err) { + for (var _len12 = arguments.length, result = new Array(_len12 > 1 ? _len12 - 1 : 0), _key12 = 1; _key12 < _len12; _key12++) { + result[_key12 - 1] = arguments[_key12]; + } -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ + runningTasks--; -exports.enable(load()); + if (err === false) { + canceled = true; + return; + } -},{"./debug":133,"fs":undefined,"net":undefined,"tty":undefined,"util":undefined}],136:[function(require,module,exports){ -'use strict' + if (result.length < 2) { + var _result = result; -const Bignumber = require('bignumber.js') + var _result2 = _slicedToArray(_result, 1); -exports.MT = { - POS_INT: 0, - NEG_INT: 1, - BYTE_STRING: 2, - UTF8_STRING: 3, - ARRAY: 4, - MAP: 5, - TAG: 6, - SIMPLE_FLOAT: 7 -} + result = _result2[0]; + } -exports.TAG = { - DATE_STRING: 0, - DATE_EPOCH: 1, - POS_BIGINT: 2, - NEG_BIGINT: 3, - DECIMAL_FRAC: 4, - BIGFLOAT: 5, - BASE64URL_EXPECTED: 21, - BASE64_EXPECTED: 22, - BASE16_EXPECTED: 23, - CBOR: 24, - URI: 32, - BASE64URL: 33, - BASE64: 34, - REGEXP: 35, - MIME: 36 -} + if (err) { + var safeResults = {}; + Object.keys(results).forEach(function (rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return; + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); -exports.NUMBYTES = { - ZERO: 0, - ONE: 24, - TWO: 25, - FOUR: 26, - EIGHT: 27, - INDEFINITE: 31 -} + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } -exports.SIMPLE = { - FALSE: 20, - TRUE: 21, - NULL: 22, - UNDEFINED: 23 -} + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(function (dependent) { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } -exports.SYMS = { - NULL: Symbol('null'), - UNDEFINED: Symbol('undef'), - PARENT: Symbol('parent'), - BREAK: Symbol('break'), - STREAM: Symbol('stream') -} + if (counter !== numTasks) { + throw new Error('async.auto cannot execute tasks due to a recursive dependency'); + } + } -exports.SHIFT32 = Math.pow(2, 32) -exports.SHIFT16 = Math.pow(2, 16) + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(function (key) { + var task = tasks[key]; -exports.MAX_SAFE_HIGH = 0x1fffff -exports.NEG_ONE = new Bignumber(-1) -exports.TEN = new Bignumber(10) -exports.TWO = new Bignumber(2) + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } -exports.PARENT = { - ARRAY: 0, - OBJECT: 1, - MAP: 2, - TAG: 3, - BYTE_STRING: 4, - UTF8_STRING: 5 -} + return callback[PROMISE_SYMBOL]; + } -},{"bignumber.js":79}],137:[function(require,module,exports){ -module.exports = function decodeAsm (stdlib, foreign, buffer) { - 'use asm' + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - // -- Imports + function parseParams(func) { + var src = func.toString().replace(STRIP_COMMENTS, ''); + var match = src.match(FN_ARGS); - var heap = new stdlib.Uint8Array(buffer) - // var log = foreign.log - var pushInt = foreign.pushInt - var pushInt32 = foreign.pushInt32 - var pushInt32Neg = foreign.pushInt32Neg - var pushInt64 = foreign.pushInt64 - var pushInt64Neg = foreign.pushInt64Neg - var pushFloat = foreign.pushFloat - var pushFloatSingle = foreign.pushFloatSingle - var pushFloatDouble = foreign.pushFloatDouble - var pushTrue = foreign.pushTrue - var pushFalse = foreign.pushFalse - var pushUndefined = foreign.pushUndefined - var pushNull = foreign.pushNull - var pushInfinity = foreign.pushInfinity - var pushInfinityNeg = foreign.pushInfinityNeg - var pushNaN = foreign.pushNaN - var pushNaNNeg = foreign.pushNaNNeg + if (!match) { + match = src.match(ARROW_FN_ARGS); + } - var pushArrayStart = foreign.pushArrayStart - var pushArrayStartFixed = foreign.pushArrayStartFixed - var pushArrayStartFixed32 = foreign.pushArrayStartFixed32 - var pushArrayStartFixed64 = foreign.pushArrayStartFixed64 - var pushObjectStart = foreign.pushObjectStart - var pushObjectStartFixed = foreign.pushObjectStartFixed - var pushObjectStartFixed32 = foreign.pushObjectStartFixed32 - var pushObjectStartFixed64 = foreign.pushObjectStartFixed64 + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src); - var pushByteString = foreign.pushByteString - var pushByteStringStart = foreign.pushByteStringStart - var pushUtf8String = foreign.pushUtf8String - var pushUtf8StringStart = foreign.pushUtf8StringStart + var _match = match, + _match2 = _slicedToArray(_match, 2), + args = _match2[1]; - var pushSimpleUnassigned = foreign.pushSimpleUnassigned + return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(function (arg) { + return arg.replace(FN_ARG, '').trim(); + }); + } + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ - var pushTagStart = foreign.pushTagStart - var pushTagStart4 = foreign.pushTagStart4 - var pushTagStart8 = foreign.pushTagStart8 - var pushTagUnassigned = foreign.pushTagUnassigned - var pushBreak = foreign.pushBreak + function autoInject(tasks, callback) { + var newTasks = {}; + Object.keys(tasks).forEach(function (key) { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; + + if (Array.isArray(taskFn)) { + params = _toConsumableArray(taskFn); + taskFn = params.pop(); + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); - var pow = stdlib.Math.pow + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } // remove callback param - // -- Constants + if (!fnIsAsync) params.pop(); + newTasks[key] = params.concat(newTask); + } - // -- Mutable Variables + function newTask(results, taskCb) { + var newArgs = params.map(function (name) { + return results[name]; + }); + newArgs.push(taskCb); + wrapAsync(taskFn).apply(void 0, _toConsumableArray(newArgs)); + } + }); + return auto(newTasks, callback); + } // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. - var offset = 0 - var inputLength = 0 - var code = 0 - // Decode a cbor string represented as Uint8Array - // which is allocated on the heap from 0 to inputLength - // - // input - Int - // - // Returns Code - Int, - // Success = 0 - // Error > 0 - function parse (input) { - input = input | 0 + var DLL = + /*#__PURE__*/ + function () { + function DLL() { + _classCallCheck(this, DLL); - offset = 0 - inputLength = input + this.head = this.tail = null; + this.length = 0; + } - while ((offset | 0) < (inputLength | 0)) { - code = jumpTable[heap[offset] & 255](heap[offset] | 0) | 0 + _createClass(DLL, [{ + key: "removeLink", + value: function removeLink(node) { + if (node.prev) node.prev.next = node.next;else this.head = node.next; + if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + node.prev = node.next = null; + this.length -= 1; + return node; + } + }, { + key: "empty", + value: function empty() { + while (this.head) { + this.shift(); + } - if ((code | 0) > 0) { - break + return this; } - } + }, { + key: "insertAfter", + value: function insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode;else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + }, { + key: "insertBefore", + value: function insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode;else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + }, { + key: "unshift", + value: function unshift(node) { + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); + } + }, { + key: "push", + value: function push(node) { + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); + } + }, { + key: "shift", + value: function shift() { + return this.head && this.removeLink(this.head); + } + }, { + key: "pop", + value: function pop() { + return this.tail && this.removeLink(this.tail); + } + }, { + key: "toArray", + value: function toArray() { + return _toConsumableArray(this); + } + }, { + key: Symbol.iterator, + value: + /*#__PURE__*/ + regeneratorRuntime.mark(function value() { + var cur; + return regeneratorRuntime.wrap(function value$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + cur = this.head; + + case 1: + if (!cur) { + _context.next = 7; + break; + } - return code | 0 - } + _context.next = 4; + return cur.data; - // -- Helper Function + case 4: + cur = cur.next; + _context.next = 1; + break; - function checkOffset (n) { - n = n | 0 + case 7: + case "end": + return _context.stop(); + } + } + }, value, this); + }) + }, { + key: "remove", + value: function remove(testFn) { + var curr = this.head; - if ((((offset | 0) + (n | 0)) | 0) < (inputLength | 0)) { - return 0 - } + while (curr) { + var _curr = curr, + next = _curr.next; - return 1 - } + if (testFn(curr)) { + this.removeLink(curr); + } - function readUInt16 (n) { - n = n | 0 + curr = next; + } - return ( - (heap[n | 0] << 8) | heap[(n + 1) | 0] - ) | 0 - } + return this; + } + }]); - function readUInt32 (n) { - n = n | 0 + return DLL; + }(); - return ( - (heap[n | 0] << 24) | (heap[(n + 1) | 0] << 16) | (heap[(n + 2) | 0] << 8) | heap[(n + 3) | 0] - ) | 0 + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; } - // -- Initial Byte Handlers - - function INT_P (octet) { - octet = octet | 0 - - pushInt(octet | 0) + function queue(worker, concurrency, payload) { + var _q; - offset = (offset + 1) | 0 + if (concurrency == null) { + concurrency = 1; + } else if (concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } - return 0 - } + var _worker = wrapAsync(worker); - function UINT_P_8 (octet) { - octet = octet | 0 + var numRunning = 0; + var _workersList = []; + var events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; - if (checkOffset(1) | 0) { - return 1 + function on(event, handler) { + events[event].push(handler); } - pushInt(heap[(offset + 1) | 0] | 0) + function once(event, handler) { + var handleAndRemove = function handleAndRemove() { + off(event, handleAndRemove); + handler.apply(void 0, arguments); + }; - offset = (offset + 2) | 0 + events[event].push(handleAndRemove); + } - return 0 - } + function off(event, handler) { + if (!event) return Object.keys(events).forEach(function (ev) { + return events[ev] = []; + }); + if (!handler) return events[event] = []; + events[event] = events[event].filter(function (ev) { + return ev !== handler; + }); + } - function UINT_P_16 (octet) { - octet = octet | 0 + function trigger(event) { + for (var _len13 = arguments.length, args = new Array(_len13 > 1 ? _len13 - 1 : 0), _key13 = 1; _key13 < _len13; _key13++) { + args[_key13 - 1] = arguments[_key13]; + } - if (checkOffset(2) | 0) { - return 1 + events[event].forEach(function (handler) { + return handler.apply(void 0, args); + }); } - pushInt( - readUInt16((offset + 1) | 0) | 0 - ) + var processingScheduled = false; - offset = (offset + 3) | 0 + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } - return 0 - } + q.started = true; + var res, rej; - function UINT_P_32 (octet) { - octet = octet | 0 + function promiseCallback(err) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res(); - if (checkOffset(4) | 0) { - return 1 - } + for (var _len14 = arguments.length, args = new Array(_len14 > 1 ? _len14 - 1 : 0), _key14 = 1; _key14 < _len14; _key14++) { + args[_key14 - 1] = arguments[_key14]; + } - pushInt32( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) + if (args.length <= 1) return res(args[0]); + res(args); + } - offset = (offset + 5) | 0 + var item = { + data: data, + callback: rejectOnError ? promiseCallback : callback || promiseCallback + }; - return 0 - } + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } - function UINT_P_64 (octet) { - octet = octet | 0 + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(function () { + processingScheduled = false; + q.process(); + }); + } - if (checkOffset(8) | 0) { - return 1 + if (rejectOnError || !callback) { + return new Promise(function (resolve, reject) { + res = resolve; + rej = reject; + }); + } } - pushInt64( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) + function _createCB(tasks) { + return function (err) { + numRunning -= 1; - offset = (offset + 9) | 0 + for (var _len15 = arguments.length, args = new Array(_len15 > 1 ? _len15 - 1 : 0), _key15 = 1; _key15 < _len15; _key15++) { + args[_key15 - 1] = arguments[_key15]; + } - return 0 - } + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; - function INT_N (octet) { - octet = octet | 0 + var index = _workersList.indexOf(task); - pushInt((-1 - ((octet - 32) | 0)) | 0) + if (index === 0) { + _workersList.shift(); + } else if (index > 0) { + _workersList.splice(index, 1); + } - offset = (offset + 1) | 0 + task.callback.apply(task, [err].concat(args)); - return 0 - } + if (err != null) { + trigger('error', err, task.data); + } + } - function UINT_N_8 (octet) { - octet = octet | 0 + if (numRunning <= q.concurrency - q.buffer) { + trigger('unsaturated'); + } - if (checkOffset(1) | 0) { - return 1 + if (q.idle()) { + trigger('drain'); + } + + q.process(); + }; } - pushInt( - (-1 - (heap[(offset + 1) | 0] | 0)) | 0 - ) + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(function () { + return trigger('drain'); + }); + return true; + } - offset = (offset + 2) | 0 + return false; + } - return 0 - } + var eventMethod = function eventMethod(name) { + return function (handler) { + if (!handler) { + return new Promise(function (resolve, reject) { + once(name, function (err, data) { + if (err) return reject(err); + resolve(data); + }); + }); + } - function UINT_N_16 (octet) { - octet = octet | 0 + off(name); + on(name, handler); + }; + }; - var val = 0 + var isProcessing = false; + var q = (_q = { + _tasks: new DLL() + }, _defineProperty(_q, Symbol.iterator, + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee() { + return regeneratorRuntime.wrap(function _callee$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + return _context2.delegateYield(q._tasks[Symbol.iterator](), "t0", 1); - if (checkOffset(2) | 0) { - return 1 - } + case 1: + case "end": + return _context2.stop(); + } + } + }, _callee); + })), _defineProperty(_q, "concurrency", concurrency), _defineProperty(_q, "payload", payload), _defineProperty(_q, "buffer", concurrency / 4), _defineProperty(_q, "started", false), _defineProperty(_q, "paused", false), _defineProperty(_q, "push", function push(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(function (datum) { + return _insert(datum, false, false, callback); + }); + } - val = readUInt16((offset + 1) | 0) | 0 - pushInt((-1 - (val | 0)) | 0) + return _insert(data, false, false, callback); + }), _defineProperty(_q, "pushAsync", function pushAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(function (datum) { + return _insert(datum, false, true, callback); + }); + } - offset = (offset + 3) | 0 + return _insert(data, false, true, callback); + }), _defineProperty(_q, "kill", function kill() { + off(); - return 0 - } + q._tasks.empty(); + }), _defineProperty(_q, "unshift", function unshift(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(function (datum) { + return _insert(datum, true, false, callback); + }); + } - function UINT_N_32 (octet) { - octet = octet | 0 + return _insert(data, true, false, callback); + }), _defineProperty(_q, "unshiftAsync", function unshiftAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(function (datum) { + return _insert(datum, true, true, callback); + }); + } - if (checkOffset(4) | 0) { - return 1 - } + return _insert(data, true, true, callback); + }), _defineProperty(_q, "remove", function remove(testFn) { + q._tasks.remove(testFn); + }), _defineProperty(_q, "process", function process() { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } - pushInt32Neg( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) + isProcessing = true; - offset = (offset + 5) | 0 + while (!q.paused && numRunning < q.concurrency && q._tasks.length) { + var tasks = [], + data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); - return 0 - } + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); - function UINT_N_64 (octet) { - octet = octet | 0 + tasks.push(node); - if (checkOffset(8) | 0) { - return 1 - } + _workersList.push(node); - pushInt64Neg( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) + data.push(node.data); + } - offset = (offset + 9) | 0 + numRunning += 1; - return 0 - } + if (q._tasks.length === 0) { + trigger('empty'); + } - function BYTE_STRING (octet) { - octet = octet | 0 + if (numRunning === q.concurrency) { + trigger('saturated'); + } - var start = 0 - var end = 0 - var step = 0 + var cb = onlyOnce(_createCB(tasks)); - step = (octet - 64) | 0 - if (checkOffset(step | 0) | 0) { - return 1 - } + _worker(data, cb); + } - start = (offset + 1) | 0 - end = (((offset + 1) | 0) + (step | 0)) | 0 + isProcessing = false; + }), _defineProperty(_q, "length", function length() { + return q._tasks.length; + }), _defineProperty(_q, "running", function running() { + return numRunning; + }), _defineProperty(_q, "workersList", function workersList() { + return _workersList; + }), _defineProperty(_q, "idle", function idle() { + return q._tasks.length + numRunning === 0; + }), _defineProperty(_q, "pause", function pause() { + q.paused = true; + }), _defineProperty(_q, "resume", function resume() { + if (q.paused === false) { + return; + } - pushByteString(start | 0, end | 0) + q.paused = false; + setImmediate$1(q.process); + }), _q); // define these as fixed properties, so people get useful errors when updating - offset = end | 0 - - return 0 + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + } + }); + return q; } + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i 1 ? _len18 - 1 : 0), _key18 = 1; _key18 < _len18; _key18++) { + nextargs[_key18 - 1] = arguments[_key18]; + } - length = readUInt32((offset + 1) | 0) | 0 - start = (offset + 5) | 0 - end = (((offset + 5) | 0) + (length | 0)) | 0 + iterCb(err, nextargs); + })); + }, function (err, results) { + return cb.apply(void 0, [err].concat(_toConsumableArray(results))); + }); + return cb[PROMISE_SYMBOL]; + }; + } + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ - if (checkOffset((length + 4) | 0) | 0) { - return 1 + function compose() { + for (var _len19 = arguments.length, args = new Array(_len19), _key19 = 0; _key19 < _len19; _key19++) { + args[_key19] = arguments[_key19]; } - pushByteString(start | 0, end | 0) - - offset = end | 0 - - return 0 - } - - function BYTE_STRING_64 (octet) { - // NOT IMPLEMENTED - octet = octet | 0 - - return 1 + return seq.apply(void 0, _toConsumableArray(args.reverse())); } + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ - function BYTE_STRING_BREAK (octet) { - octet = octet | 0 - - pushByteStringStart() - - offset = (offset + 1) | 0 - return 0 + function mapLimit(coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit(limit), coll, iteratee, callback); } - function UTF8_STRING (octet) { - octet = octet | 0 + var mapLimit$1 = awaitify(mapLimit, 4); + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ - var start = 0 - var end = 0 - var step = 0 + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); - step = (octet - 96) | 0 + return mapLimit$1(coll, limit, function (val, iterCb) { + _iteratee(val, function (err) { + if (err) return iterCb(err); - if (checkOffset(step | 0) | 0) { - return 1 - } + for (var _len20 = arguments.length, args = new Array(_len20 > 1 ? _len20 - 1 : 0), _key20 = 1; _key20 < _len20; _key20++) { + args[_key20 - 1] = arguments[_key20]; + } - start = (offset + 1) | 0 - end = (((offset + 1) | 0) + (step | 0)) | 0 + return iterCb(err, args); + }); + }, function (err, mapResults) { + var result = []; - pushUtf8String(start | 0, end | 0) + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var _result3; - offset = end | 0 + result = (_result3 = result).concat.apply(_result3, _toConsumableArray(mapResults[i])); + } + } - return 0 + return callback(err, result); + }); } - function UTF8_STRING_8 (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var length = 0 - - if (checkOffset(1) | 0) { - return 1 - } - - length = heap[(offset + 1) | 0] | 0 - start = (offset + 2) | 0 - end = (((offset + 2) | 0) + (length | 0)) | 0 - - if (checkOffset((length + 1) | 0) | 0) { - return 1 - } - - pushUtf8String(start | 0, end | 0) - - offset = end | 0 + var concatLimit$1 = awaitify(concatLimit, 4); + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { + * // files is now a list of filenames that exist in the 3 directories + * }); + */ - return 0 + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback); } - function UTF8_STRING_16 (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var length = 0 + var concat$1 = awaitify(concat, 3); + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ - if (checkOffset(2) | 0) { - return 1 - } + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback); + } - length = readUInt16((offset + 1) | 0) | 0 - start = (offset + 3) | 0 - end = (((offset + 3) | 0) + (length | 0)) | 0 + var concatSeries$1 = awaitify(concatSeries, 3); + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ - if (checkOffset((length + 2) | 0) | 0) { - return 1 + function constant() { + for (var _len21 = arguments.length, args = new Array(_len21), _key21 = 0; _key21 < _len21; _key21++) { + args[_key21] = arguments[_key21]; } - pushUtf8String(start | 0, end | 0) - - offset = end | 0 + return function () + /*, callback*/ + { + for (var _len22 = arguments.length, ignoredArgs = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) { + ignoredArgs[_key22] = arguments[_key22]; + } - return 0 + var callback = ignoredArgs.pop(); + return callback.apply(void 0, [null].concat(args)); + }; } - function UTF8_STRING_32 (octet) { - octet = octet | 0 + function _createTester(check, getResult) { + return function (eachfn, arr, _iteratee, cb) { + var testPassed = false; + var testResult; + var iteratee = wrapAsync(_iteratee); + eachfn(arr, function (value, _, callback) { + iteratee(value, function (err, result) { + if (err || err === false) return callback(err); - var start = 0 - var end = 0 - var length = 0 - - if (checkOffset(4) | 0) { - return 1 - } + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } - length = readUInt32((offset + 1) | 0) | 0 - start = (offset + 5) | 0 - end = (((offset + 5) | 0) + (length | 0)) | 0 + callback(); + }); + }, function (err) { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ - if (checkOffset((length + 4) | 0) | 0) { - return 1 - } - pushUtf8String(start | 0, end | 0) + function detect(coll, iteratee, callback) { + return _createTester(function (bool) { + return bool; + }, function (res, item) { + return item; + })(eachOf$1, coll, iteratee, callback); + } - offset = end | 0 + var detect$1 = awaitify(detect, 3); + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ - return 0 + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(function (bool) { + return bool; + }, function (res, item) { + return item; + })(eachOfLimit(limit), coll, iteratee, callback); } - function UTF8_STRING_64 (octet) { - // NOT IMPLEMENTED - octet = octet | 0 + var detectLimit$1 = awaitify(detectLimit, 4); + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ - return 1 + function detectSeries(coll, iteratee, callback) { + return _createTester(function (bool) { + return bool; + }, function (res, item) { + return item; + })(eachOfLimit(1), coll, iteratee, callback); } - function UTF8_STRING_BREAK (octet) { - octet = octet | 0 + var detectSeries$1 = awaitify(detectSeries, 3); - pushUtf8StringStart() + function consoleFunc(name) { + return function (fn) { + for (var _len23 = arguments.length, args = new Array(_len23 > 1 ? _len23 - 1 : 0), _key23 = 1; _key23 < _len23; _key23++) { + args[_key23 - 1] = arguments[_key23]; + } - offset = (offset + 1) | 0 + return wrapAsync(fn).apply(void 0, args.concat([function (err) { + if ((typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + for (var _len24 = arguments.length, resultArgs = new Array(_len24 > 1 ? _len24 - 1 : 0), _key24 = 1; _key24 < _len24; _key24++) { + resultArgs[_key24 - 1] = arguments[_key24]; + } - return 0 + resultArgs.forEach(function (x) { + return console[name](x); + }); + } + } + }])); + }; } + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ - function ARRAY (octet) { - octet = octet | 0 - - pushArrayStartFixed((octet - 128) | 0) - offset = (offset + 1) | 0 + var dir = consoleFunc('dir'); + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ - return 0 - } + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); - function ARRAY_8 (octet) { - octet = octet | 0 + var _fn = wrapAsync(iteratee); - if (checkOffset(1) | 0) { - return 1 - } + var _test = wrapAsync(test); - pushArrayStartFixed(heap[(offset + 1) | 0] | 0) + var results; - offset = (offset + 2) | 0 + function next(err) { + if (err) return callback(err); + if (err === false) return; - return 0 - } + for (var _len25 = arguments.length, args = new Array(_len25 > 1 ? _len25 - 1 : 0), _key25 = 1; _key25 < _len25; _key25++) { + args[_key25 - 1] = arguments[_key25]; + } - function ARRAY_16 (octet) { - octet = octet | 0 + results = args; - if (checkOffset(2) | 0) { - return 1 + _test.apply(void 0, args.concat([check])); } - pushArrayStartFixed( - readUInt16((offset + 1) | 0) | 0 - ) + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback.apply(void 0, [null].concat(_toConsumableArray(results))); - offset = (offset + 3) | 0 + _fn(next); + } - return 0 + return check(null, true); } - function ARRAY_32 (octet) { - octet = octet | 0 + var doWhilst$1 = awaitify(doWhilst, 3); + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ - if (checkOffset(4) | 0) { - return 1 - } + function doUntil(iteratee, test, callback) { + var _test = wrapAsync(test); - pushArrayStartFixed32( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) + return doWhilst$1(iteratee, function () { + for (var _len26 = arguments.length, args = new Array(_len26), _key26 = 0; _key26 < _len26; _key26++) { + args[_key26] = arguments[_key26]; + } - offset = (offset + 5) | 0 + var cb = args.pop(); - return 0 + _test.apply(void 0, args.concat([function (err, truth) { + return cb(err, !truth); + }])); + }, callback); } - function ARRAY_64 (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } - - pushArrayStartFixed64( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) + function _withoutIndex(iteratee) { + return function (value, index, callback) { + return iteratee(value, callback); + }; + } + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ - offset = (offset + 9) | 0 - return 0 + function eachLimit(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); } - function ARRAY_BREAK (octet) { - octet = octet | 0 + var each = awaitify(eachLimit, 3); + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ - pushArrayStart() + function eachLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } - offset = (offset + 1) | 0 + var eachLimit$2 = awaitify(eachLimit$1, 4); + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ - return 0 + function eachSeries(coll, iteratee, callback) { + return eachLimit$2(coll, 1, iteratee, callback); } - function MAP (octet) { - octet = octet | 0 - - var step = 0 + var eachSeries$1 = awaitify(eachSeries, 3); + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ - step = (octet - 160) | 0 + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function () + /*, callback*/ + { + for (var _len27 = arguments.length, args = new Array(_len27), _key27 = 0; _key27 < _len27; _key27++) { + args[_key27] = arguments[_key27]; + } - if (checkOffset(step | 0) | 0) { - return 1 - } + var callback = args.pop(); + var sync = true; + args.push(function () { + for (var _len28 = arguments.length, innerArgs = new Array(_len28), _key28 = 0; _key28 < _len28; _key28++) { + innerArgs[_key28] = arguments[_key28]; + } - pushObjectStartFixed(step | 0) + if (sync) { + setImmediate$1(function () { + return callback.apply(void 0, innerArgs); + }); + } else { + callback.apply(void 0, innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ - offset = (offset + 1) | 0 - return 0 + function every(coll, iteratee, callback) { + return _createTester(function (bool) { + return !bool; + }, function (res) { + return !res; + })(eachOf$1, coll, iteratee, callback); } - function MAP_8 (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 - } + var every$1 = awaitify(every, 3); + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ - pushObjectStartFixed(heap[(offset + 1) | 0] | 0) + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(function (bool) { + return !bool; + }, function (res) { + return !res; + })(eachOfLimit(limit), coll, iteratee, callback); + } - offset = (offset + 2) | 0 + var everyLimit$1 = awaitify(everyLimit, 4); + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ - return 0 + function everySeries(coll, iteratee, callback) { + return _createTester(function (bool) { + return !bool; + }, function (res) { + return !res; + })(eachOfSeries$1, coll, iteratee, callback); } - function MAP_16 (octet) { - octet = octet | 0 - - if (checkOffset(2) | 0) { - return 1 - } + var everySeries$1 = awaitify(everySeries, 3); - pushObjectStartFixed( - readUInt16((offset + 1) | 0) | 0 - ) + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, function (x, index, iterCb) { + iteratee(x, function (err, v) { + truthValues[index] = !!v; + iterCb(err); + }); + }, function (err) { + if (err) return callback(err); + var results = []; - offset = (offset + 3) | 0 + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } - return 0 + callback(null, results); + }); } - function MAP_32 (octet) { - octet = octet | 0 + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, function (x, index, iterCb) { + iteratee(x, function (err, v) { + if (err) return iterCb(err); + + if (v) { + results.push({ + index: index, + value: x + }); + } - if (checkOffset(4) | 0) { - return 1 - } + iterCb(err); + }); + }, function (err) { + if (err) return callback(err); + callback(null, results.sort(function (a, b) { + return a.index - b.index; + }).map(function (v) { + return v.value; + })); + }); + } - pushObjectStartFixed32( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ - offset = (offset + 5) | 0 - return 0 + function filter(coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback); } - function MAP_64 (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } + var filter$1 = awaitify(filter, 3); + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ - pushObjectStartFixed64( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) + function filterLimit(coll, limit, iteratee, callback) { + return _filter(eachOfLimit(limit), coll, iteratee, callback); + } - offset = (offset + 9) | 0 + var filterLimit$1 = awaitify(filterLimit, 4); + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ - return 0 + function filterSeries(coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback); } - function MAP_BREAK (octet) { - octet = octet | 0 + var filterSeries$1 = awaitify(filterSeries, 3); + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ - pushObjectStart() + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); - offset = (offset + 1) | 0 + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } - return 0 + return next(); } - function TAG_KNOWN (octet) { - octet = octet | 0 - - pushTagStart((octet - 192| 0) | 0) + var forever$1 = awaitify(forever, 2); + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ - offset = (offset + 1 | 0) + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); - return 0 - } + return mapLimit$1(coll, limit, function (val, iterCb) { + _iteratee(val, function (err, key) { + if (err) return iterCb(err); + return iterCb(err, { + key: key, + val: val + }); + }); + }, function (err, mapResults) { + var result = {}; // from MDN, handle object having an `hasOwnProperty` prop - function TAG_BIGNUM_POS (octet) { - octet = octet | 0 + var hasOwnProperty = Object.prototype.hasOwnProperty; - pushTagStart(octet | 0) + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var key = mapResults[i].key; + var val = mapResults[i].val; - offset = (offset + 1 | 0) + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } - return 0 + return callback(err, result); + }); } - function TAG_BIGNUM_NEG (octet) { - octet = octet | 0 + var groupByLimit$1 = awaitify(groupByLimit, 4); + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ - pushTagStart(octet | 0) + function groupBy(coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback); + } + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ - offset = (offset + 1 | 0) - return 0 + function groupBySeries(coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback); } + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ - function TAG_FRAC (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - offset = (offset + 1 | 0) + var log = consoleFunc('log'); + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ - return 0 - } + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; - function TAG_BIGNUM_FLOAT (octet) { - octet = octet | 0 + var _iteratee = wrapAsync(iteratee); - pushTagStart(octet | 0) + return eachOfLimit(limit)(obj, function (val, key, next) { + _iteratee(val, key, function (err, result) { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, function (err) { + return callback(err, newObj); + }); + } - offset = (offset + 1 | 0) + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ - return 0 + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback); } + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ - function TAG_UNASSIGNED (octet) { - octet = octet | 0 - pushTagStart((octet - 192| 0) | 0) + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback); + } + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ - offset = (offset + 1 | 0) - return 0 - } + function memoize(fn) { + var hasher = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (v) { + return v; + }; + var memo = Object.create(null); + var queues = Object.create(null); - function TAG_BASE64_URL (octet) { - octet = octet | 0 + var _fn = wrapAsync(fn); - pushTagStart(octet | 0) + var memoized = initialParams(function (args, callback) { + var key = hasher.apply(void 0, _toConsumableArray(args)); - offset = (offset + 1 | 0) + if (key in memo) { + setImmediate$1(function () { + return callback.apply(void 0, [null].concat(_toConsumableArray(memo[key]))); + }); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; - return 0 - } + _fn.apply(void 0, _toConsumableArray(args).concat([function (err) { + for (var _len29 = arguments.length, resultArgs = new Array(_len29 > 1 ? _len29 - 1 : 0), _key29 = 1; _key29 < _len29; _key29++) { + resultArgs[_key29 - 1] = arguments[_key29]; + } // #1465 don't memoize if an error occurred - function TAG_BASE64 (octet) { - octet = octet | 0 - pushTagStart(octet | 0) + if (!err) { + memo[key] = resultArgs; + } - offset = (offset + 1 | 0) + var q = queues[key]; + delete queues[key]; - return 0 + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(q, [err].concat(resultArgs)); + } + }])); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; } + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ - function TAG_BASE16 (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - offset = (offset + 1 | 0) + var _defer$1; - return 0 + if (hasNextTick) { + _defer$1 = process.nextTick; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else { + _defer$1 = fallback; } - function TAG_MORE_1 (octet) { - octet = octet | 0 + var nextTick = wrap(_defer$1); - if (checkOffset(1) | 0) { - return 1 - } + var _parallel = awaitify(function (eachfn, tasks, callback) { + var results = isArrayLike(tasks) ? [] : {}; + eachfn(tasks, function (task, key, taskCb) { + wrapAsync(task)(function (err) { + for (var _len30 = arguments.length, result = new Array(_len30 > 1 ? _len30 - 1 : 0), _key30 = 1; _key30 < _len30; _key30++) { + result[_key30 - 1] = arguments[_key30]; + } - pushTagStart(heap[(offset + 1) | 0] | 0) + if (result.length < 2) { + var _result4 = result; - offset = (offset + 2 | 0) + var _result5 = _slicedToArray(_result4, 1); - return 0 - } + result = _result5[0]; + } - function TAG_MORE_2 (octet) { - octet = octet | 0 + results[key] = result; + taskCb(err); + }); + }, function (err) { + return callback(err, results); + }); + }, 3); + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ - if (checkOffset(2) | 0) { - return 1 - } - pushTagStart( - readUInt16((offset + 1) | 0) | 0 - ) + function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); + } + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ - offset = (offset + 3 | 0) - return 0 + function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit(limit), tasks, callback); } + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = aync.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ - function TAG_MORE_4 (octet) { - octet = octet | 0 + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ - if (checkOffset(4) | 0) { - return 1 - } - pushTagStart4( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) + function queue$1(worker, concurrency) { + var _worker = wrapAsync(worker); - offset = (offset + 5 | 0) + return queue(function (items, cb) { + _worker(items[0], cb); + }, concurrency, 1); + } // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities - return 0 - } - function TAG_MORE_8 (octet) { - octet = octet | 0 + var Heap = + /*#__PURE__*/ + function () { + function Heap() { + _classCallCheck(this, Heap); - if (checkOffset(8) | 0) { - return 1 + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; } - pushTagStart8( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) - - offset = (offset + 9 | 0) - - return 0 - } - - function SIMPLE_UNASSIGNED (octet) { - octet = octet | 0 - - pushSimpleUnassigned(((octet | 0) - 224) | 0) + _createClass(Heap, [{ + key: "empty", + value: function empty() { + this.heap = []; + return this; + } + }, { + key: "percUp", + value: function percUp(index) { + var p; - offset = (offset + 1) | 0 + while (index > 0 && smaller(this.heap[index], this.heap[p = parent(index)])) { + var t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + index = p; + } + } + }, { + key: "percDown", + value: function percDown(index) { + var l; - return 0 - } + while ((l = leftChi(index)) < this.heap.length) { + if (l + 1 < this.heap.length && smaller(this.heap[l + 1], this.heap[l])) { + l = l + 1; + } - function SIMPLE_FALSE (octet) { - octet = octet | 0 + if (smaller(this.heap[index], this.heap[l])) { + break; + } - pushFalse() + var t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + index = l; + } + } + }, { + key: "push", + value: function push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length - 1); + } + }, { + key: "unshift", + value: function unshift(node) { + return this.heap.push(node); + } + }, { + key: "shift", + value: function shift() { + var _this$heap = _slicedToArray(this.heap, 1), + top = _this$heap[0]; - offset = (offset + 1) | 0 + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.percDown(0); + return top; + } + }, { + key: "toArray", + value: function toArray() { + return _toConsumableArray(this); + } + }, { + key: Symbol.iterator, + value: + /*#__PURE__*/ + regeneratorRuntime.mark(function value() { + var i; + return regeneratorRuntime.wrap(function value$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + i = 0; + + case 1: + if (!(i < this.heap.length)) { + _context3.next = 7; + break; + } - return 0 - } + _context3.next = 4; + return this.heap[i].data; - function SIMPLE_TRUE (octet) { - octet = octet | 0 + case 4: + i++; + _context3.next = 1; + break; - pushTrue() + case 7: + case "end": + return _context3.stop(); + } + } + }, value, this); + }) + }, { + key: "remove", + value: function remove(testFn) { + var j = 0; - offset = (offset + 1) | 0 + for (var i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } - return 0 - } + this.heap.splice(j); - function SIMPLE_NULL (octet) { - octet = octet | 0 + for (var _i2 = parent(this.heap.length - 1); _i2 >= 0; _i2--) { + this.percDown(_i2); + } - pushNull() + return this; + } + }, { + key: "length", + get: function get() { + return this.heap.length; + } + }]); - offset = (offset + 1) | 0 + return Heap; + }(); - return 0 + function leftChi(i) { + return (i << 1) + 1; } - function SIMPLE_UNDEFINED (octet) { - octet = octet | 0 - - pushUndefined() - - offset = (offset + 1) | 0 - - return 0 + function parent(i) { + return (i + 1 >> 1) - 1; } - function SIMPLE_BYTE (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } else { + return x.pushCount < y.pushCount; } + } + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ - pushSimpleUnassigned(heap[(offset + 1) | 0] | 0) - offset = (offset + 2) | 0 + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + q._tasks = new Heap(); // Override push to accept second parameter representing priority - return 0 - } + q.push = function (data) { + var priority = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; - function SIMPLE_FLOAT_HALF (octet) { - octet = octet | 0 + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } - var f = 0 - var g = 0 - var sign = 1.0 - var exp = 0.0 - var mant = 0.0 - var r = 0.0 - if (checkOffset(2) | 0) { - return 1 - } + q.started = true; - f = heap[(offset + 1) | 0] | 0 - g = heap[(offset + 2) | 0] | 0 + if (!Array.isArray(data)) { + data = [data]; + } - if ((f | 0) & 0x80) { - sign = -1.0 - } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(function () { + return q.drain(); + }); + } - exp = +(((f | 0) & 0x7C) >> 2) - mant = +((((f | 0) & 0x03) << 8) | g) + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority: priority, + callback: callback + }; - if (+exp == 0.0) { - pushFloat(+( - (+sign) * +5.9604644775390625e-8 * (+mant) - )) - } else if (+exp == 31.0) { - if (+sign == 1.0) { - if (+mant > 0.0) { - pushNaN() - } else { - pushInfinity() - } - } else { - if (+mant > 0.0) { - pushNaNNeg() - } else { - pushInfinityNeg() - } + q._tasks.push(item); } - } else { - pushFloat(+( - +sign * pow(+2, +(+exp - 25.0)) * +(1024.0 + mant) - )) - } - offset = (offset + 3) | 0 + setImmediate$1(q.process); + }; // Remove unshift function + - return 0 + delete q.unshift; + return q; } + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ - function SIMPLE_FLOAT_SINGLE (octet) { - octet = octet | 0 - if (checkOffset(4) | 0) { - return 1 + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); } + } - pushFloatSingle( - heap[(offset + 1) | 0] | 0, - heap[(offset + 2) | 0] | 0, - heap[(offset + 3) | 0] | 0, - heap[(offset + 4) | 0] | 0 - ) + var race$1 = awaitify(race, 2); + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ - offset = (offset + 5) | 0 + function reduceRight(array, memo, iteratee, callback) { + var reversed = _toConsumableArray(array).reverse(); - return 0 + return reduce$1(reversed, memo, iteratee, callback); } + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ - function SIMPLE_FLOAT_DOUBLE (octet) { - octet = octet | 0 - if (checkOffset(8) | 0) { - return 1 - } - - pushFloatDouble( - heap[(offset + 1) | 0] | 0, - heap[(offset + 2) | 0] | 0, - heap[(offset + 3) | 0] | 0, - heap[(offset + 4) | 0] | 0, - heap[(offset + 5) | 0] | 0, - heap[(offset + 6) | 0] | 0, - heap[(offset + 7) | 0] | 0, - heap[(offset + 8) | 0] | 0 - ) + function reflect(fn) { + var _fn = wrapAsync(fn); - offset = (offset + 9) | 0 - - return 0 - } - - function ERROR (octet) { - octet = octet | 0 - - return 1 - } - - function BREAK (octet) { - octet = octet | 0 - - pushBreak() - - offset = (offset + 1) | 0 - - return 0 - } - - // -- Jump Table - - var jumpTable = [ - // Integer 0x00..0x17 (0..23) - INT_P, // 0x00 - INT_P, // 0x01 - INT_P, // 0x02 - INT_P, // 0x03 - INT_P, // 0x04 - INT_P, // 0x05 - INT_P, // 0x06 - INT_P, // 0x07 - INT_P, // 0x08 - INT_P, // 0x09 - INT_P, // 0x0A - INT_P, // 0x0B - INT_P, // 0x0C - INT_P, // 0x0D - INT_P, // 0x0E - INT_P, // 0x0F - INT_P, // 0x10 - INT_P, // 0x11 - INT_P, // 0x12 - INT_P, // 0x13 - INT_P, // 0x14 - INT_P, // 0x15 - INT_P, // 0x16 - INT_P, // 0x17 - // Unsigned integer (one-byte uint8_t follows) - UINT_P_8, // 0x18 - // Unsigned integer (two-byte uint16_t follows) - UINT_P_16, // 0x19 - // Unsigned integer (four-byte uint32_t follows) - UINT_P_32, // 0x1a - // Unsigned integer (eight-byte uint64_t follows) - UINT_P_64, // 0x1b - ERROR, // 0x1c - ERROR, // 0x1d - ERROR, // 0x1e - ERROR, // 0x1f - // Negative integer -1-0x00..-1-0x17 (-1..-24) - INT_N, // 0x20 - INT_N, // 0x21 - INT_N, // 0x22 - INT_N, // 0x23 - INT_N, // 0x24 - INT_N, // 0x25 - INT_N, // 0x26 - INT_N, // 0x27 - INT_N, // 0x28 - INT_N, // 0x29 - INT_N, // 0x2A - INT_N, // 0x2B - INT_N, // 0x2C - INT_N, // 0x2D - INT_N, // 0x2E - INT_N, // 0x2F - INT_N, // 0x30 - INT_N, // 0x31 - INT_N, // 0x32 - INT_N, // 0x33 - INT_N, // 0x34 - INT_N, // 0x35 - INT_N, // 0x36 - INT_N, // 0x37 - // Negative integer -1-n (one-byte uint8_t for n follows) - UINT_N_8, // 0x38 - // Negative integer -1-n (two-byte uint16_t for n follows) - UINT_N_16, // 0x39 - // Negative integer -1-n (four-byte uint32_t for nfollows) - UINT_N_32, // 0x3a - // Negative integer -1-n (eight-byte uint64_t for n follows) - UINT_N_64, // 0x3b - ERROR, // 0x3c - ERROR, // 0x3d - ERROR, // 0x3e - ERROR, // 0x3f - // byte string (0x00..0x17 bytes follow) - BYTE_STRING, // 0x40 - BYTE_STRING, // 0x41 - BYTE_STRING, // 0x42 - BYTE_STRING, // 0x43 - BYTE_STRING, // 0x44 - BYTE_STRING, // 0x45 - BYTE_STRING, // 0x46 - BYTE_STRING, // 0x47 - BYTE_STRING, // 0x48 - BYTE_STRING, // 0x49 - BYTE_STRING, // 0x4A - BYTE_STRING, // 0x4B - BYTE_STRING, // 0x4C - BYTE_STRING, // 0x4D - BYTE_STRING, // 0x4E - BYTE_STRING, // 0x4F - BYTE_STRING, // 0x50 - BYTE_STRING, // 0x51 - BYTE_STRING, // 0x52 - BYTE_STRING, // 0x53 - BYTE_STRING, // 0x54 - BYTE_STRING, // 0x55 - BYTE_STRING, // 0x56 - BYTE_STRING, // 0x57 - // byte string (one-byte uint8_t for n, and then n bytes follow) - BYTE_STRING_8, // 0x58 - // byte string (two-byte uint16_t for n, and then n bytes follow) - BYTE_STRING_16, // 0x59 - // byte string (four-byte uint32_t for n, and then n bytes follow) - BYTE_STRING_32, // 0x5a - // byte string (eight-byte uint64_t for n, and then n bytes follow) - BYTE_STRING_64, // 0x5b - ERROR, // 0x5c - ERROR, // 0x5d - ERROR, // 0x5e - // byte string, byte strings follow, terminated by "break" - BYTE_STRING_BREAK, // 0x5f - // UTF-8 string (0x00..0x17 bytes follow) - UTF8_STRING, // 0x60 - UTF8_STRING, // 0x61 - UTF8_STRING, // 0x62 - UTF8_STRING, // 0x63 - UTF8_STRING, // 0x64 - UTF8_STRING, // 0x65 - UTF8_STRING, // 0x66 - UTF8_STRING, // 0x67 - UTF8_STRING, // 0x68 - UTF8_STRING, // 0x69 - UTF8_STRING, // 0x6A - UTF8_STRING, // 0x6B - UTF8_STRING, // 0x6C - UTF8_STRING, // 0x6D - UTF8_STRING, // 0x6E - UTF8_STRING, // 0x6F - UTF8_STRING, // 0x70 - UTF8_STRING, // 0x71 - UTF8_STRING, // 0x72 - UTF8_STRING, // 0x73 - UTF8_STRING, // 0x74 - UTF8_STRING, // 0x75 - UTF8_STRING, // 0x76 - UTF8_STRING, // 0x77 - // UTF-8 string (one-byte uint8_t for n, and then n bytes follow) - UTF8_STRING_8, // 0x78 - // UTF-8 string (two-byte uint16_t for n, and then n bytes follow) - UTF8_STRING_16, // 0x79 - // UTF-8 string (four-byte uint32_t for n, and then n bytes follow) - UTF8_STRING_32, // 0x7a - // UTF-8 string (eight-byte uint64_t for n, and then n bytes follow) - UTF8_STRING_64, // 0x7b - // UTF-8 string, UTF-8 strings follow, terminated by "break" - ERROR, // 0x7c - ERROR, // 0x7d - ERROR, // 0x7e - UTF8_STRING_BREAK, // 0x7f - // array (0x00..0x17 data items follow) - ARRAY, // 0x80 - ARRAY, // 0x81 - ARRAY, // 0x82 - ARRAY, // 0x83 - ARRAY, // 0x84 - ARRAY, // 0x85 - ARRAY, // 0x86 - ARRAY, // 0x87 - ARRAY, // 0x88 - ARRAY, // 0x89 - ARRAY, // 0x8A - ARRAY, // 0x8B - ARRAY, // 0x8C - ARRAY, // 0x8D - ARRAY, // 0x8E - ARRAY, // 0x8F - ARRAY, // 0x90 - ARRAY, // 0x91 - ARRAY, // 0x92 - ARRAY, // 0x93 - ARRAY, // 0x94 - ARRAY, // 0x95 - ARRAY, // 0x96 - ARRAY, // 0x97 - // array (one-byte uint8_t fo, and then n data items follow) - ARRAY_8, // 0x98 - // array (two-byte uint16_t for n, and then n data items follow) - ARRAY_16, // 0x99 - // array (four-byte uint32_t for n, and then n data items follow) - ARRAY_32, // 0x9a - // array (eight-byte uint64_t for n, and then n data items follow) - ARRAY_64, // 0x9b - // array, data items follow, terminated by "break" - ERROR, // 0x9c - ERROR, // 0x9d - ERROR, // 0x9e - ARRAY_BREAK, // 0x9f - // map (0x00..0x17 pairs of data items follow) - MAP, // 0xa0 - MAP, // 0xa1 - MAP, // 0xa2 - MAP, // 0xa3 - MAP, // 0xa4 - MAP, // 0xa5 - MAP, // 0xa6 - MAP, // 0xa7 - MAP, // 0xa8 - MAP, // 0xa9 - MAP, // 0xaA - MAP, // 0xaB - MAP, // 0xaC - MAP, // 0xaD - MAP, // 0xaE - MAP, // 0xaF - MAP, // 0xb0 - MAP, // 0xb1 - MAP, // 0xb2 - MAP, // 0xb3 - MAP, // 0xb4 - MAP, // 0xb5 - MAP, // 0xb6 - MAP, // 0xb7 - // map (one-byte uint8_t for n, and then n pairs of data items follow) - MAP_8, // 0xb8 - // map (two-byte uint16_t for n, and then n pairs of data items follow) - MAP_16, // 0xb9 - // map (four-byte uint32_t for n, and then n pairs of data items follow) - MAP_32, // 0xba - // map (eight-byte uint64_t for n, and then n pairs of data items follow) - MAP_64, // 0xbb - ERROR, // 0xbc - ERROR, // 0xbd - ERROR, // 0xbe - // map, pairs of data items follow, terminated by "break" - MAP_BREAK, // 0xbf - // Text-based date/time (data item follows; see Section 2.4.1) - TAG_KNOWN, // 0xc0 - // Epoch-based date/time (data item follows; see Section 2.4.1) - TAG_KNOWN, // 0xc1 - // Positive bignum (data item "byte string" follows) - TAG_KNOWN, // 0xc2 - // Negative bignum (data item "byte string" follows) - TAG_KNOWN, // 0xc3 - // Decimal Fraction (data item "array" follows; see Section 2.4.3) - TAG_KNOWN, // 0xc4 - // Bigfloat (data item "array" follows; see Section 2.4.3) - TAG_KNOWN, // 0xc5 - // (tagged item) - TAG_UNASSIGNED, // 0xc6 - TAG_UNASSIGNED, // 0xc7 - TAG_UNASSIGNED, // 0xc8 - TAG_UNASSIGNED, // 0xc9 - TAG_UNASSIGNED, // 0xca - TAG_UNASSIGNED, // 0xcb - TAG_UNASSIGNED, // 0xcc - TAG_UNASSIGNED, // 0xcd - TAG_UNASSIGNED, // 0xce - TAG_UNASSIGNED, // 0xcf - TAG_UNASSIGNED, // 0xd0 - TAG_UNASSIGNED, // 0xd1 - TAG_UNASSIGNED, // 0xd2 - TAG_UNASSIGNED, // 0xd3 - TAG_UNASSIGNED, // 0xd4 - // Expected Conversion (data item follows; see Section 2.4.4.2) - TAG_UNASSIGNED, // 0xd5 - TAG_UNASSIGNED, // 0xd6 - TAG_UNASSIGNED, // 0xd7 - // (more tagged items, 1/2/4/8 bytes and then a data item follow) - TAG_MORE_1, // 0xd8 - TAG_MORE_2, // 0xd9 - TAG_MORE_4, // 0xda - TAG_MORE_8, // 0xdb - ERROR, // 0xdc - ERROR, // 0xdd - ERROR, // 0xde - ERROR, // 0xdf - // (simple value) - SIMPLE_UNASSIGNED, // 0xe0 - SIMPLE_UNASSIGNED, // 0xe1 - SIMPLE_UNASSIGNED, // 0xe2 - SIMPLE_UNASSIGNED, // 0xe3 - SIMPLE_UNASSIGNED, // 0xe4 - SIMPLE_UNASSIGNED, // 0xe5 - SIMPLE_UNASSIGNED, // 0xe6 - SIMPLE_UNASSIGNED, // 0xe7 - SIMPLE_UNASSIGNED, // 0xe8 - SIMPLE_UNASSIGNED, // 0xe9 - SIMPLE_UNASSIGNED, // 0xea - SIMPLE_UNASSIGNED, // 0xeb - SIMPLE_UNASSIGNED, // 0xec - SIMPLE_UNASSIGNED, // 0xed - SIMPLE_UNASSIGNED, // 0xee - SIMPLE_UNASSIGNED, // 0xef - SIMPLE_UNASSIGNED, // 0xf0 - SIMPLE_UNASSIGNED, // 0xf1 - SIMPLE_UNASSIGNED, // 0xf2 - SIMPLE_UNASSIGNED, // 0xf3 - // False - SIMPLE_FALSE, // 0xf4 - // True - SIMPLE_TRUE, // 0xf5 - // Null - SIMPLE_NULL, // 0xf6 - // Undefined - SIMPLE_UNDEFINED, // 0xf7 - // (simple value, one byte follows) - SIMPLE_BYTE, // 0xf8 - // Half-Precision Float (two-byte IEEE 754) - SIMPLE_FLOAT_HALF, // 0xf9 - // Single-Precision Float (four-byte IEEE 754) - SIMPLE_FLOAT_SINGLE, // 0xfa - // Double-Precision Float (eight-byte IEEE 754) - SIMPLE_FLOAT_DOUBLE, // 0xfb - ERROR, // 0xfc - ERROR, // 0xfd - ERROR, // 0xfe - // "break" stop code - BREAK // 0xff - ] + return initialParams(function reflectOn(args, reflectCallback) { + args.push(function (error) { + var retVal = {}; - // -- + if (error) { + retVal.error = error; + } - return { - parse: parse - } -} + for (var _len31 = arguments.length, cbArgs = new Array(_len31 > 1 ? _len31 - 1 : 0), _key31 = 1; _key31 < _len31; _key31++) { + cbArgs[_key31 - 1] = arguments[_key31]; + } -},{}],138:[function(require,module,exports){ -'use strict' + if (cbArgs.length > 0) { + var value = cbArgs; -const ieee754 = require('ieee754') -const Bignumber = require('bignumber.js') + if (cbArgs.length <= 1) { + value = cbArgs[0]; + } -const parser = require('./decoder.asm') -const utils = require('./utils') -const c = require('./constants') -const Simple = require('./simple') -const Tagged = require('./tagged') -const url = require('url') + retVal.value = value; + } -/** - * Transform binary cbor data into JavaScript objects. - */ -class Decoder { + reflectCallback(null, retVal); + }); + return _fn.apply(this, args); + }); + } /** - * @param {Object} [opts={}] - * @param {number} [opts.size=65536] - Size of the allocated heap. + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); */ - constructor (opts) { - opts = opts || {} - if (!opts.size || opts.size < 0x10000) { - opts.size = 0x10000 + + function reflectAll(tasks) { + var _this2 = this; + + var results; + + if (Array.isArray(tasks)) { + results = tasks.map(reflect); } else { - // Ensure the size is a power of 2 - opts.size = utils.nextPowerOf2(opts.size) + results = {}; + Object.keys(tasks).forEach(function (key) { + results[key] = reflect.call(_this2, tasks[key]); + }); } - // Heap use to share the input with the parser - this._heap = new ArrayBuffer(opts.size) - this._heap8 = new Uint8Array(this._heap) + return results; + } - this._reset() + function reject(eachfn, arr, _iteratee, callback) { + var iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, function (value, cb) { + iteratee(value, function (err, v) { + cb(err, !v); + }); + }, callback); + } + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ - // Known tags - this._knownTags = Object.assign({ - 0: (val) => new Date(val), - 1: (val) => new Date(val * 1000), - 2: (val) => utils.arrayBufferToBignumber(val), - 3: (val) => c.NEG_ONE.minus(utils.arrayBufferToBignumber(val)), - 4: (v) => { - // const v = new Uint8Array(val) - return c.TEN.pow(v[0]).times(v[1]) - }, - 5: (v) => { - // const v = new Uint8Array(val) - return c.TWO.pow(v[0]).times(v[1]) - }, - 32: (val) => url.parse(val), - 35: (val) => new RegExp(val) - }, opts.tags) - // Initialize asm based parser - this.parser = parser(global, { - log: console.log.bind(console), - pushInt: this.pushInt.bind(this), - pushInt32: this.pushInt32.bind(this), - pushInt32Neg: this.pushInt32Neg.bind(this), - pushInt64: this.pushInt64.bind(this), - pushInt64Neg: this.pushInt64Neg.bind(this), - pushFloat: this.pushFloat.bind(this), - pushFloatSingle: this.pushFloatSingle.bind(this), - pushFloatDouble: this.pushFloatDouble.bind(this), - pushTrue: this.pushTrue.bind(this), - pushFalse: this.pushFalse.bind(this), - pushUndefined: this.pushUndefined.bind(this), - pushNull: this.pushNull.bind(this), - pushInfinity: this.pushInfinity.bind(this), - pushInfinityNeg: this.pushInfinityNeg.bind(this), - pushNaN: this.pushNaN.bind(this), - pushNaNNeg: this.pushNaNNeg.bind(this), - pushArrayStart: this.pushArrayStart.bind(this), - pushArrayStartFixed: this.pushArrayStartFixed.bind(this), - pushArrayStartFixed32: this.pushArrayStartFixed32.bind(this), - pushArrayStartFixed64: this.pushArrayStartFixed64.bind(this), - pushObjectStart: this.pushObjectStart.bind(this), - pushObjectStartFixed: this.pushObjectStartFixed.bind(this), - pushObjectStartFixed32: this.pushObjectStartFixed32.bind(this), - pushObjectStartFixed64: this.pushObjectStartFixed64.bind(this), - pushByteString: this.pushByteString.bind(this), - pushByteStringStart: this.pushByteStringStart.bind(this), - pushUtf8String: this.pushUtf8String.bind(this), - pushUtf8StringStart: this.pushUtf8StringStart.bind(this), - pushSimpleUnassigned: this.pushSimpleUnassigned.bind(this), - pushTagUnassigned: this.pushTagUnassigned.bind(this), - pushTagStart: this.pushTagStart.bind(this), - pushTagStart4: this.pushTagStart4.bind(this), - pushTagStart8: this.pushTagStart8.bind(this), - pushBreak: this.pushBreak.bind(this) - }, this._heap) + function reject$1(coll, iteratee, callback) { + return reject(eachOf$1, coll, iteratee, callback); } - get _depth () { - return this._parents.length + var reject$2 = awaitify(reject$1, 3); + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + + function rejectLimit(coll, limit, iteratee, callback) { + return reject(eachOfLimit(limit), coll, iteratee, callback); } - get _currentParent () { - return this._parents[this._depth - 1] + var rejectLimit$1 = awaitify(rejectLimit, 4); + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + + function rejectSeries(coll, iteratee, callback) { + return reject(eachOfSeries$1, coll, iteratee, callback); } - get _ref () { - return this._currentParent.ref + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant$1(value) { + return function () { + return value; + }; } + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ - // Finish the current parent - _closeParent () { - var p = this._parents.pop() - if (p.length > 0) { - throw new Error(`Missing ${p.length} elements`) - } + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; - switch (p.type) { - case c.PARENT.TAG: - this._push( - this.createTag(p.ref[0], p.ref[1]) - ) - break - case c.PARENT.BYTE_STRING: - this._push(this.createByteString(p.ref, p.length)) - break - case c.PARENT.UTF8_STRING: - this._push(this.createUtf8String(p.ref, p.length)) - break - case c.PARENT.MAP: - if (p.values % 2 > 0) { - throw new Error('Odd number of elements in the map') - } - this._push(this.createMap(p.ref, p.length)) - break - case c.PARENT.OBJECT: - if (p.values % 2 > 0) { - throw new Error('Odd number of elements in the map') - } - this._push(this.createObject(p.ref, p.length)) - break - case c.PARENT.ARRAY: - this._push(this.createArray(p.ref, p.length)) - break - default: - break - } + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; - if (this._currentParent && this._currentParent.type === c.PARENT.TAG) { - this._dec() + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); } - } - // Reduce the expected length of the current parent by one - _dec () { - const p = this._currentParent - // The current parent does not know the epxected child length - - if (p.length < 0) { - return + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); } - p.length-- + var _task = wrapAsync(task); - // All children were seen, we can close the current parent - if (p.length === 0) { - this._closeParent() - } - } + var attempt = 1; - // Push any value to the current parent - _push (val, hasChildren) { - const p = this._currentParent - p.values++ + function retryAttempt() { + _task(function (err) { + if (err === false) return; - switch (p.type) { - case c.PARENT.ARRAY: - case c.PARENT.BYTE_STRING: - case c.PARENT.UTF8_STRING: - if (p.length > -1) { - this._ref[this._ref.length - p.length] = val - } else { - this._ref.push(val) - } - this._dec() - break - case c.PARENT.OBJECT: - if (p.tmpKey != null) { - this._ref[p.tmpKey] = val - p.tmpKey = null - this._dec() + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); } else { - p.tmpKey = val - - if (typeof p.tmpKey !== 'string') { - // too bad, convert to a Map - p.type = c.PARENT.MAP - p.ref = utils.buildMap(p.ref) + for (var _len32 = arguments.length, args = new Array(_len32 > 1 ? _len32 - 1 : 0), _key32 = 1; _key32 < _len32; _key32++) { + args[_key32 - 1] = arguments[_key32]; } + + callback.apply(void 0, [err].concat(args)); } - break - case c.PARENT.MAP: - if (p.tmpKey != null) { - this._ref.set(p.tmpKey, val) - p.tmpKey = null - this._dec() - } else { - p.tmpKey = val - } - break - case c.PARENT.TAG: - this._ref.push(val) - if (!hasChildren) { - this._dec() - } - break - default: - throw new Error('Unknown parent type') + }); } - } - // Create a new parent in the parents list - _createParent (obj, type, len) { - this._parents[this._depth] = { - type: type, - length: len, - ref: obj, - values: 0, - tmpKey: null - } - } - - // Reset all state back to the beginning, also used for initiatlization - _reset () { - this._res = [] - this._parents = [{ - type: c.PARENT.ARRAY, - length: -1, - ref: this._res, - values: 0, - tmpKey: null - }] + retryAttempt(); + return callback[PROMISE_SYMBOL]; } - // -- Interface to customize deoding behaviour - createTag (tagNumber, value) { - const typ = this._knownTags[tagNumber] - - if (!typ) { - return new Tagged(tagNumber, value) + function parseTimes(acc, t) { + if (_typeof(t) === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant$1(+t.interval || DEFAULT_INTERVAL); + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); } - - return typ(value) - } - - createMap (obj, len) { - return obj } + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ - createObject (obj, len) { - return obj - } - createArray (arr, len) { - return arr - } + function retryable(opts, task) { + if (!task) { + task = opts; + opts = null; + } - createByteString (raw, len) { - return Buffer.concat(raw) - } + var arity = opts && opts.arity || task.length; - createByteStringFromHeap (start, end) { - if (start === end) { - return Buffer.alloc(0) + if (isAsync(task)) { + arity += 1; } - return Buffer.from(this._heap.slice(start, end)) - } + var _task = wrapAsync(task); - createInt (val) { - return val - } + return initialParams(function (args, callback) { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } - createInt32 (f, g) { - return utils.buildInt32(f, g) - } + function taskFn(cb) { + _task.apply(void 0, _toConsumableArray(args).concat([cb])); + } - createInt64 (f1, f2, g1, g2) { - return utils.buildInt64(f1, f2, g1, g2) + if (opts) retry(opts, taskFn, callback);else retry(taskFn, callback); + return callback[PROMISE_SYMBOL]; + }); } + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ - createFloat (val) { - return val - } - createFloatSingle (a, b, c, d) { - return ieee754.read([a, b, c, d], 0, false, 23, 4) + function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); } + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ - createFloatDouble (a, b, c, d, e, f, g, h) { - return ieee754.read([a, b, c, d, e, f, g, h], 0, false, 52, 8) - } - createInt32Neg (f, g) { - return -1 - utils.buildInt32(f, g) + function some(coll, iteratee, callback) { + return _createTester(Boolean, function (res) { + return res; + })(eachOf$1, coll, iteratee, callback); } - createInt64Neg (f1, f2, g1, g2) { - const f = utils.buildInt32(f1, f2) - const g = utils.buildInt32(g1, g2) - - if (f > c.MAX_SAFE_HIGH) { - return c.NEG_ONE.minus(new Bignumber(f).times(c.SHIFT32).plus(g)) - } - - return -1 - ((f * c.SHIFT32) + g) - } + var some$1 = awaitify(some, 3); + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ - createTrue () { - return true + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, function (res) { + return res; + })(eachOfLimit(limit), coll, iteratee, callback); } - createFalse () { - return false - } + var someLimit$1 = awaitify(someLimit, 4); + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ - createNull () { - return null + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, function (res) { + return res; + })(eachOfSeries$1, coll, iteratee, callback); } - createUndefined () { - return void 0 - } + var someSeries$1 = awaitify(someSeries, 3); + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ - createInfinity () { - return Infinity - } + function sortBy(coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); - createInfinityNeg () { - return -Infinity - } + return map$1(coll, function (x, iterCb) { + _iteratee(x, function (err, criteria) { + if (err) return iterCb(err); + iterCb(err, { + value: x, + criteria: criteria + }); + }); + }, function (err, results) { + if (err) return callback(err); + callback(null, results.sort(comparator).map(function (v) { + return v.value; + })); + }); - createNaN () { - return NaN + function comparator(left, right) { + var a = left.criteria, + b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } } - createNaNNeg () { - return -NaN - } + var sortBy$1 = awaitify(sortBy, 3); + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ - createUtf8String (raw, len) { - return raw.join('') - } + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + return initialParams(function (args, callback) { + var timedOut = false; + var timer; - createUtf8StringFromHeap (start, end) { - if (start === end) { - return '' - } + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; - return ( - Buffer.from(this._heap.slice(start, end)) - ).toString('utf8') - } + if (info) { + error.info = info; + } - createSimpleUnassigned (val) { - return new Simple(val) - } + timedOut = true; + callback(error); + } - // -- Interface for decoder.asm.js + args.push(function () { + if (!timedOut) { + callback.apply(void 0, arguments); + clearTimeout(timer); + } + }); // setup timer and call original function - pushInt (val) { - this._push(this.createInt(val)) + timer = setTimeout(timeoutCallback, milliseconds); + fn.apply(void 0, _toConsumableArray(args)); + }); } - pushInt32 (f, g) { - this._push(this.createInt32(f, g)) - } + function range(size) { + var result = Array(size); - pushInt64 (f1, f2, g1, g2) { - this._push(this.createInt64(f1, f2, g1, g2)) - } + while (size--) { + result[size] = size; + } - pushFloat (val) { - this._push(this.createFloat(val)) + return result; } + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ - pushFloatSingle (a, b, c, d) { - this._push(this.createFloatSingle(a, b, c, d)) - } - pushFloatDouble (a, b, c, d, e, f, g, h) { - this._push(this.createFloatDouble(a, b, c, d, e, f, g, h)) - } + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); - pushInt32Neg (f, g) { - this._push(this.createInt32Neg(f, g)) + return mapLimit$1(range(count), limit, _iteratee, callback); } + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ - pushInt64Neg (f1, f2, g1, g2) { - this._push(this.createInt64Neg(f1, f2, g1, g2)) - } - pushTrue () { - this._push(this.createTrue()) + function times(n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback); } + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ - pushFalse () { - this._push(this.createFalse()) - } - pushNull () { - this._push(this.createNull()) + function timesSeries(n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback); } + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc[index] = item * 2 + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ - pushUndefined () { - this._push(this.createUndefined()) - } - pushInfinity () { - this._push(this.createInfinity()) - } + function transform(coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } - pushInfinityNeg () { - this._push(this.createInfinityNeg()) - } + callback = once(callback || promiseCallback()); - pushNaN () { - this._push(this.createNaN()) - } + var _iteratee = wrapAsync(iteratee); - pushNaNNeg () { - this._push(this.createNaNNeg()) + eachOf$1(coll, function (v, k, cb) { + _iteratee(accumulator, v, k, cb); + }, function (err) { + return callback(err, accumulator); + }); + return callback[PROMISE_SYMBOL]; } + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ - pushArrayStart () { - this._createParent([], c.PARENT.ARRAY, -1) - } - pushArrayStartFixed (len) { - this._createArrayStartFixed(len) - } + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, function (task, taskCb) { + wrapAsync(task)(function (err) { + if (err === false) return taskCb(err); - pushArrayStartFixed32 (len1, len2) { - const len = utils.buildInt32(len1, len2) - this._createArrayStartFixed(len) - } + for (var _len33 = arguments.length, args = new Array(_len33 > 1 ? _len33 - 1 : 0), _key33 = 1; _key33 < _len33; _key33++) { + args[_key33 - 1] = arguments[_key33]; + } - pushArrayStartFixed64 (len1, len2, len3, len4) { - const len = utils.buildInt64(len1, len2, len3, len4) - this._createArrayStartFixed(len) - } + if (args.length < 2) { + result = args[0]; + } else { + result = args; + } - pushObjectStart () { - this._createObjectStartFixed(-1) + error = err; + taskCb(err ? null : {}); + }); + }, function () { + return callback(error, result); + }); } - pushObjectStartFixed (len) { - this._createObjectStartFixed(len) - } + var tryEach$1 = awaitify(tryEach); + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ - pushObjectStartFixed32 (len1, len2) { - const len = utils.buildInt32(len1, len2) - this._createObjectStartFixed(len) + function unmemoize(fn) { + return function () { + return (fn.unmemoized || fn).apply(void 0, arguments); + }; } + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5;) }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ - pushObjectStartFixed64 (len1, len2, len3, len4) { - const len = utils.buildInt64(len1, len2, len3, len4) - this._createObjectStartFixed(len) - } - pushByteStringStart () { - this._parents[this._depth] = { - type: c.PARENT.BYTE_STRING, - length: -1, - ref: [], - values: 0, - tmpKey: null - } - } + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); - pushByteString (start, end) { - this._push(this.createByteStringFromHeap(start, end)) - } + var _fn = wrapAsync(iteratee); - pushUtf8StringStart () { - this._parents[this._depth] = { - type: c.PARENT.UTF8_STRING, - length: -1, - ref: [], - values: 0, - tmpKey: null - } - } + var _test = wrapAsync(test); - pushUtf8String (start, end) { - this._push(this.createUtf8StringFromHeap(start, end)) - } + var results = []; - pushSimpleUnassigned (val) { - this._push(this.createSimpleUnassigned(val)) - } + function next(err) { + if (err) return callback(err); - pushTagStart (tag) { - this._parents[this._depth] = { - type: c.PARENT.TAG, - length: 1, - ref: [tag] - } - } + for (var _len34 = arguments.length, rest = new Array(_len34 > 1 ? _len34 - 1 : 0), _key34 = 1; _key34 < _len34; _key34++) { + rest[_key34 - 1] = arguments[_key34]; + } - pushTagStart4 (f, g) { - this.pushTagStart(utils.buildInt32(f, g)) - } + results = rest; + if (err === false) return; - pushTagStart8 (f1, f2, g1, g2) { - this.pushTagStart(utils.buildInt64(f1, f2, g1, g2)) - } + _test(check); + } - pushTagUnassigned (tagNumber) { - this._push(this.createTag(tagNumber)) - } + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback.apply(void 0, [null].concat(_toConsumableArray(results))); - pushBreak () { - if (this._currentParent.length > -1) { - throw new Error('Unexpected break') + _fn(next); } - this._closeParent() + return _test(check); } - _createObjectStartFixed (len) { - if (len === 0) { - this._push(this.createObject({})) - return - } + var whilst$1 = awaitify(whilst, 3); + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * async.until(function test(page, cb) { + * cb(null, page.next == null) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * next(err, body) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ - this._createParent({}, c.PARENT.OBJECT, len) + function until(test, iteratee, callback) { + var _test = wrapAsync(test); + + return whilst$1(function (cb) { + return _test(function (err, truth) { + return cb(err, !truth); + }); + }, iteratee, callback); } + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ - _createArrayStartFixed (len) { - if (len === 0) { - this._push(this.createArray([])) - return - } - this._createParent(new Array(len), c.PARENT.ARRAY, len) - } + function waterfall(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; - _decode (input) { - if (input.byteLength === 0) { - throw new Error('Input too short') + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task.apply(void 0, _toConsumableArray(args).concat([onlyOnce(next)])); } - this._reset() - this._heap8.set(input) - const code = this.parser.parse(input.byteLength) + function next(err) { + if (err === false) return; - if (this._depth > 1) { - while (this._currentParent.length === 0) { - this._closeParent() - } - if (this._depth > 1) { - throw new Error('Undeterminated nesting') + for (var _len35 = arguments.length, args = new Array(_len35 > 1 ? _len35 - 1 : 0), _key35 = 1; _key35 < _len35; _key35++) { + args[_key35 - 1] = arguments[_key35]; } - } - if (code > 0) { - throw new Error('Failed to parse') - } + if (err || taskIndex === tasks.length) { + return callback.apply(void 0, [err].concat(args)); + } - if (this._res.length === 0) { - throw new Error('No valid result') + nextTask(args); } - } - - // -- Public Interface - - decodeFirst (input) { - this._decode(input) - - return this._res[0] - } - - decodeAll (input) { - this._decode(input) - return this._res + nextTask([]); } + var waterfall$1 = awaitify(waterfall); /** - * Decode the first cbor object. + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. * - * @param {Buffer|string} input - * @param {string} [enc='hex'] - Encoding used if a string is passed. - * @returns {*} + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static */ - static decode (input, enc) { - if (typeof input === 'string') { - input = Buffer.from(input, enc || 'hex') - } - - const dec = new Decoder({size: input.length}) - return dec.decodeFirst(input) - } - /** - * Decode all cbor objects. - * - * @param {Buffer|string} input - * @param {string} [enc='hex'] - Encoding used if a string is passed. - * @returns {Array<*>} - */ - static decodeAll (input, enc) { - if (typeof input === 'string') { - input = Buffer.from(input, enc || 'hex') - } + var index = { + apply: apply, + applyEach: applyEach$1, + applyEachSeries: applyEachSeries, + asyncify: asyncify, + auto: auto, + autoInject: autoInject, + cargo: cargo, + cargoQueue: cargo$1, + compose: compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir: dir, + doUntil: doUntil, + doWhilst: doWhilst$1, + each: each, + eachLimit: eachLimit$2, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$2, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync: ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy: groupBy, + groupByLimit: groupByLimit$1, + groupBySeries: groupBySeries, + log: log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues: mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries: mapValuesSeries, + memoize: memoize, + nextTick: nextTick, + parallel: parallel, + parallelLimit: parallelLimit, + priorityQueue: priorityQueue, + queue: queue$1, + race: race$1, + reduce: reduce$1, + reduceRight: reduceRight, + reflect: reflect, + reflectAll: reflectAll, + reject: reject$2, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry: retry, + retryable: retryable, + seq: seq, + series: series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout: timeout, + times: times, + timesLimit: timesLimit, + timesSeries: timesSeries, + transform: transform, + tryEach: tryEach$1, + unmemoize: unmemoize, + until: until, + waterfall: waterfall$1, + whilst: whilst$1, + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$2, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$2, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + exports["default"] = index; + exports.apply = apply; + exports.applyEach = applyEach$1; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo; + exports.cargoQueue = cargo$1; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.each = each; + exports.eachLimit = eachLimit$2; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$2; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue$1; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$2; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.forEach = each; + exports.forEachSeries = eachSeries$1; + exports.forEachLimit = eachLimit$2; + exports.forEachOf = eachOf$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachOfLimit = eachOfLimit$2; + exports.inject = reduce$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.wrapSync = asyncify; + exports.during = whilst$1; + exports.doDuring = doWhilst$1; + Object.defineProperty(exports, '__esModule', { + value: true + }); +}); - const dec = new Decoder({size: input.length}) - return dec.decodeAll(input) - } -} +},{}],123:[function(require,module,exports){ +"use strict"; -Decoder.decodeFirst = Decoder.decode +module.exports = { + parallel: require('./parallel.js'), + serial: require('./serial.js'), + serialOrdered: require('./serialOrdered.js') +}; -module.exports = Decoder +},{"./parallel.js":130,"./serial.js":131,"./serialOrdered.js":132}],124:[function(require,module,exports){ +"use strict"; -},{"./constants":136,"./decoder.asm":137,"./simple":142,"./tagged":143,"./utils":144,"bignumber.js":79,"ieee754":397,"url":undefined}],139:[function(require,module,exports){ -'use strict' +// API +module.exports = abort; +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ -const Decoder = require('./decoder') -const utils = require('./utils') +function abort(state) { + Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs + state.jobs = {}; +} /** - * Output the diagnostic format from a stream of CBOR bytes. + * Cleans up leftover job by invoking abort function for the provided job id * + * @this state + * @param {string|number} key - job id to abort */ -class Diagnose extends Decoder { - createTag (tagNumber, value) { - return `${tagNumber}(${value})` - } - createInt (val) { - return super.createInt(val).toString() - } - createInt32 (f, g) { - return super.createInt32(f, g).toString() +function clean(key) { + if (typeof this.jobs[key] == 'function') { + this.jobs[key](); } +} - createInt64 (f1, f2, g1, g2) { - return super.createInt64(f1, f2, g1, g2).toString() - } +},{}],125:[function(require,module,exports){ +"use strict"; - createInt32Neg (f, g) { - return super.createInt32Neg(f, g).toString() - } +var defer = require('./defer.js'); // API - createInt64Neg (f1, f2, g1, g2) { - return super.createInt64Neg(f1, f2, g1, g2).toString() - } - createTrue () { - return 'true' - } +module.exports = async; +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ - createFalse () { - return 'false' - } +function async(callback) { + var isAsync = false; // check if async happened - createFloat (val) { - const fl = super.createFloat(val) - if (utils.isNegativeZero(val)) { - return '-0_1' + defer(function () { + isAsync = true; + }); + return function async_callback(err, result) { + if (isAsync) { + callback(err, result); + } else { + defer(function nextTick_callback() { + callback(err, result); + }); } + }; +} - return `${fl}_1` - } +},{"./defer.js":126}],126:[function(require,module,exports){ +"use strict"; - createFloatSingle (a, b, c, d) { - const fl = super.createFloatSingle(a, b, c, d) - return `${fl}_2` - } +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - createFloatDouble (a, b, c, d, e, f, g, h) { - const fl = super.createFloatDouble(a, b, c, d, e, f, g, h) - return `${fl}_3` - } +module.exports = defer; +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ - createByteString (raw, len) { - const val = raw.join(', ') +function defer(fn) { + var nextTick = typeof setImmediate == 'function' ? setImmediate : (typeof process === "undefined" ? "undefined" : _typeof(process)) == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null; - if (len === -1) { - return `(_ ${val})` - } - return `h'${val}` + if (nextTick) { + nextTick(fn); + } else { + setTimeout(fn, 0); } +} - createByteStringFromHeap (start, end) { - const val = (Buffer.from( - super.createByteStringFromHeap(start, end) - )).toString('hex') - - return `h'${val}'` - } +},{}],127:[function(require,module,exports){ +"use strict"; - createInfinity () { - return 'Infinity_1' - } +var async = require('./async.js'), + abort = require('./abort.js'); // API - createInfinityNeg () { - return '-Infinity_1' - } - createNaN () { - return 'NaN_1' - } +module.exports = iterate; +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ - createNaNNeg () { - return '-NaN_1' - } +function iterate(list, iterator, state, callback) { + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + state.jobs[key] = runJob(iterator, key, list[key], function (error, output) { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) { + return; + } // clean up jobs - createNull () { - return 'null' - } - createUndefined () { - return 'undefined' - } + delete state.jobs[key]; - createSimpleUnassigned (val) { - return `simple(${val})` - } + if (error) { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } else { + state.results[key] = output; + } // return salvaged results - createArray (arr, len) { - const val = super.createArray(arr, len) - if (len === -1) { - // indefinite - return `[_ ${val.join(', ')}]` - } + callback(error, state.results); + }); +} +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ - return `[${val.join(', ')}]` - } - createMap (map, len) { - const val = super.createMap(map) - const list = Array.from(val.keys()) - .reduce(collectObject(val), '') +function runJob(iterator, key, item, callback) { + var aborter; // allow shortcut if iterator expects only two arguments - if (len === -1) { - return `{_ ${list}}` + if (iterator.length == 2) { + aborter = iterator(item, async(callback)); + } // otherwise go with full three arguments + else { + aborter = iterator(item, key, async(callback)); } - return `{${list}}` - } + return aborter; +} - createObject (obj, len) { - const val = super.createObject(obj) - const map = Object.keys(val) - .reduce(collectObject(val), '') +},{"./abort.js":124,"./async.js":125}],128:[function(require,module,exports){ +"use strict"; - if (len === -1) { - return `{_ ${map}}` - } +// API +module.exports = state; +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ - return `{${map}}` - } +function state(list, sortMethod) { + var isNamedList = !Array.isArray(list), + initState = { + index: 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs: {}, + results: isNamedList ? {} : [], + size: isNamedList ? Object.keys(list).length : list.length + }; - createUtf8String (raw, len) { - const val = raw.join(', ') + if (sortMethod) { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function (a, b) { + return sortMethod(list[a], list[b]); + }); + } - if (len === -1) { - return `(_ ${val})` - } + return initState; +} - return `"${val}"` - } +},{}],129:[function(require,module,exports){ +"use strict"; - createUtf8StringFromHeap (start, end) { - const val = (Buffer.from( - super.createUtf8StringFromHeap(start, end) - )).toString('utf8') +var abort = require('./abort.js'), + async = require('./async.js'); // API - return `"${val}"` - } - static diagnose (input, enc) { - if (typeof input === 'string') { - input = Buffer.from(input, enc || 'hex') - } +module.exports = terminator; +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ - const dec = new Diagnose() - return dec.decodeFirst(input) - } -} +function terminator(callback) { + if (!Object.keys(this.jobs).length) { + return; + } // fast forward iteration index -module.exports = Diagnose -function collectObject (val) { - return (acc, key) => { - if (acc) { - return `${acc}, ${key}: ${val[key]}` - } - return `${key}: ${val[key]}` - } -} + this.index = this.size; // abort jobs -},{"./decoder":138,"./utils":144}],140:[function(require,module,exports){ -'use strict' + abort(this); // send back results we have so far -const url = require('url') -const Bignumber = require('bignumber.js') + async(callback)(null, this.results); +} -const utils = require('./utils') -const constants = require('./constants') -const MT = constants.MT -const NUMBYTES = constants.NUMBYTES -const SHIFT32 = constants.SHIFT32 -const SYMS = constants.SYMS -const TAG = constants.TAG -const HALF = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.TWO -const FLOAT = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.FOUR -const DOUBLE = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.EIGHT -const TRUE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.TRUE -const FALSE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.FALSE -const UNDEFINED = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.UNDEFINED -const NULL = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.NULL +},{"./abort.js":124,"./async.js":125}],130:[function(require,module,exports){ +"use strict"; -const MAXINT_BN = new Bignumber('0x20000000000000') -const BUF_NAN = Buffer.from('f97e00', 'hex') -const BUF_INF_NEG = Buffer.from('f9fc00', 'hex') -const BUF_INF_POS = Buffer.from('f97c00', 'hex') +var iterate = require('./lib/iterate.js'), + initState = require('./lib/state.js'), + terminator = require('./lib/terminator.js'); // Public API -function toType (obj) { - // [object Type] - // --------8---1 - return ({}).toString.call(obj).slice(8, -1) -} +module.exports = parallel; /** - * Transform JavaScript values into CBOR bytes + * Runs iterator over provided array elements in parallel * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator */ -class Encoder { - /** - * @param {Object} [options={}] - * @param {function(Buffer)} options.stream - */ - constructor (options) { - options = options || {} - - this.streaming = typeof options.stream === 'function' - this.onData = options.stream - this.semanticTypes = [ - [url.Url, this._pushUrl], - [Bignumber, this._pushBigNumber] - ] +function parallel(list, iterator, callback) { + var state = initState(list); - const addTypes = options.genTypes || [] - const len = addTypes.length - for (let i = 0; i < len; i++) { - this.addSemanticType( - addTypes[i][0], - addTypes[i][1] - ) - } + while (state.index < (state['keyedList'] || list).length) { + iterate(list, iterator, state, function (error, result) { + if (error) { + callback(error, result); + return; + } // looks like it's the last one - this._reset() - } - addSemanticType (type, fun) { - const len = this.semanticTypes.length - for (let i = 0; i < len; i++) { - const typ = this.semanticTypes[i][0] - if (typ === type) { - const old = this.semanticTypes[i][1] - this.semanticTypes[i][1] = fun - return old + if (Object.keys(state.jobs).length === 0) { + callback(null, state.results); + return; } - } - this.semanticTypes.push([type, fun]) - return null + }); + state.index++; } - push (val) { - if (!val) { - return true - } + return terminator.bind(state, callback); +} - this.result[this.offset] = val - this.resultMethod[this.offset] = 0 - this.resultLength[this.offset] = val.length - this.offset++ +},{"./lib/iterate.js":127,"./lib/state.js":128,"./lib/terminator.js":129}],131:[function(require,module,exports){ +"use strict"; - if (this.streaming) { - this.onData(this.finalize()) - } +var serialOrdered = require('./serialOrdered.js'); // Public API - return true - } - pushWrite (val, method, len) { - this.result[this.offset] = val - this.resultMethod[this.offset] = method - this.resultLength[this.offset] = len - this.offset++ +module.exports = serial; +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ - if (this.streaming) { - this.onData(this.finalize()) - } +function serial(list, iterator, callback) { + return serialOrdered(list, iterator, null, callback); +} - return true - } +},{"./serialOrdered.js":132}],132:[function(require,module,exports){ +"use strict"; - _pushUInt8 (val) { - return this.pushWrite(val, 1, 1) - } +var iterate = require('./lib/iterate.js'), + initState = require('./lib/state.js'), + terminator = require('./lib/terminator.js'); // Public API - _pushUInt16BE (val) { - return this.pushWrite(val, 2, 2) - } - _pushUInt32BE (val) { - return this.pushWrite(val, 3, 4) - } +module.exports = serialOrdered; // sorting helpers - _pushDoubleBE (val) { - return this.pushWrite(val, 4, 8) - } +module.exports.ascending = ascending; +module.exports.descending = descending; +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ - _pushNaN () { - return this.push(BUF_NAN) - } +function serialOrdered(list, iterator, sortMethod, callback) { + var state = initState(list, sortMethod); + iterate(list, iterator, state, function iteratorHandler(error, result) { + if (error) { + callback(error, result); + return; + } - _pushInfinity (obj) { - const half = (obj < 0) ? BUF_INF_NEG : BUF_INF_POS - return this.push(half) - } + state.index++; // are we there yet? - _pushFloat (obj) { - const b2 = Buffer.allocUnsafe(2) + if (state.index < (state['keyedList'] || list).length) { + iterate(list, iterator, state, iteratorHandler); + return; + } // done here - if (utils.writeHalf(b2, obj)) { - if (utils.parseHalf(b2) === obj) { - return this._pushUInt8(HALF) && this.push(b2) - } - } - const b4 = Buffer.allocUnsafe(4) - b4.writeFloatBE(obj, 0) - if (b4.readFloatBE(0) === obj) { - return this._pushUInt8(FLOAT) && this.push(b4) - } + callback(null, state.results); + }); + return terminator.bind(state, callback); +} +/* + * -- Sort methods + */ - return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj) - } +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ - _pushInt (obj, mt, orig) { - const m = mt << 5 - if (obj < 24) { - return this._pushUInt8(m | obj) - } - if (obj <= 0xff) { - return this._pushUInt8(m | NUMBYTES.ONE) && this._pushUInt8(obj) - } +function ascending(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ - if (obj <= 0xffff) { - return this._pushUInt8(m | NUMBYTES.TWO) && this._pushUInt16BE(obj) - } - if (obj <= 0xffffffff) { - return this._pushUInt8(m | NUMBYTES.FOUR) && this._pushUInt32BE(obj) - } +function descending(a, b) { + return -1 * ascending(a, b); +} - if (obj <= Number.MAX_SAFE_INTEGER) { - return this._pushUInt8(m | NUMBYTES.EIGHT) && - this._pushUInt32BE(Math.floor(obj / SHIFT32)) && - this._pushUInt32BE(obj % SHIFT32) - } +},{"./lib/iterate.js":127,"./lib/state.js":128,"./lib/terminator.js":129}],133:[function(require,module,exports){ +"use strict"; - if (mt === MT.NEG_INT) { - return this._pushFloat(orig) - } +/*! + * Copyright 2010 LearnBoost + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - return this._pushFloat(obj) - } +/** + * Module dependencies. + */ +var crypto = require('crypto'), + parse = require('url').parse; +/** + * Valid keys. + */ - _pushIntNum (obj) { - if (obj < 0) { - return this._pushInt(-obj - 1, MT.NEG_INT, obj) - } else { - return this._pushInt(obj, MT.POS_INT) - } - } - _pushNumber (obj) { - switch (false) { - case (obj === obj): // eslint-disable-line - return this._pushNaN(obj) - case isFinite(obj): - return this._pushInfinity(obj) - case ((obj % 1) !== 0): - return this._pushIntNum(obj) - default: - return this._pushFloat(obj) - } - } +var keys = ['acl', 'location', 'logging', 'notification', 'partNumber', 'policy', 'requestPayment', 'torrent', 'uploadId', 'uploads', 'versionId', 'versioning', 'versions', 'website']; +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS :" + * + * @param {Object} options + * @return {String} + * @api private + */ - _pushString (obj) { - const len = Buffer.byteLength(obj, 'utf8') - return this._pushInt(len, MT.UTF8_STRING) && this.pushWrite(obj, 5, len) - } +function authorization(options) { + return 'AWS ' + options.key + ':' + sign(options); +} - _pushBoolean (obj) { - return this._pushUInt8(obj ? TRUE : FALSE) - } +module.exports = authorization; +module.exports.authorization = authorization; +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ - _pushUndefined (obj) { - return this._pushUInt8(UNDEFINED) - } +function hmacSha1(options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64'); +} - _pushArray (gen, obj) { - const len = obj.length - if (!gen._pushInt(len, MT.ARRAY)) { - return false - } - for (let j = 0; j < len; j++) { - if (!gen.pushAny(obj[j])) { - return false - } - } - return true - } +module.exports.hmacSha1 = hmacSha1; +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ - _pushTag (tag) { - return this._pushInt(tag, MT.TAG) - } +function sign(options) { + options.message = stringToSign(options); + return hmacSha1(options); +} - _pushDate (gen, obj) { - // Round date, to get seconds since 1970-01-01 00:00:00 as defined in - // Sec. 2.4.1 and get a possibly more compact encoding. Note that it is - // still allowed to encode fractions of seconds which can be achieved by - // changing overwriting the encode function for Date objects. - return gen._pushTag(TAG.DATE_EPOCH) && gen.pushAny(Math.round(obj / 1000)) - } +module.exports.sign = sign; +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ - _pushBuffer (gen, obj) { - return gen._pushInt(obj.length, MT.BYTE_STRING) && gen.push(obj) - } +function signQuery(options) { + options.message = queryStringToSign(options); + return hmacSha1(options); +} - _pushNoFilter (gen, obj) { - return gen._pushBuffer(gen, obj.slice()) - } +module.exports.signQuery = signQuery; +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * \n + * \n + * \n + * \n + * [headers\n] + * + * + * @param {Object} options + * @return {String} + * @api private + */ - _pushRegexp (gen, obj) { - return gen._pushTag(TAG.REGEXP) && gen.pushAny(obj.source) - } +function stringToSign(options) { + var headers = options.amazonHeaders || ''; + if (headers) headers += '\n'; + var r = [options.verb, options.md5, options.contentType, options.date ? options.date.toUTCString() : '', headers + options.resource]; + return r.join('\n'); +} - _pushSet (gen, obj) { - if (!gen._pushInt(obj.size, MT.ARRAY)) { - return false - } - for (let x of obj) { - if (!gen.pushAny(x)) { - return false - } - } - return true - } +module.exports.stringToSign = stringToSign; +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * \n + * + * + * @param {Object} options + * @return {String} + * @api private + */ - _pushUrl (gen, obj) { - return gen._pushTag(TAG.URI) && gen.pushAny(obj.format()) - } +function queryStringToSign(options) { + return 'GET\n\n\n' + options.date + '\n' + options.resource; +} - _pushBigint (obj) { - let tag = TAG.POS_BIGINT - if (obj.isNegative()) { - obj = obj.negated().minus(1) - tag = TAG.NEG_BIGINT - } - let str = obj.toString(16) - if (str.length % 2) { - str = '0' + str - } - const buf = Buffer.from(str, 'hex') - return this._pushTag(tag) && this._pushBuffer(this, buf) - } +module.exports.queryStringToSign = queryStringToSign; +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ - _pushBigNumber (gen, obj) { - if (obj.isNaN()) { - return gen._pushNaN() - } - if (!obj.isFinite()) { - return gen._pushInfinity(obj.isNegative() ? -Infinity : Infinity) - } - if (obj.isInteger()) { - return gen._pushBigint(obj) - } - if (!(gen._pushTag(TAG.DECIMAL_FRAC) && - gen._pushInt(2, MT.ARRAY))) { - return false - } +function canonicalizeHeaders(headers) { + var buf = [], + fields = Object.keys(headers); - const dec = obj.decimalPlaces() - const slide = obj.multipliedBy(new Bignumber(10).pow(dec)) - if (!gen._pushIntNum(-dec)) { - return false - } - if (slide.abs().isLessThan(MAXINT_BN)) { - return gen._pushIntNum(slide.toNumber()) - } else { - return gen._pushBigint(slide) - } + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i], + val = headers[field], + field = field.toLowerCase(); + if (0 !== field.indexOf('x-amz')) continue; + buf.push(field + ':' + val); } - _pushMap (gen, obj) { - if (!gen._pushInt(obj.size, MT.MAP)) { - return false - } + return buf.sort().join('\n'); +} - return this._pushRawMap( - obj.size, - Array.from(obj) - ) - } +module.exports.canonicalizeHeaders = canonicalizeHeaders; +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ - _pushObject (obj) { - if (!obj) { - return this._pushUInt8(NULL) - } +function canonicalizeResource(resource) { + var url = parse(resource, true), + path = url.pathname, + buf = []; + Object.keys(url.query).forEach(function (key) { + if (!~keys.indexOf(key)) return; + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]); + buf.push(key + val); + }); + return path + (buf.length ? '?' + buf.sort().join('&') : ''); +} - var len = this.semanticTypes.length - for (var i = 0; i < len; i++) { - if (obj instanceof this.semanticTypes[i][0]) { - return this.semanticTypes[i][1].call(obj, this, obj) - } - } +module.exports.canonicalizeResource = canonicalizeResource; - var f = obj.encodeCBOR - if (typeof f === 'function') { - return f.call(obj, this) - } +},{"crypto":undefined,"url":undefined}],134:[function(require,module,exports){ +"use strict"; - var keys = Object.keys(obj) - var keyLength = keys.length - if (!this._pushInt(keyLength, MT.MAP)) { - return false - } +var aws4 = exports, + url = require('url'), + querystring = require('querystring'), + crypto = require('crypto'), + lru = require('./lru'), + credentialsCache = lru(1000); // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html - return this._pushRawMap( - keyLength, - keys.map((k) => [k, obj[k]]) - ) - } - _pushRawMap (len, map) { - // Sort keys for canoncialization - // 1. encode key - // 2. shorter key comes before longer key - // 3. same length keys are sorted with lower - // byte value before higher +function hmac(key, string, encoding) { + return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding); +} - map = map.map(function (a) { - a[0] = Encoder.encode(a[0]) - return a - }).sort(utils.keySorter) +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding); +} // This function assumes the string has already been percent encoded - for (var j = 0; j < len; j++) { - if (!this.push(map[j][0])) { - return false - } - if (!this.pushAny(map[j][1])) { - return false - } - } +function encodeRfc3986(urlEncodedString) { + return urlEncodedString.replace(/[!'()*]/g, function (c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} // request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } - return true - } - /** - * Alias for `.pushAny` - * - * @param {*} obj - * @returns {boolean} true on success - */ - write (obj) { - return this.pushAny(obj) - } +function RequestSigner(request, credentials) { + if (typeof request === 'string') request = url.parse(request); + var headers = request.headers = request.headers || {}, + hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host); + this.request = request; + this.credentials = credentials || this.defaultCredentials(); + this.service = request.service || hostParts[0] || ''; + this.region = request.region || hostParts[1] || 'us-east-1'; // SES uses a different domain from the service name - /** - * Push any supported type onto the encoded stream - * - * @param {any} obj - * @returns {boolean} true on success - */ - pushAny (obj) { - var typ = toType(obj) + if (this.service === 'email') this.service = 'ses'; + if (!request.method && request.body) request.method = 'POST'; - switch (typ) { - case 'Number': - return this._pushNumber(obj) - case 'String': - return this._pushString(obj) - case 'Boolean': - return this._pushBoolean(obj) - case 'Object': - return this._pushObject(obj) - case 'Array': - return this._pushArray(this, obj) - case 'Uint8Array': - return this._pushBuffer(this, Buffer.isBuffer(obj) ? obj : Buffer.from(obj)) - case 'Null': - return this._pushUInt8(NULL) - case 'Undefined': - return this._pushUndefined(obj) - case 'Map': - return this._pushMap(this, obj) - case 'Set': - return this._pushSet(this, obj) - case 'Date': - return this._pushDate(this, obj) - case 'RegExp': - return this._pushRegexp(this, obj) - case 'Symbol': - switch (obj) { - case SYMS.NULL: - return this._pushObject(null) - case SYMS.UNDEFINED: - return this._pushUndefined(void 0) - // TODO: Add pluggable support for other symbols - default: - throw new Error('Unknown symbol: ' + obj.toString()) - } - default: - throw new Error('Unknown type: ' + typeof obj + ', ' + (obj ? obj.toString() : '')) - } + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost(); // If a port is specified explicitly, use it as is + + if (request.port) headers.Host += ':' + request.port; } - finalize () { - if (this.offset === 0) { - return null - } + if (!request.hostname && !request.host) request.hostname = headers.Host || headers.host; + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'; +} - var result = this.result - var resultLength = this.resultLength - var resultMethod = this.resultMethod - var offset = this.offset +RequestSigner.prototype.matchHost = function (host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/); + var hostParts = (match || []).slice(1, 3); // ES's hostParts are sometimes the other way round, if the value that is expected + // to be region equals ‘es’ switch them back + // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com - // Determine the size of the buffer - var size = 0 - var i = 0 + if (hostParts[1] === 'es') hostParts = hostParts.reverse(); + return hostParts; +}; // http://docs.aws.amazon.com/general/latest/gr/rande.html - for (; i < offset; i++) { - size += resultLength[i] - } - var res = Buffer.allocUnsafe(size) - var index = 0 - var length = 0 +RequestSigner.prototype.isSingleRegion = function () { + // Special case for S3 and SimpleDB in us-east-1 + if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true; + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'].indexOf(this.service) >= 0; +}; - // Write the content into the result buffer - for (i = 0; i < offset; i++) { - length = resultLength[i] +RequestSigner.prototype.createHost = function () { + var region = this.isSingleRegion() ? '' : (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region, + service = this.service === 'ses' ? 'email' : this.service; + return service + region + '.amazonaws.com'; +}; - switch (resultMethod[i]) { - case 0: - result[i].copy(res, index) - break - case 1: - res.writeUInt8(result[i], index, true) - break - case 2: - res.writeUInt16BE(result[i], index, true) - break - case 3: - res.writeUInt32BE(result[i], index, true) - break - case 4: - res.writeDoubleBE(result[i], index, true) - break - case 5: - res.write(result[i], index, length, 'utf8') - break - default: - throw new Error('unkown method') - } +RequestSigner.prototype.prepareRequest = function () { + this.parsePath(); + var request = this.request, + headers = request.headers, + query; - index += length + if (request.signQuery) { + this.parsedPath.query = query = this.parsedPath.query || {}; + if (this.credentials.sessionToken) query['X-Amz-Security-Token'] = this.credentials.sessionToken; + if (this.service === 's3' && !query['X-Amz-Expires']) query['X-Amz-Expires'] = 86400; + if (query['X-Amz-Date']) this.datetime = query['X-Amz-Date'];else query['X-Amz-Date'] = this.getDateTime(); + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'; + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString(); + query['X-Amz-SignedHeaders'] = this.signedHeaders(); + } else { + if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { + if (request.body && !headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; + if (request.body && !headers['Content-Length'] && !headers['content-length']) headers['Content-Length'] = Buffer.byteLength(request.body); + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) headers['X-Amz-Security-Token'] = this.credentials.sessionToken; + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex'); + if (headers['X-Amz-Date'] || headers['x-amz-date']) this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'];else headers['X-Amz-Date'] = this.getDateTime(); } - var tmp = res + delete headers.Authorization; + delete headers.authorization; + } +}; - this._reset() +RequestSigner.prototype.sign = function () { + if (!this.parsedPath) this.prepareRequest(); - return tmp + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature(); + } else { + this.request.headers.Authorization = this.authHeader(); } - _reset () { - this.result = [] - this.resultMethod = [] - this.resultLength = [] - this.offset = 0 - } + this.request.path = this.formatPath(); + return this.request; +}; - /** - * Encode the given value - * @param {*} o - * @returns {Buffer} - */ - static encode (o) { - const enc = new Encoder() - const ret = enc.pushAny(o) - if (!ret) { - throw new Error('Failed to encode input') - } +RequestSigner.prototype.getDateTime = function () { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date()); + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, ''); // Remove the trailing 'Z' on the timestamp string for CodeCommit git access - return enc.finalize() + if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1); } -} - -module.exports = Encoder -},{"./constants":136,"./utils":144,"bignumber.js":79,"url":undefined}],141:[function(require,module,exports){ -'use strict' + return this.datetime; +}; -// exports.Commented = require('./commented') -exports.Diagnose = require('./diagnose') -exports.Decoder = require('./decoder') -exports.Encoder = require('./encoder') -exports.Simple = require('./simple') -exports.Tagged = require('./tagged') +RequestSigner.prototype.getDate = function () { + return this.getDateTime().substr(0, 8); +}; -// exports.comment = exports.Commented.comment -exports.decodeAll = exports.Decoder.decodeAll -exports.decodeFirst = exports.Decoder.decodeFirst -exports.diagnose = exports.Diagnose.diagnose -exports.encode = exports.Encoder.encode -exports.decode = exports.Decoder.decode +RequestSigner.prototype.authHeader = function () { + return ['AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), 'SignedHeaders=' + this.signedHeaders(), 'Signature=' + this.signature()].join(', '); +}; -exports.leveldb = { - decode: exports.Decoder.decodeAll, - encode: exports.Encoder.encode, - buffer: true, - name: 'cbor' -} +RequestSigner.prototype.signature = function () { + var date = this.getDate(), + cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), + kDate, + kRegion, + kService, + kCredentials = credentialsCache.get(cacheKey); -},{"./decoder":138,"./diagnose":139,"./encoder":140,"./simple":142,"./tagged":143}],142:[function(require,module,exports){ -'use strict' + if (!kCredentials) { + kDate = hmac('AWS4' + this.credentials.secretAccessKey, date); + kRegion = hmac(kDate, this.region); + kService = hmac(kRegion, this.service); + kCredentials = hmac(kService, 'aws4_request'); + credentialsCache.set(cacheKey, kCredentials); + } -const constants = require('./constants') -const MT = constants.MT -const SIMPLE = constants.SIMPLE -const SYMS = constants.SYMS + return hmac(kCredentials, this.stringToSign(), 'hex'); +}; -/** - * A CBOR Simple Value that does not map onto a known constant. - */ -class Simple { - /** - * Creates an instance of Simple. - * - * @param {integer} value - the simple value's integer value - */ - constructor (value) { - if (typeof value !== 'number') { - throw new Error('Invalid Simple type: ' + (typeof value)) - } - if ((value < 0) || (value > 255) || ((value | 0) !== value)) { - throw new Error('value must be a small positive integer: ' + value) - } - this.value = value - } +RequestSigner.prototype.stringToSign = function () { + return ['AWS4-HMAC-SHA256', this.getDateTime(), this.credentialString(), hash(this.canonicalString(), 'hex')].join('\n'); +}; - /** - * Debug string for simple value - * - * @returns {string} simple(value) - */ - toString () { - return 'simple(' + this.value + ')' - } +RequestSigner.prototype.canonicalString = function () { + if (!this.parsedPath) this.prepareRequest(); + var pathStr = this.parsedPath.path, + query = this.parsedPath.query, + headers = this.request.headers, + queryStr = '', + normalizePath = this.service !== 's3', + decodePath = this.service === 's3' || this.request.doNotEncodePath, + decodeSlashesInPath = this.service === 's3', + firstValOnly = this.service === 's3', + bodyHash; - /** - * Debug string for simple value - * - * @returns {string} simple(value) - */ - inspect () { - return 'simple(' + this.value + ')' + if (this.service === 's3' && this.request.signQuery) { + bodyHash = 'UNSIGNED-PAYLOAD'; + } else if (this.isCodeCommitGit) { + bodyHash = ''; + } else { + bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || hash(this.request.body || '', 'hex'); } - /** - * Push the simple value onto the CBOR stream - * - * @param {cbor.Encoder} gen The generator to push onto - * @returns {number} - */ - encodeCBOR (gen) { - return gen._pushInt(this.value, MT.SIMPLE_FLOAT) + if (query) { + queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function (obj, key) { + if (!key) return obj; + obj[key] = !Array.isArray(query[key]) ? query[key] : firstValOnly ? query[key][0] : query[key].slice().sort(); + return obj; + }, {}))); } - /** - * Is the given object a Simple? - * - * @param {any} obj - object to test - * @returns {bool} - is it Simple? - */ - static isSimple (obj) { - return obj instanceof Simple - } + if (pathStr !== '/') { + if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/'); + pathStr = pathStr.split('/').reduce(function (path, piece) { + if (normalizePath && piece === '..') { + path.pop(); + } else if (!normalizePath || piece !== '.') { + if (decodePath) piece = decodeURIComponent(piece); + path.push(encodeRfc3986(encodeURIComponent(piece))); + } - /** - * Decode from the CBOR additional information into a JavaScript value. - * If the CBOR item has no parent, return a "safe" symbol instead of - * `null` or `undefined`, so that the value can be passed through a - * stream in object mode. - * - * @param {Number} val - the CBOR additional info to convert - * @param {bool} hasParent - Does the CBOR item have a parent? - * @returns {(null|undefined|Boolean|Symbol)} - the decoded value - */ - static decode (val, hasParent) { - if (hasParent == null) { - hasParent = true - } - switch (val) { - case SIMPLE.FALSE: - return false - case SIMPLE.TRUE: - return true - case SIMPLE.NULL: - if (hasParent) { - return null - } else { - return SYMS.NULL - } - case SIMPLE.UNDEFINED: - if (hasParent) { - return void 0 - } else { - return SYMS.UNDEFINED - } - case -1: - if (!hasParent) { - throw new Error('Invalid BREAK') - } - return SYMS.BREAK - default: - return new Simple(val) - } + return path; + }, []).join('/'); + if (pathStr[0] !== '/') pathStr = '/' + pathStr; + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/'); } -} -module.exports = Simple + return [this.request.method || 'GET', pathStr, queryStr, this.canonicalHeaders() + '\n', this.signedHeaders(), bodyHash].join('\n'); +}; -},{"./constants":136}],143:[function(require,module,exports){ -'use strict' +RequestSigner.prototype.canonicalHeaders = function () { + var headers = this.request.headers; -/** - * A CBOR tagged item, where the tag does not have semantics specified at the - * moment, or those semantics threw an error during parsing. Typically this will - * be an extension point you're not yet expecting. - */ -class Tagged { - /** - * Creates an instance of Tagged. - * - * @param {Number} tag - the number of the tag - * @param {any} value - the value inside the tag - * @param {Error} err - the error that was thrown parsing the tag, or null - */ - constructor (tag, value, err) { - this.tag = tag - this.value = value - this.err = err - if (typeof this.tag !== 'number') { - throw new Error('Invalid tag type (' + (typeof this.tag) + ')') - } - if ((this.tag < 0) || ((this.tag | 0) !== this.tag)) { - throw new Error('Tag must be a positive integer: ' + this.tag) - } + function trimAll(header) { + return header.toString().trim().replace(/\s+/g, ' '); } - /** - * Convert to a String - * - * @returns {String} string of the form '1(2)' - */ - toString () { - return `${this.tag}(${JSON.stringify(this.value)})` - } + return Object.keys(headers).sort(function (a, b) { + return a.toLowerCase() < b.toLowerCase() ? -1 : 1; + }).map(function (key) { + return key.toLowerCase() + ':' + trimAll(headers[key]); + }).join('\n'); +}; - /** - * Push the simple value onto the CBOR stream - * - * @param {cbor.Encoder} gen The generator to push onto - * @returns {number} - */ - encodeCBOR (gen) { - gen._pushTag(this.tag) - return gen.pushAny(this.value) - } +RequestSigner.prototype.signedHeaders = function () { + return Object.keys(this.request.headers).map(function (key) { + return key.toLowerCase(); + }).sort().join(';'); +}; - /** - * If we have a converter for this type, do the conversion. Some converters - * are built-in. Additional ones can be passed in. If you want to remove - * a built-in converter, pass a converter in whose value is 'null' instead - * of a function. - * - * @param {Object} converters - keys in the object are a tag number, the value - * is a function that takes the decoded CBOR and returns a JavaScript value - * of the appropriate type. Throw an exception in the function on errors. - * @returns {any} - the converted item - */ - convert (converters) { - var er, f - f = converters != null ? converters[this.tag] : void 0 - if (typeof f !== 'function') { - f = Tagged['_tag' + this.tag] - if (typeof f !== 'function') { - return this - } - } - try { - return f.call(Tagged, this.value) - } catch (error) { - er = error - this.err = er - return this - } - } -} +RequestSigner.prototype.credentialString = function () { + return [this.getDate(), this.region, this.service, 'aws4_request'].join('/'); +}; -module.exports = Tagged +RequestSigner.prototype.defaultCredentials = function () { + var env = process.env; + return { + accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, + secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, + sessionToken: env.AWS_SESSION_TOKEN + }; +}; -},{}],144:[function(require,module,exports){ -'use strict' +RequestSigner.prototype.parsePath = function () { + var path = this.request.path || '/', + queryIx = path.indexOf('?'), + query = null; -const Bignumber = require('bignumber.js') + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)); + path = path.slice(0, queryIx); + } // S3 doesn't always encode characters > 127 correctly and + // all services don't encode characters > 255 correctly + // So if there are non-reserved chars (and it's not already all % encoded), just encode them all -const constants = require('./constants') -const SHIFT32 = constants.SHIFT32 -const SHIFT16 = constants.SHIFT16 -const MAX_SAFE_HIGH = 0x1fffff -exports.parseHalf = function parseHalf (buf) { - var exp, mant, sign - sign = buf[0] & 0x80 ? -1 : 1 - exp = (buf[0] & 0x7C) >> 2 - mant = ((buf[0] & 0x03) << 8) | buf[1] - if (!exp) { - return sign * 5.9604644775390625e-8 * mant - } else if (exp === 0x1f) { - return sign * (mant ? 0 / 0 : 2e308) - } else { - return sign * Math.pow(2, exp - 25) * (1024 + mant) + if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) { + path = path.split('/').map(function (piece) { + return encodeURIComponent(decodeURIComponent(piece)); + }).join('/'); } -} -function toHex (n) { - if (n < 16) { - return '0' + n.toString(16) - } + this.parsedPath = { + path: path, + query: query + }; +}; - return n.toString(16) -} +RequestSigner.prototype.formatPath = function () { + var path = this.parsedPath.path, + query = this.parsedPath.query; + if (!query) return path; // Services don't support empty query string keys -exports.arrayBufferToBignumber = function (buf) { - const len = buf.byteLength - let res = '' - for (let i = 0; i < len; i++) { - res += toHex(buf[i]) - } + if (query[''] != null) delete query['']; + return path + '?' + encodeRfc3986(querystring.stringify(query)); +}; - return new Bignumber(res, 16) -} +aws4.RequestSigner = RequestSigner; -// convert an Object into a Map -exports.buildMap = (obj) => { - const res = new Map() - const keys = Object.keys(obj) - const length = keys.length - for (let i = 0; i < length; i++) { - res.set(keys[i], obj[keys[i]]) - } - return res -} +aws4.sign = function (request, credentials) { + return new RequestSigner(request, credentials).sign(); +}; + +},{"./lru":135,"crypto":undefined,"querystring":undefined,"url":undefined}],135:[function(require,module,exports){ +"use strict"; + +module.exports = function (size) { + return new LruCache(size); +}; -exports.buildInt32 = (f, g) => { - return f * SHIFT16 + g +function LruCache(size) { + this.capacity = size | 0; + this.map = Object.create(null); + this.list = new DoublyLinkedList(); } -exports.buildInt64 = (f1, f2, g1, g2) => { - const f = exports.buildInt32(f1, f2) - const g = exports.buildInt32(g1, g2) +LruCache.prototype.get = function (key) { + var node = this.map[key]; + if (node == null) return undefined; + this.used(node); + return node.val; +}; + +LruCache.prototype.set = function (key, val) { + var node = this.map[key]; - if (f > MAX_SAFE_HIGH) { - return new Bignumber(f).times(SHIFT32).plus(g) + if (node != null) { + node.val = val; } else { - return (f * SHIFT32) + g + if (!this.capacity) this.prune(); + if (!this.capacity) return false; + node = new DoublyLinkedNode(key, val); + this.map[key] = node; + this.capacity--; } -} -exports.writeHalf = function writeHalf (buf, half) { - // assume 0, -0, NaN, Infinity, and -Infinity have already been caught + this.used(node); + return true; +}; - // HACK: everyone settle in. This isn't going to be pretty. - // Translate cn-cbor's C code (from Carsten Borman): +LruCache.prototype.used = function (node) { + this.list.moveToFront(node); +}; - // uint32_t be32; - // uint16_t be16, u16; - // union { - // float f; - // uint32_t u; - // } u32; - // u32.f = float_val; +LruCache.prototype.prune = function () { + var node = this.list.pop(); - const u32 = Buffer.allocUnsafe(4) - u32.writeFloatBE(half, 0) - const u = u32.readUInt32BE(0) + if (node != null) { + delete this.map[node.key]; + this.capacity++; + } +}; - // if ((u32.u & 0x1FFF) == 0) { /* worth trying half */ +function DoublyLinkedList() { + this.firstNode = null; + this.lastNode = null; +} - // hildjj: If the lower 13 bits are 0, we won't lose anything in the conversion - if ((u & 0x1FFF) !== 0) { - return false - } +DoublyLinkedList.prototype.moveToFront = function (node) { + if (this.firstNode == node) return; + this.remove(node); - // int s16 = (u32.u >> 16) & 0x8000; - // int exp = (u32.u >> 23) & 0xff; - // int mant = u32.u & 0x7fffff; + if (this.firstNode == null) { + this.firstNode = node; + this.lastNode = node; + node.prev = null; + node.next = null; + } else { + node.prev = null; + node.next = this.firstNode; + node.next.prev = node; + this.firstNode = node; + } +}; - var s16 = (u >> 16) & 0x8000 // top bit is sign - const exp = (u >> 23) & 0xff // then 5 bits of exponent - const mant = u & 0x7fffff +DoublyLinkedList.prototype.pop = function () { + var lastNode = this.lastNode; - // if (exp == 0 && mant == 0) - // ; /* 0.0, -0.0 */ + if (lastNode != null) { + this.remove(lastNode); + } - // hildjj: zeros already handled. Assert if you don't believe me. + return lastNode; +}; - // else if (exp >= 113 && exp <= 142) /* normalized */ - // s16 += ((exp - 112) << 10) + (mant >> 13); - if ((exp >= 113) && (exp <= 142)) { - s16 += ((exp - 112) << 10) + (mant >> 13) +DoublyLinkedList.prototype.remove = function (node) { + if (this.firstNode == node) { + this.firstNode = node.next; + } else if (node.prev != null) { + node.prev.next = node.next; + } - // else if (exp >= 103 && exp < 113) { /* denorm, exp16 = 0 */ - // if (mant & ((1 << (126 - exp)) - 1)) - // goto float32; /* loss of precision */ - // s16 += ((mant + 0x800000) >> (126 - exp)); - } else if ((exp >= 103) && (exp < 113)) { - if (mant & ((1 << (126 - exp)) - 1)) { - return false - } - s16 += ((mant + 0x800000) >> (126 - exp)) + if (this.lastNode == node) { + this.lastNode = node.prev; + } else if (node.next != null) { + node.next.prev = node.prev; + } +}; - // } else if (exp == 255 && mant == 0) { /* Inf */ - // s16 += 0x7c00; +function DoublyLinkedNode(key, val) { + this.key = key; + this.val = val; + this.prev = null; + this.next = null; +} - // hildjj: Infinity already handled +},{}],136:[function(require,module,exports){ +"use strict"; - // } else - // goto float32; /* loss of range */ - } else { - return false - } +/** + * Expose `Backoff`. + */ +module.exports = Backoff; +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ - // ensure_writable(3); - // u16 = s16; - // be16 = hton16p((const uint8_t*)&u16); - buf.writeUInt16BE(s16, 0) - return true +function Backoff(opts) { + opts = opts || {}; + this.ms = opts.min || 100; + this.max = opts.max || 10000; + this.factor = opts.factor || 2; + this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; + this.attempts = 0; } +/** + * Return the backoff duration. + * + * @return {Number} + * @api public + */ -exports.keySorter = function (a, b) { - var lenA = a[0].byteLength - var lenB = b[0].byteLength - if (lenA > lenB) { - return 1 - } +Backoff.prototype.duration = function () { + var ms = this.ms * Math.pow(this.factor, this.attempts++); - if (lenB > lenA) { - return -1 + if (this.jitter) { + var rand = Math.random(); + var deviation = Math.floor(rand * this.jitter * ms); + ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; } - return a[0].compare(b[0]) -} + return Math.min(ms, this.max) | 0; +}; +/** + * Reset the number of attempts. + * + * @api public + */ -// Adapted from http://www.2ality.com/2012/03/signedzero.html -exports.isNegativeZero = (x) => { - return x === 0 && (1 / x < 0) -} -exports.nextPowerOf2 = (n) => { - let count = 0 - // First n in the below condition is for - // the case where n is 0 - if (n && !(n & (n - 1))) { - return n - } +Backoff.prototype.reset = function () { + this.attempts = 0; +}; +/** + * Set the minimum duration + * + * @api public + */ - while (n !== 0) { - n >>= 1 - count += 1 - } - return 1 << count -} +Backoff.prototype.setMin = function (min) { + this.ms = min; +}; +/** + * Set the maximum duration + * + * @api public + */ -},{"./constants":136,"bignumber.js":79}],145:[function(require,module,exports){ -var concatMap = require('concat-map'); -var balanced = require('balanced-match'); -module.exports = expandTop; +Backoff.prototype.setMax = function (max) { + this.max = max; +}; +/** + * Set the jitter + * + * @api public + */ -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} +Backoff.prototype.setJitter = function (jitter) { + this.jitter = jitter; +}; -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} +},{}],137:[function(require,module,exports){ +'use strict'; -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + var r = range(a, b, str); + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} - var parts = []; - var m = balanced('{', '}', str); +balanced.range = range; - if (!m) - return str.split(','); +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [begs.pop(), bi]; + } else { + beg = begs.pop(); - parts.push.apply(parts, p); + if (beg < left) { + left = beg; + right = bi; + } - return parts; -} + bi = str.indexOf(b, i + 1); + } -function expandTop(str) { - if (!str) - return []; + i = ai < bi && ai >= 0 ? ai : bi; + } - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); + if (begs.length) { + result = [left, right]; + } } - return expand(escapeBraces(str), true).map(unescapeBraces); + return result; } -function identity(e) { - return e; -} +},{}],138:[function(require,module,exports){ +"use strict"; -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} +// base-x encoding / decoding +// Copyright (c) 2018 base-x contributors +// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +var Buffer = require('safe-buffer').Buffer; -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} +module.exports = function base(ALPHABET) { + if (ALPHABET.length >= 255) throw new TypeError('Alphabet too long'); + var BASE_MAP = new Uint8Array(256); + BASE_MAP.fill(255); -function expand(str, isTop) { - var expansions = []; + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) throw new TypeError(x + ' is ambiguous'); + BASE_MAP[xc] = i; + } - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } + function encode(source) { + if (!Buffer.isBuffer(source)) throw new TypeError('Expected Buffer'); + if (source.length === 0) return ''; // Skip & count leading zeroes. - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } // Allocate enough space in big-endian base58 representation. - var N; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); + var size = (pend - pbegin) * iFACTOR + 1 >>> 0; + var b58 = new Uint8Array(size); // Process the bytes. - N = []; + while (pbegin !== pend) { + var carry = source[pbegin]; // Apply "b58 = b58 * 256 + ch". - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } + var _i = 0; + + for (var _it = size - 1; (carry !== 0 || _i < length) && _it !== -1; _it--, _i++) { + carry += 256 * b58[_it] >>> 0; + b58[_it] = carry % BASE >>> 0; + carry = carry / BASE >>> 0; } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } + if (carry !== 0) throw new Error('Non-zero carry'); + length = _i; + pbegin++; + } // Skip leading zeroes in base58 result. - return expansions; -} + var it = size - length; -},{"balanced-match":67,"concat-map":159}],146:[function(require,module,exports){ -var r; + while (it !== size && b58[it] === 0) { + it++; + } // Translate the result into a string. -module.exports = function rand(len) { - if (!r) - r = new Rand(null); - return r.generate(len); -}; + var str = LEADER.repeat(zeroes); -function Rand(rand) { - this.rand = rand; -} -module.exports.Rand = Rand; + for (; it < size; ++it) { + str += ALPHABET.charAt(b58[it]); + } -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; + return str; + } -// Emulate crypto API using randy -Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); + function decodeUnsafe(source) { + if (typeof source !== 'string') throw new TypeError('Expected String'); + if (source.length === 0) return Buffer.alloc(0); + var psz = 0; // Skip leading spaces. - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; -}; + if (source[psz] === ' ') return; // Skip and count leading '1's. -if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; + var zeroes = 0; + var length = 0; - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; - } -} else { - // Node.js or Web worker with no crypto support - try { - var crypto = require('crypto'); - if (typeof crypto.randomBytes !== 'function') - throw new Error('Not supported'); + while (source[psz] === LEADER) { + zeroes++; + psz++; + } // Allocate enough space in big-endian base256 representation. - Rand.prototype._rand = function _rand(n) { - return crypto.randomBytes(n); - }; - } catch (e) { - } -} -},{"crypto":undefined}],147:[function(require,module,exports){ -var basex = require('base-x') -var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' + var size = (source.length - psz) * FACTOR + 1 >>> 0; // log(58) / log(256), rounded up. -module.exports = basex(ALPHABET) + var b256 = new Uint8Array(size); // Process the characters. -},{"base-x":68}],148:[function(require,module,exports){ -'use strict' + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; // Invalid character -var base58 = require('bs58') -var Buffer = require('safe-buffer').Buffer + if (carry === 255) return; + var _i2 = 0; -module.exports = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload) + for (var _it2 = size - 1; (carry !== 0 || _i2 < length) && _it2 !== -1; _it2--, _i2++) { + carry += BASE * b256[_it2] >>> 0; + b256[_it2] = carry % 256 >>> 0; + carry = carry / 256 >>> 0; + } - return base58.encode(Buffer.concat([ - payload, - checksum - ], payload.length + 4)) - } + if (carry !== 0) throw new Error('Non-zero carry'); + length = _i2; + psz++; + } // Skip trailing spaces. - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4) - var checksum = buffer.slice(-4) - var newChecksum = checksumFn(payload) - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return + if (source[psz] === ' ') return; // Skip leading zeroes in b256. - return payload - } + var it = size - length; - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string) - if (!buffer) return + while (it !== size && b256[it] === 0) { + it++; + } + + var vch = Buffer.allocUnsafe(zeroes + (size - it)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + + while (it !== size) { + vch[j++] = b256[it++]; + } - return decodeRaw(buffer) + return vch; } - function decode (string) { - var buffer = base58.decode(string) - var payload = decodeRaw(buffer, checksumFn) - if (!payload) throw new Error('Invalid checksum') - return payload + function decode(string) { + var buffer = decodeUnsafe(string); + if (buffer) return buffer; + throw new Error('Non-base' + BASE + ' character'); } return { encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe - } -} - -},{"bs58":147,"safe-buffer":1256}],149:[function(require,module,exports){ -'use strict' - -var createHash = require('create-hash') -var bs58checkBase = require('./base') + decodeUnsafe: decodeUnsafe, + decode: decode + }; +}; -// SHA256(SHA256(buffer)) -function sha256x2 (buffer) { - var tmp = createHash('sha256').update(buffer).digest() - return createHash('sha256').update(tmp).digest() -} +},{"safe-buffer":2812}],139:[function(require,module,exports){ +"use strict"; -module.exports = bs58checkBase(sha256x2) +var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; +var RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'; +var CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; -},{"./base":148,"create-hash":167}],150:[function(require,module,exports){ -module.exports = function bufferIndexOf(buf,search,offset){ - offset = offset||0 - - var m = 0; - var s = -1; - for(var i=offset;i -1 && buf.length - s < search.length) return -1; - return s; -} + switch (variant) { + case 'RFC3548': + case 'RFC4648': + alphabet = RFC4648; + defaultPadding = true; + break; -},{}],151:[function(require,module,exports){ -var bufferIndexOf = require('buffer-indexof'); + case 'RFC4648-HEX': + alphabet = RFC4648_HEX; + defaultPadding = true; + break; -module.exports = function(buf,splitBuf,includeDelim){ - - var search = -1 - , lines = [] - , move = includeDelim?splitBuf.length:0 - ; + case 'Crockford': + alphabet = CROCKFORD; + defaultPadding = false; + break; - while((search = bufferIndexOf(buf,splitBuf)) > -1){ - lines.push(buf.slice(0,search+move)); - buf = buf.slice(search+splitBuf.length,buf.length); + default: + throw new Error('Unknown base32 variant: ' + variant); } - lines.push(buf); - - return lines; -} - + var padding = options.padding !== undefined ? options.padding : defaultPadding; + var length = buffer.byteLength; + var view = new Uint8Array(buffer); + var bits = 0; + var value = 0; + var output = ''; + for (var i = 0; i < length; i++) { + value = value << 8 | view[i]; + bits += 8; + while (bits >= 5) { + output += alphabet[value >>> bits - 5 & 31]; + bits -= 5; + } + } + if (bits > 0) { + output += alphabet[value << 5 - bits & 31]; + } -},{"buffer-indexof":150}],152:[function(require,module,exports){ -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ + if (padding) { + while (output.length % 8 !== 0) { + output += '='; + } + } -'use strict'; + return output; +}; +},{}],140:[function(require,module,exports){ +"use strict"; /** - * Module exports. - * @public + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method */ -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; - +var charmap = function charmap(alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +}; /** - * Module variables. - * @private + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} */ -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: ((1 << 30) * 1024) +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } }; - -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i; - +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); /** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} */ -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } - - if (typeof value === 'number') { - return format(value, options); +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 } +}; +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ - return null; -} - +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); /** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. + * Create a new `Decoder` with the given options. * - * @param {number} value * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor */ -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } +function Decoder(options) { + this.buf = []; + this.shift = 8; + this.carry = 0; - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; + if (options) { + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; - } - } + case "crockford": + this.charmap = exports.crockford.charmap; + break; - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } + default: + throw new Error("invalid type"); + } - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); + if (options.charmap) this.charmap = options.charmap; } - - return str + unitSeparator + unit; } - /** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public + * The default character map coresponds to RFC4648. */ -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } - - if (typeof val !== 'string') { - return null; - } - - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - - return Math.floor(map[unit] * floatValue); -} - -},{}],153:[function(require,module,exports){ -'use strict' -const mh = require('multihashes') +Decoder.prototype.charmap = rfc4648.charmap; +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ -var CIDUtil = { - /** - * Test if the given input is a valid CID object. - * Returns an error message if it is not. - * Returns undefined if it is a valid CID. - * - * @param {any} other - * @returns {string} - */ - checkCIDComponents: function (other) { - if (other == null) { - return 'null values are not valid CIDs' - } +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; // decode string - if (!(other.version === 0 || other.version === 1)) { - return 'Invalid version, must be a number equal to 1 or 0' - } + str.toUpperCase().split("").forEach(function (_char) { + // ignore padding + if (_char == "=") return; // lookup symbol - if (typeof other.codec !== 'string') { - return 'codec must be string' - } + var symbol = charmap[_char] & 0xff; // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 - if (!Buffer.isBuffer(other.multihash)) { - return 'multihash must be a Buffer' - } + shift -= 5; - try { - mh.validate(other.multihash) - } catch (err) { - let errorMsg = err.message - if (!errorMsg) { // Just in case mh.validate() throws an error with empty error message - errorMsg = 'Multihash validation failed' - } - return errorMsg + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | symbol >> -shift); + shift += 8; + carry = symbol << shift & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; } - } -} - -module.exports = CIDUtil + }); // save state -},{"multihashes":984}],154:[function(require,module,exports){ -'use strict' - -const mh = require('multihashes') -const multibase = require('multibase') -const multicodec = require('multicodec') -const codecs = require('multicodec/src/base-table') -const codecVarints = require('multicodec/src/varint-table') -const multihash = require('multihashes') -const CIDUtil = require('./cid-util') + this.shift = shift; + this.carry = carry; // for chaining + return this; +}; /** - * @typedef {Object} SerializedCID - * @param {string} codec - * @param {number} version - * @param {Buffer} multihash + * Finish decoding. * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. */ -/** - * Class representing a CID `` - * , as defined in [ipld/cid](https://github.com/ipld/cid). - * @class CID - */ -class CID { - /** - * Create a new CID. - * - * The algorithm for argument input is roughly: - * ``` - * if (str) - * if (1st char is on multibase table) -> CID String - * else -> bs58 encoded multihash - * else if (Buffer) - * if (0 or 1) -> CID - * else -> multihash - * else if (Number) - * -> construct CID by parts - * - * ..if only JS had traits.. - * ``` - * - * @param {string|Buffer} version - * @param {string} [codec] - * @param {Buffer} [multihash] - * - * @example - * - * new CID(, , ) - * new CID() - * new CID() - * new CID() - * new CID() - * new CID() - * - */ - constructor (version, codec, multihash) { - if (CID.isCID(version)) { - let cid = version - this.version = cid.version - this.codec = cid.codec - this.multihash = Buffer.from(cid.multihash) - return - } - if (typeof version === 'string') { - if (multibase.isEncoded(version)) { // CID String (encoded with multibase) - const cid = multibase.decode(version) - version = parseInt(cid.slice(0, 1).toString('hex'), 16) - codec = multicodec.getCodec(cid.slice(1)) - multihash = multicodec.rmPrefix(cid.slice(1)) - } else { // bs58 string encoded multihash - codec = 'dag-pb' - multihash = mh.fromB58String(version) - version = 0 - } - } else if (Buffer.isBuffer(version)) { - const firstByte = version.slice(0, 1) - const v = parseInt(firstByte.toString('hex'), 16) - if (v === 0 || v === 1) { // CID - const cid = version - version = v - codec = multicodec.getCodec(cid.slice(1)) - multihash = multicodec.rmPrefix(cid.slice(1)) - } else { // multihash - codec = 'dag-pb' - multihash = version - version = 0 - } - } - - /** - * @type {string} - */ - this.codec = codec - - /** - * @type {number} - */ - this.version = version - - /** - * @type {Buffer} - */ - this.multihash = multihash - CID.validateCID(this) +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); } - /** - * The CID as a `Buffer` - * - * @return {Buffer} - * @readonly - * - * @memberOf CID - */ - get buffer () { - switch (this.version) { - case 0: - return this.multihash - case 1: - return Buffer.concat([ - Buffer.from('01', 'hex'), - Buffer.from(codecVarints[this.codec]), - this.multihash - ]) - default: - throw new Error('unsupported version') - } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; } - /** - * Get the prefix of the CID. - * - * @returns {Buffer} - * @readonly - */ - get prefix () { - return Buffer.concat([ - Buffer.from(`0${this.version}`, 'hex'), - codecVarints[this.codec], - multihash.prefix(this.multihash) - ]) - } + return this.buf; +}; +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ - /** - * Convert to a CID of version `0`. - * - * @returns {CID} - */ - toV0 () { - if (this.codec !== 'dag-pb') { - throw new Error('Cannot convert a non dag-pb CID to CIDv0') - } - return new CID(0, this.codec, this.multihash) - } +function Encoder(options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; - /** - * Convert to a CID of version `1`. - * - * @returns {CID} - */ - toV1 () { - return new CID(1, this.codec, this.multihash) - } + if (options) { + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; - /** - * Encode the CID into a string. - * - * @param {string} [base='base58btc'] - Base encoding to use. - * @returns {string} - */ - toBaseEncodedString (base) { - base = base || 'base58btc' + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; - switch (this.version) { - case 0: { - if (base !== 'base58btc') { - throw new Error('not supported with CIDv0, to support different bases, please migrate the instance do CIDv1, you can do that through cid.toV1()') - } - return mh.toB58String(this.multihash) - } - case 1: - return multibase.encode(base, this.buffer).toString() - default: - throw new Error('Unsupported version') - } - } + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; - /** - * Serialize to a plain object. - * - * @returns {SerializedCID} - */ - toJSON () { - return { - codec: this.codec, - version: this.version, - hash: this.multihash + default: + throw new Error("invalid type"); } - } - /** - * Compare equality with another CID. - * - * @param {CID} other - * @returns {bool} - */ - equals (other) { - return this.codec === other.codec && - this.version === other.version && - this.multihash.equals(other.multihash) - } - - /** - * Test if the given input is a CID. - * - * @param {any} other - * @returns {bool} - */ - static isCID (other) { - return !(CIDUtil.checkCIDComponents(other)) - } - - /** - * Test if the given input is a valid CID object. - * Throws if it is not. - * - * @param {any} other - * @returns {void} - */ - static validateCID (other) { - let errorMsg = CIDUtil.checkCIDComponents(other) - if (errorMsg) { - throw new Error(errorMsg) - } + if (options.alphabet) this.alphabet = options.alphabet;else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); } } +/** + * The default alphabet coresponds to RFC4648. + */ -CID.codecs = codecs - -module.exports = CID - -},{"./cid-util":153,"multibase":976,"multicodec":979,"multicodec/src/base-table":978,"multicodec/src/varint-table":982,"multihashes":984}],155:[function(require,module,exports){ -'use strict'; - -function withIs(Class, { className, symbolName }) { - const symbol = Symbol.for(symbolName); - const ClassIsWrapper = { - // The code below assigns the class wrapper to an object to trick - // JavaScript engines to show the name of the extended class when - // logging an instances. - // We are assigning an anonymous class (class wrapper) to the object - // with key `className` to keep the correct name. - // If this is not supported it falls back to logging `ClassIsWrapper`. - [className]: class extends Class { - constructor(...args) { - super(...args); - Object.defineProperty(this, symbol, { value: true }); - } +Encoder.prototype.alphabet = rfc4648.alphabet; +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ - get [Symbol.toStringTag]() { - return className; - } - }, - }[className]; +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; - ClassIsWrapper[`is${className}`] = (obj) => !!(obj && obj[symbol]); + var _byte; - return ClassIsWrapper; -} + var i; // encode each byte in buf -function withIsProto(Class, { className, symbolName, withoutNew }) { - const symbol = Symbol.for(symbolName); + for (i = 0; i < buf.length; i++) { + _byte = buf[i]; // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 - /* eslint-disable object-shorthand */ - const ClassIsWrapper = { - [className]: function (...args) { - if (withoutNew && !(this instanceof ClassIsWrapper)) { - return new ClassIsWrapper(...args); - } + symbol = carry | _byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; - const _this = Class.call(this, ...args) || this; + if (shift > 5) { + shift -= 5; + symbol = _byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } - if (_this && !_this[symbol]) { - Object.defineProperty(_this, symbol, { value: true }); - } + shift = 5 - shift; + carry = _byte << shift; + shift = 8 - shift; + } // save state - return _this; - }, - }[className]; - /* eslint-enable object-shorthand */ - ClassIsWrapper.prototype = Object.create(Class.prototype); - ClassIsWrapper.prototype.constructor = ClassIsWrapper; + this.shift = shift; + this.carry = carry; // for chaining - Object.defineProperty(ClassIsWrapper.prototype, Symbol.toStringTag, { - get() { - return className; - }, - }); + return this; +}; +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ - ClassIsWrapper[`is${className}`] = (obj) => !!(obj && obj[symbol]); - return ClassIsWrapper; -} +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } -module.exports = withIs; -module.exports.proto = withIsProto; + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } -},{}],156:[function(require,module,exports){ + return this.buf; +}; /** - * Slice reference. + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. */ -var slice = [].slice; +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; /** - * Bind `obj` to `fn`. + * Convenience decoder. * - * @param {Object} obj - * @param {Function|String} fn or string - * @return {Function} - * @api public + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. */ -module.exports = function(obj, fn){ - if ('string' == typeof fn) fn = obj[fn]; - if ('function' != typeof fn) throw new Error('bind() requires a function'); - var args = slice.call(arguments, 2); - return function(){ - return fn.apply(obj, args.concat(slice.call(arguments))); - } -}; -},{}],157:[function(require,module,exports){ - -/** - * Expose `Emitter`. - */ - -if (typeof module !== 'undefined') { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; // Exports. -},{}],158:[function(require,module,exports){ -module.exports = function(a, b){ - var fn = function(){}; - fn.prototype = b.prototype; - a.prototype = new fn; - a.prototype.constructor = a; -}; -},{}],159:[function(require,module,exports){ -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; +},{}],141:[function(require,module,exports){ +"use strict"; // Module dependencies. -},{}],160:[function(require,module,exports){ -/*! - * content-disposition - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ +var base32 = require("./base32"); // Wrap decoder finalize to return a buffer; -'use strict' -/** - * Module exports. - */ +var finalizeDecode = base32.Decoder.prototype.finalize; -module.exports = contentDisposition -module.exports.parse = parse +base32.Decoder.prototype.finalize = function (buf) { + var bytes = finalizeDecode.call(this, buf); + return new Buffer(bytes); +}; // Export Base32. -/** - * Module dependencies. - */ -var basename = require('path').basename +module.exports = base32; -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") +},{"./base32":140}],142:[function(require,module,exports){ +/*! + * basic-auth + * Copyright(c) 2013 TJ Holowaychuk + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed */ - -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex - +'use strict'; /** - * RegExp to match percent encoding escape. + * Module dependencies. + * @private */ -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } +var Buffer = require('safe-buffer').Buffer; /** - * RegExp to match non-latin1 characters. + * Module exports. + * @public */ -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g +module.exports = auth; +module.exports.parse = parse; /** - * RegExp to match quoted-pair in RFC 2616 + * RegExp for basic auth credentials * - * quoted-pair = "\" CHAR - * CHAR = + * credentials = auth-scheme 1*SP token68 + * auth-scheme = "Basic" ; case insensitive + * token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"=" + * @private */ -var QESC_REGEXP = /\\([\u0000-\u007f])/g - +var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/; /** - * RegExp to match chars that must be quoted-pair in RFC 2616 + * RegExp for basic auth user/pass + * + * user-pass = userid ":" password + * userid = * + * password = *TEXT + * @private */ -var QUOTE_REGEXP = /([\\"])/g - +var USER_PASS_REGEXP = /^([^:]*):(.*)$/; /** - * RegExp for various RFC 2616 grammar + * Parse the Authorization header field of a request. * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = + * @param {object} req + * @return {object} with .name and .pass + * @public */ -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ +function auth(req) { + if (!req) { + throw new TypeError('argument req is required'); + } -/** - * RegExp for various RFC 5987 grammar - * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - */ + if (_typeof(req) !== 'object') { + throw new TypeError('argument req is required to be an object'); + } // get header -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + var header = getAuthorization(req); // parse header + + return parse(header); +} /** - * RegExp for various RFC 6266 grammar - * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = + * Decode base64 string. + * @private */ -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex +function decodeBase64(str) { + return Buffer.from(str, 'base64').toString(); +} /** - * Create an attachment Content-Disposition header. - * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @api public + * Get the Authorization header from request object. + * @private */ -function contentDisposition (filename, options) { - var opts = options || {} - - // get type - var type = opts.type || 'attachment' - // get parameters - var params = createparams(filename, opts.fallback) +function getAuthorization(req) { + if (!req.headers || _typeof(req.headers) !== 'object') { + throw new TypeError('argument req is required to have headers property'); + } - // format into string - return format(new ContentDisposition(type, params)) + return req.headers.authorization; } - /** - * Create parameters object from filename and fallback. + * Parse basic auth to object. * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] + * @param {string} string * @return {object} - * @api private + * @public */ -function createparams (filename, fallback) { - if (filename === undefined) { - return - } - var params = {} +function parse(string) { + if (typeof string !== 'string') { + return undefined; + } // parse header - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } + var match = CREDENTIALS_REGEXP.exec(string); - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } + if (!match) { + return undefined; + } // decode user pass - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') - } - // restrict to file base name - var name = basename(filename) + var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1])); - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) + if (!userPass) { + return undefined; + } // return credentials object - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } + return new Credentials(userPass[1], userPass[2]); +} +/** + * Object to represent user credentials. + * @private + */ - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name - } - return params +function Credentials(name, pass) { + this.name = name; + this.pass = pass; } -/** - * Format object to Content-Disposition header. +},{"safe-buffer":2812}],143:[function(require,module,exports){ +'use strict'; + +var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash; +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @api private + * Credit for the actual porting work goes to: + * Devi Mandiri */ -function format (obj) { - var parameters = obj.parameters - var type = obj.type - - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') - } +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ - // start with normalized type - var string = String(type).toLowerCase() +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 - for (var i = 0; i < params.length; i++) { - param = params[i] - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) +var BLF_J = 0; - string += '; ' + param + '=' + val - } - } +var Blowfish = function Blowfish() { + this.S = [new Uint32Array([0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), new Uint32Array([0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), new Uint32Array([0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), new Uint32Array([0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])]; + this.P = new Uint32Array([0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b]); +}; - return string +function F(S, x8, i) { + return (S[0][x8[i + 3]] + S[1][x8[i + 2]] ^ S[2][x8[i + 1]]) + S[3][x8[i]]; } -/** - * Decode a RFC 6987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @api private - */ +; -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) +Blowfish.prototype.encipher = function (x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); + } - if (!match) { - throw new TypeError('invalid extended field value') + x[0] ^= this.P[0]; + + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i + 1]; } - var charset = match[1].toLowerCase() - var encoded = match[2] - var value + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; +}; - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) +Blowfish.prototype.decipher = function (x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = new Buffer(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i - 1]; } - return value -} + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @api private - */ +function stream2word(data, databytes) { + var i, + temp = 0; -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = temp << 8 | data[BLF_J]; + } + + return temp; } -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @api private - */ +; -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') +Blowfish.prototype.expand0state = function (key, keybytes) { + var d = new Uint32Array(2), + i, + k; + var d8 = new Uint8Array(d.buffer); + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); } - var match = DISPOSITION_TYPE_REGEXP.exec(string) + BLF_J = 0; - if (!match) { - throw new TypeError('invalid type format') + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i + 1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k + 1] = d[1]; + } } +}; - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() +Blowfish.prototype.expandstate = function (data, databytes, key, keybytes) { + var d = new Uint32Array(2), + i, + k; - var key - var names = [] - var params = {} - var value + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i + 1] = d[1]; + } - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k + 1] = d[1]; } + } - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + BLF_J = 0; +}; - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') - } +Blowfish.prototype.enc = function (data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i * 2)); + } +}; - names.push(key) +Blowfish.prototype.dec = function (data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i * 2)); + } +}; - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; - // overwrite existing value - params[key] = value - continue - } +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), + i, + ciphertext = new Uint8Array([79, 120, 121, 99, 104, 114, 111, 109, 97, 116, 105, 99, 66, 108, 111, 119, 102, 105, 115, 104, 83, 119, 97, 116, 68, 121, 110, 97, 109, 105, 116, 101]); //"OxychromaticBlowfishSwatDynamite" - if (typeof params[key] === 'string') { - continue - } + state.expandstate(sha2salt, 64, sha2pass, 64); - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } - params[key] = value + for (i = 0; i < BCRYPT_BLOCKS; i++) { + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); } - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') + for (i = 0; i < 64; i++) { + state.enc(cdata, cdata.byteLength / 8); } - return new ContentDisposition(type, params) + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4 * i + 3] = cdata[i] >>> 24; + out[4 * i + 2] = cdata[i] >>> 16; + out[4 * i + 1] = cdata[i] >>> 8; + out[4 * i + 0] = cdata[i]; + } } -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @api private - */ - -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} +; -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @api private - */ +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen + 4), + i, + j, + amt, + stride, + dest, + count, + origkeylen = keylen; + if (rounds < 1) return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || keylen > out.byteLength * out.byteLength || saltlen > 1 << 20) return -1; + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); -function pencode (char) { - var hex = String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() - return hex.length === 1 - ? '%0' + hex - : '%' + hex -} + for (i = 0; i < saltlen; i++) { + countsalt[i] = salt[i]; + } -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @api private - */ + crypto_hash_sha512(sha2pass, pass, passlen); -function qstring (val) { - var str = String(val) + for (count = 1; keylen > 0; count++) { + countsalt[saltlen + 0] = count >>> 24; + countsalt[saltlen + 1] = count >>> 16; + countsalt[saltlen + 2] = count >>> 8; + countsalt[saltlen + 3] = count; + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + for (i = out.byteLength; i--;) { + out[i] = tmpout[i]; + } -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @api private - */ + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); -function ustring (val) { - var str = String(val) + for (j = 0; j < out.byteLength; j++) { + out[j] ^= tmpout[j]; + } + } - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + amt = Math.min(amt, keylen); - return 'UTF-8\'\'' + encoded -} + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) break; + key[dest] = out[i]; + } -/** - * Class for parsed Content-Disposition header for v8 optimization - */ + keylen -= i; + } -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters + return 0; } -},{"path":undefined}],161:[function(require,module,exports){ -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +; +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf +}; -'use strict' +},{"tweetnacl":144}],144:[function(require,module,exports){ +"use strict"; -/** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ +(function (nacl) { + 'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. + // Public domain. + // + // Implementation derived from TweetNaCl version 20140427. + // See for details: http://tweetnacl.cr.yp.to/ -/** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + var gf = function gf(init) { + var i, + r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) { + r[i] = init[i]; + } + return r; + }; // Pluggable, initialized in high-level API below. -/** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + var randombytes = function randombytes() + /* x, n */ + { + throw new Error('no PRNG'); + }; -/** - * Module exports. - * @public - */ + var _0 = new Uint8Array(16); + + var _9 = new Uint8Array(32); + + _9[0] = 9; + + var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + + function ts64(x, i, h, l) { + x[i] = h >> 24 & 0xff; + x[i + 1] = h >> 16 & 0xff; + x[i + 2] = h >> 8 & 0xff; + x[i + 3] = h & 0xff; + x[i + 4] = l >> 24 & 0xff; + x[i + 5] = l >> 16 & 0xff; + x[i + 6] = l >> 8 & 0xff; + x[i + 7] = l & 0xff; + } + + function vn(x, xi, y, yi, n) { + var i, + d = 0; + + for (i = 0; i < n; i++) { + d |= x[xi + i] ^ y[yi + i]; + } + + return (1 & d - 1 >>> 8) - 1; + } + + function crypto_verify_16(x, xi, y, yi) { + return vn(x, xi, y, yi, 16); + } + + function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); + } + + function core_salsa20(o, p, k, c) { + var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, + j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, + j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, + j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, + j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, + j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, + j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, + j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, + j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, + j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, + j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, + j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, + j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, + j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, + j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, + j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24; + var x0 = j0, + x1 = j1, + x2 = j2, + x3 = j3, + x4 = j4, + x5 = j5, + x6 = j6, + x7 = j7, + x8 = j8, + x9 = j9, + x10 = j10, + x11 = j11, + x12 = j12, + x13 = j13, + x14 = j14, + x15 = j15, + u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u << 7 | u >>> 32 - 7; + u = x4 + x0 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x4 | 0; + x12 ^= u << 13 | u >>> 32 - 13; + u = x12 + x8 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x1 | 0; + x9 ^= u << 7 | u >>> 32 - 7; + u = x9 + x5 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x9 | 0; + x1 ^= u << 13 | u >>> 32 - 13; + u = x1 + x13 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x6 | 0; + x14 ^= u << 7 | u >>> 32 - 7; + u = x14 + x10 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x14 | 0; + x6 ^= u << 13 | u >>> 32 - 13; + u = x6 + x2 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x11 | 0; + x3 ^= u << 7 | u >>> 32 - 7; + u = x3 + x15 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x3 | 0; + x11 ^= u << 13 | u >>> 32 - 13; + u = x11 + x7 | 0; + x15 ^= u << 18 | u >>> 32 - 18; + u = x0 + x3 | 0; + x1 ^= u << 7 | u >>> 32 - 7; + u = x1 + x0 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x1 | 0; + x3 ^= u << 13 | u >>> 32 - 13; + u = x3 + x2 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x4 | 0; + x6 ^= u << 7 | u >>> 32 - 7; + u = x6 + x5 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x6 | 0; + x4 ^= u << 13 | u >>> 32 - 13; + u = x4 + x7 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x9 | 0; + x11 ^= u << 7 | u >>> 32 - 7; + u = x11 + x10 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x11 | 0; + x9 ^= u << 13 | u >>> 32 - 13; + u = x9 + x8 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x14 | 0; + x12 ^= u << 7 | u >>> 32 - 7; + u = x12 + x15 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x12 | 0; + x14 ^= u << 13 | u >>> 32 - 13; + u = x14 + x13 | 0; + x15 ^= u << 18 | u >>> 32 - 18; + } + + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + o[0] = x0 >>> 0 & 0xff; + o[1] = x0 >>> 8 & 0xff; + o[2] = x0 >>> 16 & 0xff; + o[3] = x0 >>> 24 & 0xff; + o[4] = x1 >>> 0 & 0xff; + o[5] = x1 >>> 8 & 0xff; + o[6] = x1 >>> 16 & 0xff; + o[7] = x1 >>> 24 & 0xff; + o[8] = x2 >>> 0 & 0xff; + o[9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; + } + + function core_hsalsa20(o, p, k, c) { + var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, + j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, + j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, + j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, + j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, + j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, + j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, + j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, + j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, + j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, + j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, + j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, + j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, + j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, + j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, + j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24; + var x0 = j0, + x1 = j1, + x2 = j2, + x3 = j3, + x4 = j4, + x5 = j5, + x6 = j6, + x7 = j7, + x8 = j8, + x9 = j9, + x10 = j10, + x11 = j11, + x12 = j12, + x13 = j13, + x14 = j14, + x15 = j15, + u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u << 7 | u >>> 32 - 7; + u = x4 + x0 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x4 | 0; + x12 ^= u << 13 | u >>> 32 - 13; + u = x12 + x8 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x1 | 0; + x9 ^= u << 7 | u >>> 32 - 7; + u = x9 + x5 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x9 | 0; + x1 ^= u << 13 | u >>> 32 - 13; + u = x1 + x13 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x6 | 0; + x14 ^= u << 7 | u >>> 32 - 7; + u = x14 + x10 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x14 | 0; + x6 ^= u << 13 | u >>> 32 - 13; + u = x6 + x2 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x11 | 0; + x3 ^= u << 7 | u >>> 32 - 7; + u = x3 + x15 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x3 | 0; + x11 ^= u << 13 | u >>> 32 - 13; + u = x11 + x7 | 0; + x15 ^= u << 18 | u >>> 32 - 18; + u = x0 + x3 | 0; + x1 ^= u << 7 | u >>> 32 - 7; + u = x1 + x0 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x1 | 0; + x3 ^= u << 13 | u >>> 32 - 13; + u = x3 + x2 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x4 | 0; + x6 ^= u << 7 | u >>> 32 - 7; + u = x6 + x5 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x6 | 0; + x4 ^= u << 13 | u >>> 32 - 13; + u = x4 + x7 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x9 | 0; + x11 ^= u << 7 | u >>> 32 - 7; + u = x11 + x10 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x11 | 0; + x9 ^= u << 13 | u >>> 32 - 13; + u = x9 + x8 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x14 | 0; + x12 ^= u << 7 | u >>> 32 - 7; + u = x12 + x15 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x12 | 0; + x14 ^= u << 13 | u >>> 32 - 13; + u = x14 + x13 | 0; + x15 ^= u << 18 | u >>> 32 - 18; + } + + o[0] = x0 >>> 0 & 0xff; + o[1] = x0 >>> 8 & 0xff; + o[2] = x0 >>> 16 & 0xff; + o[3] = x0 >>> 24 & 0xff; + o[4] = x5 >>> 0 & 0xff; + o[5] = x5 >>> 8 & 0xff; + o[6] = x5 >>> 16 & 0xff; + o[7] = x5 >>> 24 & 0xff; + o[8] = x10 >>> 0 & 0xff; + o[9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; + } + + function crypto_core_salsa20(out, inp, k, c) { + core_salsa20(out, inp, k, c); + } + + function crypto_core_hsalsa20(out, inp, k, c) { + core_hsalsa20(out, inp, k, c); + } + + var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); // "expand 32-byte k" + + function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) { + var z = new Uint8Array(16), + x = new Uint8Array(64); + var u, i; -exports.format = format -exports.parse = parse + for (i = 0; i < 16; i++) { + z[i] = 0; + } -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public - */ + for (i = 0; i < 8; i++) { + z[i] = n[i]; + } -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } + while (b >= 64) { + crypto_core_salsa20(x, z, k, sigma); - var parameters = obj.parameters - var type = obj.type + for (i = 0; i < 64; i++) { + c[cpos + i] = m[mpos + i] ^ x[i]; + } - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') - } + u = 1; - var string = type + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + b -= 64; + cpos += 64; + mpos += 64; + } - for (var i = 0; i < params.length; i++) { - param = params[i] + if (b > 0) { + crypto_core_salsa20(x, z, k, sigma); - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') + for (i = 0; i < b; i++) { + c[cpos + i] = m[mpos + i] ^ x[i]; } - - string += '; ' + param + '=' + qstring(parameters[param]) } - } - return string -} + return 0; + } -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ + function crypto_stream_salsa20(c, cpos, b, n, k) { + var z = new Uint8Array(16), + x = new Uint8Array(64); + var u, i; -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } + for (i = 0; i < 16; i++) { + z[i] = 0; + } - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string + for (i = 0; i < 8; i++) { + z[i] = n[i]; + } - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } + while (b >= 64) { + crypto_core_salsa20(x, z, k, sigma); - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() + for (i = 0; i < 64; i++) { + c[cpos + i] = x[i]; + } - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') - } + u = 1; - var obj = new ContentType(type.toLowerCase()) + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } - // parse parameters - if (index !== -1) { - var key - var match - var value + b -= 64; + cpos += 64; + } - PARAM_REGEXP.lastIndex = index + if (b > 0) { + crypto_core_salsa20(x, z, k, sigma); - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') + for (i = 0; i < b; i++) { + c[cpos + i] = x[i]; } + } - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + return 0; + } - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } + function crypto_stream(c, cpos, d, n, k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k, sigma); + var sn = new Uint8Array(8); - obj.parameters[key] = value + for (var i = 0; i < 8; i++) { + sn[i] = n[i + 16]; } - if (index !== header.length) { - throw new TypeError('invalid parameter format') - } + return crypto_stream_salsa20(c, cpos, d, sn, s); } - return obj -} - -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ + function crypto_stream_xor(c, cpos, m, mpos, d, n, k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k, sigma); + var sn = new Uint8Array(8); -function getcontenttype (obj) { - var header + for (var i = 0; i < 8; i++) { + sn[i] = n[i + 16]; + } - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] + return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s); } + /* + * Port of Andrew Moon's Poly1305-donna-16. Public domain. + * https://github.com/floodyberry/poly1305-donna + */ - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') - } - return header -} + var poly1305 = function poly1305(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + var t0, t1, t2, t3, t4, t5, t6, t7; + t0 = key[0] & 0xff | (key[1] & 0xff) << 8; + this.r[0] = t0 & 0x1fff; + t1 = key[2] & 0xff | (key[3] & 0xff) << 8; + this.r[1] = (t0 >>> 13 | t1 << 3) & 0x1fff; + t2 = key[4] & 0xff | (key[5] & 0xff) << 8; + this.r[2] = (t1 >>> 10 | t2 << 6) & 0x1f03; + t3 = key[6] & 0xff | (key[7] & 0xff) << 8; + this.r[3] = (t2 >>> 7 | t3 << 9) & 0x1fff; + t4 = key[8] & 0xff | (key[9] & 0xff) << 8; + this.r[4] = (t3 >>> 4 | t4 << 12) & 0x00ff; + this.r[5] = t4 >>> 1 & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; + this.r[6] = (t4 >>> 14 | t5 << 2) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; + this.r[7] = (t5 >>> 11 | t6 << 5) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; + this.r[8] = (t6 >>> 8 | t7 << 8) & 0x1fff; + this.r[9] = t7 >>> 5 & 0x007f; + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; + }; -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @private - */ + poly1305.prototype.blocks = function (m, mpos, bytes) { + var hibit = this.fin ? 0 : 1 << 11; + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos + 0] & 0xff | (m[mpos + 1] & 0xff) << 8; + h0 += t0 & 0x1fff; + t1 = m[mpos + 2] & 0xff | (m[mpos + 3] & 0xff) << 8; + h1 += (t0 >>> 13 | t1 << 3) & 0x1fff; + t2 = m[mpos + 4] & 0xff | (m[mpos + 5] & 0xff) << 8; + h2 += (t1 >>> 10 | t2 << 6) & 0x1fff; + t3 = m[mpos + 6] & 0xff | (m[mpos + 7] & 0xff) << 8; + h3 += (t2 >>> 7 | t3 << 9) & 0x1fff; + t4 = m[mpos + 8] & 0xff | (m[mpos + 9] & 0xff) << 8; + h4 += (t3 >>> 4 | t4 << 12) & 0x1fff; + h5 += t4 >>> 1 & 0x1fff; + t5 = m[mpos + 10] & 0xff | (m[mpos + 11] & 0xff) << 8; + h6 += (t4 >>> 14 | t5 << 2) & 0x1fff; + t6 = m[mpos + 12] & 0xff | (m[mpos + 13] & 0xff) << 8; + h7 += (t5 >>> 11 | t6 << 5) & 0x1fff; + t7 = m[mpos + 14] & 0xff | (m[mpos + 15] & 0xff) << 8; + h8 += (t6 >>> 8 | t7 << 8) & 0x1fff; + h9 += t7 >>> 5 | hibit; + c = 0; + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 0x1fff; + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 0x1fff; + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 0x1fff; + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 0x1fff; + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = d4 >>> 13; + d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 0x1fff; + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = d5 >>> 13; + d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 0x1fff; + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = d6 >>> 13; + d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 0x1fff; + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = d7 >>> 13; + d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 0x1fff; + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = d8 >>> 13; + d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 0x1fff; + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = d9 >>> 13; + d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += d9 >>> 13; + d9 &= 0x1fff; + c = (c << 2) + c | 0; + c = c + d0 | 0; + d0 = c & 0x1fff; + c = c >>> 13; + d1 += c; + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + mpos += 16; + bytes -= 16; + } + + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; + }; -function qstring (val) { - var str = String(val) + poly1305.prototype.finish = function (mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') - } + for (; i < 16; i++) { + this.buffer[i] = 0; + } - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type -} + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; -},{}],162:[function(require,module,exports){ -/** - * Module dependencies. - */ + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } -var crypto = require('crypto'); + this.h[0] += c * 5; + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; + g[9] -= 1 << 13; + mask = (c ^ 1) - 1; -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ + for (i = 0; i < 10; i++) { + g[i] &= mask; + } -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf('.')) - , mac = exports.sign(str, secret); - - return sha1(mac) == sha1(val) ? str : false; -}; + mask = ~mask; -/** - * Private - */ + for (i = 0; i < 10; i++) { + this.h[i] = this.h[i] & mask | g[i]; + } -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} + this.h[0] = (this.h[0] | this.h[1] << 13) & 0xffff; + this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 0xffff; + this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 0xffff; + this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 0xffff; + this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 0xffff; + this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 0xffff; + this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 0xffff; + this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 0xffff; + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; -},{"crypto":undefined}],163:[function(require,module,exports){ -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + for (i = 1; i < 8; i++) { + f = (this.h[i] + this.pad[i] | 0) + (f >>> 16) | 0; + this.h[i] = f & 0xffff; + } -'use strict'; + mac[macpos + 0] = this.h[0] >>> 0 & 0xff; + mac[macpos + 1] = this.h[0] >>> 8 & 0xff; + mac[macpos + 2] = this.h[1] >>> 0 & 0xff; + mac[macpos + 3] = this.h[1] >>> 8 & 0xff; + mac[macpos + 4] = this.h[2] >>> 0 & 0xff; + mac[macpos + 5] = this.h[2] >>> 8 & 0xff; + mac[macpos + 6] = this.h[3] >>> 0 & 0xff; + mac[macpos + 7] = this.h[3] >>> 8 & 0xff; + mac[macpos + 8] = this.h[4] >>> 0 & 0xff; + mac[macpos + 9] = this.h[4] >>> 8 & 0xff; + mac[macpos + 10] = this.h[5] >>> 0 & 0xff; + mac[macpos + 11] = this.h[5] >>> 8 & 0xff; + mac[macpos + 12] = this.h[6] >>> 0 & 0xff; + mac[macpos + 13] = this.h[6] >>> 8 & 0xff; + mac[macpos + 14] = this.h[7] >>> 0 & 0xff; + mac[macpos + 15] = this.h[7] >>> 8 & 0xff; + }; -/** - * Module exports. - * @public - */ + poly1305.prototype.update = function (m, mpos, bytes) { + var i, want; -exports.parse = parse; -exports.serialize = serialize; + if (this.leftover) { + want = 16 - this.leftover; + if (want > bytes) want = bytes; -/** - * Module variables. - * @private - */ + for (i = 0; i < want; i++) { + this.buffer[this.leftover + i] = m[mpos + i]; + } -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ + if (bytes >= 16) { + want = bytes - bytes % 16; + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + if (bytes) { + for (i = 0; i < bytes; i++) { + this.buffer[this.leftover + i] = m[mpos + i]; + } -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ + this.leftover += bytes; + } + }; -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); + function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; } - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; + function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x, 0, m, mpos, n, k); + return crypto_verify_16(h, hpos, x, 0); + } - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); + function crypto_secretbox(c, m, d, n, k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c, 0, m, 0, d, n, k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; + for (i = 0; i < 16; i++) { + c[i] = 0; } - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); + return 0; + } - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } + function crypto_secretbox_open(m, c, d, n, k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x, 0, 32, n, k); + if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1; + crypto_stream_xor(m, 0, c, 0, d, n, k); - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); + for (i = 0; i < 32; i++) { + m[i] = 0; } - } - return obj; -} - -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ + return 0; + } -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; + function set25519(r, a) { + var i; - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); + for (i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } } - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } + function car25519(o) { + var i, + v, + c = 1; - var value = enc(val); + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); + o[0] += c - 1 + 37 * (c - 1); } - var str = name + '=' + value; + function sel25519(p, q, b) { + var t, + c = ~(b - 1); - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; - if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); - str += '; Max-Age=' + Math.floor(maxAge); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } } - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); + function pack25519(o, n) { + var i, j, b; + var m = gf(), + t = gf(); + + for (i = 0; i < 16; i++) { + t[i] = n[i]; } - str += '; Domain=' + opt.domain; - } + car25519(t); + car25519(t); + car25519(t); - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; - str += '; Path=' + opt.path; - } + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - (m[i - 1] >> 16 & 1); + m[i - 1] &= 0xffff; + } - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); + m[15] = t[15] - 0x7fff - (m[14] >> 16 & 1); + b = m[15] >> 16 & 1; + m[14] &= 0xffff; + sel25519(t, m, 1 - b); } - str += '; Expires=' + opt.expires.toUTCString(); + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 0xff; + o[2 * i + 1] = t[i] >> 8; + } } - if (opt.httpOnly) { - str += '; HttpOnly'; + function neq25519(a, b) { + var c = new Uint8Array(32), + d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); } - if (opt.secure) { - str += '; Secure'; + function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; } - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; + function unpack25519(o, n) { + var i; - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } - } - - return str; -} - -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ + for (i = 0; i < 16; i++) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + + o[15] &= 0x7fff; + } + + function A(o, a, b) { + for (var i = 0; i < 16; i++) { + o[i] = a[i] + b[i]; + } + } + + function Z(o, a, b) { + for (var i = 0; i < 16; i++) { + o[i] = a[i] - b[i]; + } + } + + function M(o, a, b) { + var v, + c, + t0 = 0, + t1 = 0, + t2 = 0, + t3 = 0, + t4 = 0, + t5 = 0, + t6 = 0, + t7 = 0, + t8 = 0, + t9 = 0, + t10 = 0, + t11 = 0, + t12 = 0, + t13 = 0, + t14 = 0, + t15 = 0, + t16 = 0, + t17 = 0, + t18 = 0, + t19 = 0, + t20 = 0, + t21 = 0, + t22 = 0, + t23 = 0, + t24 = 0, + t25 = 0, + t26 = 0, + t27 = 0, + t28 = 0, + t29 = 0, + t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; // t15 left as is + // first car + + c = 1; + v = t0 + c + 65535; + c = Math.floor(v / 65536); + t0 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t2 + c + 65535; + c = Math.floor(v / 65536); + t2 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); // second car -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} + c = 1; + v = t0 + c + 65535; + c = Math.floor(v / 65536); + t0 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t2 + c + 65535; + c = Math.floor(v / 65536); + t2 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); + o[0] = t0; + o[1] = t1; + o[2] = t2; + o[3] = t3; + o[4] = t4; + o[5] = t5; + o[6] = t6; + o[7] = t7; + o[8] = t8; + o[9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; + } + + function S(o, a) { + M(o, a, a); + } + + function inv25519(o, i) { + var c = gf(); + var a; -},{}],164:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. + for (a = 0; a < 16; a++) { + c[a] = i[a]; + } -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. + for (a = 253; a >= 0; a--) { + S(c, c); + if (a !== 2 && a !== 4) M(c, c, i); + } -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); + for (a = 0; a < 16; a++) { + o[a] = c[a]; + } } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + function pow2523(o, i) { + var c = gf(); + var a; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; + for (a = 0; a < 16; a++) { + c[a] = i[a]; + } -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + for (a = 250; a >= 0; a--) { + S(c, c); + if (a !== 1) M(c, c, i); + } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + for (a = 0; a < 16; a++) { + o[a] = c[a]; + } + } -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; + function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), + r, + i; + var a = gf(), + b = gf(), + c = gf(), + d = gf(), + e = gf(), + f = gf(); -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; + for (i = 0; i < 31; i++) { + z[i] = n[i]; + } -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; + z[31] = n[31] & 127 | 64; + z[0] &= 248; + unpack25519(x, p); -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; + for (i = 0; i < 16; i++) { + b[i] = x[i]; + d[i] = a[i] = c[i] = 0; + } + + a[0] = d[0] = 1; + + for (i = 254; i >= 0; --i) { + r = z[i >>> 3] >>> (i & 7) & 1; + sel25519(a, b, r); + sel25519(c, d, r); + A(e, a, c); + Z(a, a, c); + A(c, b, d); + Z(b, b, d); + S(d, e); + S(f, a); + M(a, c, a); + M(c, b, e); + A(e, a, c); + Z(a, a, c); + S(b, a); + Z(c, d, f); + M(a, c, _121665); + A(a, a, d); + M(c, c, a); + M(a, d, f); + M(d, b, x); + S(b, e); + sel25519(a, b, r); + sel25519(c, d, r); + } -exports.isBuffer = Buffer.isBuffer; + for (i = 0; i < 16; i++) { + x[i + 16] = a[i]; + x[i + 32] = c[i]; + x[i + 48] = b[i]; + x[i + 64] = d[i]; + } -function objectToString(o) { - return Object.prototype.toString.call(o); -} + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32, x32); + M(x16, x16, x32); + pack25519(q, x16); + return 0; + } -},{}],165:[function(require,module,exports){ -'use strict' + function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); + } + + function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); + } + + function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); + } + + var crypto_box_afternm = crypto_secretbox; + var crypto_box_open_afternm = crypto_secretbox_open; + + function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); + } + + function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); + } + + var K = [0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817]; + + function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), + wl = new Int32Array(16), + bh0, + bh1, + bh2, + bh3, + bh4, + bh5, + bh6, + bh7, + bl0, + bl1, + bl2, + bl3, + bl4, + bl5, + bl6, + bl7, + th, + tl, + i, + j, + h, + l, + a, + b, + c, + d; + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + var pos = 0; + + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = m[j + 0] << 24 | m[j + 1] << 16 | m[j + 2] << 8 | m[j + 3]; + wl[i] = m[j + 4] << 24 | m[j + 5] << 16 | m[j + 6] << 8 | m[j + 7]; + } + + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; // add + + h = ah7; + l = al7; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; // Sigma1 + + h = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); + l = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; // Ch + + h = ah4 & ah5 ^ ~ah4 & ah6; + l = al4 & al5 ^ ~al4 & al6; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; // K + + h = K[i * 2]; + l = K[i * 2 + 1]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; // w + + h = wh[i % 16]; + l = wl[i % 16]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; // add + + h = th; + l = tl; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; // Sigma0 + + h = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); + l = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; // Maj + + h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; + l = al0 & al1 ^ al0 & al2 ^ al1 & al2; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + bh7 = c & 0xffff | d << 16; + bl7 = a & 0xffff | b << 16; // add + + h = bh3; + l = bl3; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = th; + l = tl; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + bh3 = c & 0xffff | d << 16; + bl3 = a & 0xffff | b << 16; + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i % 16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = wh[(j + 9) % 16]; + l = wl[(j + 9) % 16]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; // sigma0 + + th = wh[(j + 1) % 16]; + tl = wl[(j + 1) % 16]; + h = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; + l = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; // sigma1 + + th = wh[(j + 14) % 16]; + tl = wl[(j + 14) % 16]; + h = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; + l = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + wh[j] = c & 0xffff | d << 16; + wl[j] = a & 0xffff | b << 16; + } + } + } // add + + + h = ah0; + l = al0; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[0]; + l = hl[0]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[0] = ah0 = c & 0xffff | d << 16; + hl[0] = al0 = a & 0xffff | b << 16; + h = ah1; + l = al1; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[1]; + l = hl[1]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[1] = ah1 = c & 0xffff | d << 16; + hl[1] = al1 = a & 0xffff | b << 16; + h = ah2; + l = al2; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[2]; + l = hl[2]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[2] = ah2 = c & 0xffff | d << 16; + hl[2] = al2 = a & 0xffff | b << 16; + h = ah3; + l = al3; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[3]; + l = hl[3]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[3] = ah3 = c & 0xffff | d << 16; + hl[3] = al3 = a & 0xffff | b << 16; + h = ah4; + l = al4; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[4]; + l = hl[4]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[4] = ah4 = c & 0xffff | d << 16; + hl[4] = al4 = a & 0xffff | b << 16; + h = ah5; + l = al5; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[5]; + l = hl[5]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[5] = ah5 = c & 0xffff | d << 16; + hl[5] = al5 = a & 0xffff | b << 16; + h = ah6; + l = al6; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[6]; + l = hl[6]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[6] = ah6 = c & 0xffff | d << 16; + hl[6] = al6 = a & 0xffff | b << 16; + h = ah7; + l = al7; + a = l & 0xffff; + b = l >>> 16; + c = h & 0xffff; + d = h >>> 16; + h = hh[7]; + l = hl[7]; + a += l & 0xffff; + b += l >>> 16; + c += h & 0xffff; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[7] = ah7 = c & 0xffff | d << 16; + hl[7] = al7 = a & 0xffff | b << 16; + pos += 128; + n -= 128; + } + + return n; + } + + function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, + b = n; + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) { + x[i] = m[b - n + i]; + } + + x[n] = 128; + n = 256 - 128 * (n < 112 ? 1 : 0); + x[n - 9] = 0; + ts64(x, n - 8, b / 0x20000000 | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) { + ts64(out, 8 * i, hh[i], hl[i]); + } -const { deepEqual } = require('./utils') -const sum = (acc, val) => acc + val + return 0; + } -/** - * G-Counter - * - * Operation-based Increment-Only Counter CRDT - * - * Sources: - * "A comprehensive study of Convergent and Commutative Replicated Data Types" - * http://hal.upmc.fr/inria-00555588/document, "3.1.1 Op-based counter and 3.1.2 State-based increment-only Counter (G-Counter)" - */ + function add(p, q) { + var a = gf(), + b = gf(), + c = gf(), + d = gf(), + e = gf(), + f = gf(), + g = gf(), + h = gf(), + t = gf(); + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); + } + + function cswap(p, q, b) { + var i; -class GCounter { - constructor (id, counter) { - this.id = id - this._counters = counter ? counter : {} - this._counters[this.id] = this._counters[this.id] ? this._counters[this.id] : 0 + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } } - get value () { - return Object.values(this._counters).reduce(sum, 0) + function pack(r, p) { + var tx = gf(), + ty = gf(), + zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; } - increment (amount) { - if (amount && amount < 1) - return - - if (amount === undefined || amount === null) - amount = 1 + function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); - this._counters[this.id] = this._counters[this.id] + amount + for (i = 255; i >= 0; --i) { + b = s[i / 8 | 0] >> (i & 7) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } } - merge (other) { - // Go through each counter in the other counter - Object.entries(other._counters).forEach(([id, value]) => { - // Take the maximum of the counter value we have or the counter value they have - this._counters[id] = Math.max(this._counters[id] || 0, value) - }) + function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); } - toJSON () { - return { - id: this.id, - counters: this._counters - } - } + function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + scalarbase(p, d); + pack(pk, p); - isEqual (other) { - return GCounter.isEqual(this, other) - } + for (i = 0; i < 32; i++) { + sk[i + 32] = pk[i]; + } - static from (json) { - return new GCounter(json.id, json.counters) + return 0; } - static isEqual (a, b) { - if(a.id !== b.id) - return false + var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - return deepEqual(a._counters, b._counters) - } -} + function modL(r, x) { + var carry, i, j, k; -module.exports = GCounter + for (i = 63; i >= 32; --i) { + carry = 0; -},{"./utils":166}],166:[function(require,module,exports){ -'use strict' + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = x[j] + 128 >> 8; + x[j] -= carry * 256; + } -exports.deepEqual = (a, b) => { - const propsA = Object.getOwnPropertyNames(a) - const propsB = Object.getOwnPropertyNames(b) + x[j] += carry; + x[i] = 0; + } - if(propsA.length !== propsB.length) - return false + carry = 0; - for(let i = 0; i < propsA.length; i ++) { - const prop = propsA[i] - if(a[prop] !== b[prop]) - return false - } + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } - return true -} + for (j = 0; j < 32; j++) { + x[j] -= carry * L[j]; + } -class OperationTuple3 { - constructor (value, added, removed) { - this.value = value - this.added = new Set(added) - this.removed = new Set(removed) + for (i = 0; i < 32; i++) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } } - static create (value, added, removed) { - return new OperationTuple3(value, added, removed) - } + function reduce(r) { + var x = new Float64Array(64), + i; - static from (json) { - return OperationTuple3.create(json.value, json.added, json.removed) - } -} + for (i = 0; i < 64; i++) { + x[i] = r[i]; + } -exports.OperationTuple3 = OperationTuple3 + for (i = 0; i < 64; i++) { + r[i] = 0; + } -},{}],167:[function(require,module,exports){ -module.exports = require('crypto').createHash + modL(r, x); + } // Note: difference from C - smlen returned, not passed as argument. -},{"crypto":undefined}],168:[function(require,module,exports){ -module.exports = require('crypto').createHmac -},{"crypto":undefined}],169:[function(require,module,exports){ -'use strict'; -const crypto = require('crypto'); + function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), + h = new Uint8Array(64), + r = new Uint8Array(64); + var i, + j, + x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + var smlen = n + 64; -const create = algorithm => async (buffer, options) => { - options = Object.assign({ - outputFormat: 'hex' - }, options); + for (i = 0; i < n; i++) { + sm[64 + i] = m[i]; + } - const hash = crypto.createHash(algorithm); - hash.update(buffer, typeof buffer === 'string' ? 'utf8' : undefined); + for (i = 0; i < 32; i++) { + sm[32 + i] = d[32 + i]; + } - if (options.outputFormat === 'hex') { - return hash.digest('hex'); - } + crypto_hash(r, sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - return hash.digest().buffer; -}; + for (i = 32; i < 64; i++) { + sm[i] = sk[i]; + } -exports.sha1 = create('sha1'); -exports.sha256 = create('sha256'); -exports.sha384 = create('sha384'); -exports.sha512 = create('sha512'); + crypto_hash(h, sm, n + 64); + reduce(h); -},{"crypto":undefined}],170:[function(require,module,exports){ -"use strict" + for (i = 0; i < 64; i++) { + x[i] = 0; + } -const EE = require("events").EventEmitter + for (i = 0; i < 32; i++) { + x[i] = r[i]; + } -function DataQueue() { - const ee = new EE() - let q = [] - let ed + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } - function unleak() { - ee.removeAllListeners("err") - ee.removeAllListeners("data") + modL(sm.subarray(32), x); + return smlen; } - return { - append: data => { - if (ed) return ed - q.push(data) - ee.emit("data") - }, - prepend: data => { //better only call this before the get queue starts - if (ed) return ed - q.unshift(data) - }, - error: e => { - ed = e - ee.emit("err", e) - }, - get: cb => { - unleak() - if (ed) return cb(ed) - if (q.length) return cb(null, q.shift()) - ee.once("err", e => { - unleak() - cb(e) - }) - ee.once("data", () => { - unleak() - return cb(null, q.shift()) - }) - }, - height: () => q.length + function unpackneg(r, p) { + var t = gf(), + chk = gf(), + num = gf(), + den = gf(), + den2 = gf(), + den4 = gf(), + den6 = gf(); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]); + M(r[3], r[0], r[1]); + return 0; } -} -module.exports = DataQueue -},{"events":undefined}],171:[function(require,module,exports){ -/* @flow */ -'use strict' - -const KeytransformDatastore = require('./keytransform') -const ShardingDatastore = require('./sharding') -const MountDatastore = require('./mount') -const TieredDatastore = require('./tiered') -const NamespaceDatastore = require('./namespace') -const shard = require('./shard') - -exports.KeytransformDatastore = KeytransformDatastore -exports.ShardingDatastore = ShardingDatastore -exports.MountDatastore = MountDatastore -exports.TieredDatastore = TieredDatastore -exports.NamespaceDatastore = NamespaceDatastore -exports.shard = shard - -},{"./keytransform":172,"./mount":173,"./namespace":174,"./shard":176,"./sharding":177,"./tiered":178}],172:[function(require,module,exports){ -/* @flow */ -'use strict' + function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new Uint8Array(32), + h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + mlen = -1; + if (n < 64) return -1; + if (unpackneg(q, pk)) return -1; -const pull = require('pull-stream') + for (i = 0; i < n; i++) { + m[i] = sm[i]; + } -/* :: -import type {Key, Datastore, Batch, Query, QueryResult, Callback} from 'interface-datastore' -*/ + for (i = 0; i < 32; i++) { + m[i + 32] = pk[i]; + } -/** - * An object with a pair of functions for (invertibly) transforming keys - */ -/* :: -type KeyTransform = { - convert: KeyMapping, - invert: KeyMapping -} -*/ + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + n -= 64; -/** - * Map one key onto another key. - */ -/* :: -type KeyMapping = (Key) => Key -*/ + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) { + m[i] = 0; + } -/** - * A datastore shim, that wraps around a given datastore, changing - * the way keys look to the user, for example namespacing - * keys, reversing them, etc. - */ -class KeyTransformDatastore /* :: */ { - /* :: child: Datastore */ - /* :: transform: KeyTransform */ + return -1; + } - constructor (child /* : Datastore */, transform /* : KeyTransform */) { - this.child = child - this.transform = transform - } + for (i = 0; i < n; i++) { + m[i] = sm[i + 64]; + } + + mlen = n; + return mlen; + } + + var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES + }; + /* High-level API */ - open (callback /* : Callback */) /* : void */ { - this.child.open(callback) + function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } - put (key /* : Key */, val /* : Value */, callback /* : Callback */) /* : void */ { - this.child.put(this.transform.convert(key), val, callback) + function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } - get (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.get(this.transform.convert(key), callback) - } + function checkArrayTypes() { + var t, i; - has (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.has(this.transform.convert(key), callback) + for (i = 0; i < arguments.length; i++) { + if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') throw new TypeError('unexpected type ' + t + ', use Uint8Array'); + } } - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.delete(this.transform.convert(key), callback) + function cleanup(arr) { + for (var i = 0; i < arr.length; i++) { + arr[i] = 0; + } + } // TODO: Completely remove this in v0.15. + + + if (!nacl.util) { + nacl.util = {}; + + nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function () { + throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); + }; } - batch () /* : Batch */ { - const b = this.child.batch() - return { - put: (key /* : Key */, value /* : Value */) /* : void */ => { - b.put(this.transform.convert(key), value) - }, - delete: (key /* : Key */) /* : void */ => { - b.delete(this.transform.convert(key)) - }, - commit: (callback /* : Callback */) /* : void */ => { - b.commit(callback) - } + nacl.randomBytes = function (n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; + }; + + nacl.secretbox = function (msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + + for (var i = 0; i < msg.length; i++) { + m[i + crypto_secretbox_ZEROBYTES] = msg[i]; } - } - query (q /* : Query */) /* : QueryResult */ { - return pull( - this.child.query(q), - pull.map(e => { - e.key = this.transform.invert(e.key) - return e - }) - ) - } + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); + }; - close (callback /* : Callback */) /* : void */ { - this.child.close(callback) - } -} + nacl.secretbox.open = function (box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); -module.exports = KeyTransformDatastore + for (var i = 0; i < box.length; i++) { + c[i + crypto_secretbox_BOXZEROBYTES] = box[i]; + } -},{"pull-stream":1175}],173:[function(require,module,exports){ -/* @flow */ -'use strict' + if (c.length < 32) return false; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; + return m.subarray(crypto_secretbox_ZEROBYTES); + }; -const each = require('async/each') -const many = require('pull-many') -const pull = require('pull-stream') + nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; + nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; + nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; -const Key = require('interface-datastore').Key -const utils = require('interface-datastore').utils -const asyncFilter = utils.asyncFilter -const asyncSort = utils.asyncSort -const replaceStartWith = utils.replaceStartWith + nacl.scalarMult = function (n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; + }; -const Keytransform = require('./keytransform') + nacl.scalarMult.base = function (n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; + }; -/* :: -import type {Datastore, Callback, Batch, Query, QueryResult} from 'interface-datastore' + nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; + nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; -type Mount = { - prefix: Key, - datastore: Datastore -} -*/ + nacl.box = function (msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); + }; -/** - * A datastore that can combine multiple stores inside various - * key prefixs. - */ -class MountDatastore /* :: */ { - /* :: mounts: Array> */ + nacl.box.before = function (publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; + }; - constructor (mounts /* : Array> */) { - this.mounts = mounts.slice() - } + nacl.box.after = nacl.secretbox; - open (callback /* : Callback */) /* : void */ { - each(this.mounts, (m, cb) => { - m.datastore.open(cb) - }, callback) - } + nacl.box.open = function (msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); + }; - /** - * Lookup the matching datastore for the given key. - * - * @private - * @param {Key} key - * @returns {{Datastore, Key, Key}} - */ - _lookup (key /* : Key */) /* : ?{datastore: Datastore, mountpoint: Key, rest: Key} */ { - for (let mount of this.mounts) { - if (mount.prefix.toString() === key.toString() || mount.prefix.isAncestorOf(key)) { - const s = replaceStartWith(key.toString(), mount.prefix.toString()) - return { - datastore: mount.datastore, - mountpoint: mount.prefix, - rest: new Key(s) - } - } - } - } + nacl.box.open.after = nacl.secretbox.open; - put (key /* : Key */, value /* : Value */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(new Error('No datastore mounted for this key')) - return - } + nacl.box.keyPair = function () { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return { + publicKey: pk, + secretKey: sk + }; + }; - match.datastore.put(match.rest, value, callback) - } + nacl.box.keyPair.fromSecretKey = function (secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return { + publicKey: pk, + secretKey: new Uint8Array(secretKey) + }; + }; - get (key /* : Key */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(new Error('No datastore mounted for this key')) - return - } + nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; + nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; + nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; + nacl.box.nonceLength = crypto_box_NONCEBYTES; + nacl.box.overheadLength = nacl.secretbox.overheadLength; + + nacl.sign = function (msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; + }; - match.datastore.get(match.rest, callback) - } + nacl.sign.open = function (signedMsg, publicKey) { + if (arguments.length !== 2) throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); - has (key /* : Key */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(null, false) - return + for (var i = 0; i < m.length; i++) { + m[i] = tmp[i]; } - match.datastore.has(match.rest, callback) - } + return m; + }; - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(new Error('No datastore mounted for this key')) - return - } + nacl.sign.detached = function (msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); - match.datastore.delete(match.rest, callback) - } + for (var i = 0; i < sig.length; i++) { + sig[i] = signedMsg[i]; + } - close (callback /* : Callback */) /* : void */ { - each(this.mounts, (m, cb) => { - m.datastore.close(cb) - }, callback) - } + return sig; + }; - batch () /* : Batch */ { - const batchMounts = {} - const lookup = (key /* : Key */) /* : {batch: Batch, rest: Key} */ => { - const match = this._lookup(key) - if (match == null) { - throw new Error('No datastore mounted for this key') - } + nacl.sign.detached.verify = function (msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; - const m = match.mountpoint.toString() - if (batchMounts[m] == null) { - batchMounts[m] = match.datastore.batch() - } + for (i = 0; i < crypto_sign_BYTES; i++) { + sm[i] = sig[i]; + } - return { - batch: batchMounts[m], - rest: match.rest - } + for (i = 0; i < msg.length; i++) { + sm[i + crypto_sign_BYTES] = msg[i]; } + return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; + }; + + nacl.sign.keyPair = function () { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); return { - put: (key /* : Key */, value /* : Value */) /* : void */ => { - const match = lookup(key) - match.batch.put(match.rest, value) - }, - delete: (key /* : Key */) /* : void */ => { - const match = lookup(key) - match.batch.delete(match.rest) - }, - commit: (callback /* : Callback */) /* : void */ => { - each(Object.keys(batchMounts), (p, cb) => { - batchMounts[p].commit(cb) - }, callback) - } - } - } + publicKey: pk, + secretKey: sk + }; + }; - query (q /* : Query */) /* : QueryResult */ { - const qs = this.mounts.map(m => { - const ks = new Keytransform(m.datastore, { - convert: (key /* : Key */) /* : Key */ => { - throw new Error('should never be called') - }, - invert: (key /* : Key */) /* : Key */ => { - return m.prefix.child(key) - } - }) + nacl.sign.keyPair.fromSecretKey = function (secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - let prefix - if (q.prefix != null) { - prefix = replaceStartWith(q.prefix, m.prefix.toString()) - } + for (var i = 0; i < pk.length; i++) { + pk[i] = secretKey[32 + i]; + } - return ks.query({ - prefix: prefix, - filters: q.filters, - keysOnly: q.keysOnly - }) - }) + return { + publicKey: pk, + secretKey: new Uint8Array(secretKey) + }; + }; - let tasks = [many(qs)] + nacl.sign.keyPair.fromSeed = function (seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - if (q.filters != null) { - tasks = tasks.concat(q.filters.map(f => asyncFilter(f))) + for (var i = 0; i < 32; i++) { + sk[i] = seed[i]; } - if (q.orders != null) { - tasks = tasks.concat(q.orders.map(o => asyncSort(o))) - } + crypto_sign_keypair(pk, sk, true); + return { + publicKey: pk, + secretKey: sk + }; + }; - if (q.offset != null) { - let i = 0 - // $FlowFixMe - tasks.push(pull.filter(() => i++ >= q.offset)) - } + nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; + nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; + nacl.sign.seedLength = crypto_sign_SEEDBYTES; + nacl.sign.signatureLength = crypto_sign_BYTES; - if (q.limit != null) { - tasks.push(pull.take(q.limit)) - } + nacl.hash = function (msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; + }; - return pull.apply(null, tasks) - } -} + nacl.hash.hashLength = crypto_hash_BYTES; -module.exports = MountDatastore + nacl.verify = function (x, y) { + checkArrayTypes(x, y); // Zero length arguments are considered not equal. -},{"./keytransform":172,"async/each":24,"interface-datastore":405,"pull-many":1165,"pull-stream":1175}],174:[function(require,module,exports){ -/* @flow */ -'use strict' + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return vn(x, 0, y, 0, x.length) === 0 ? true : false; + }; -const Key = require('interface-datastore').Key -const KeytransformDatastore = require('./keytransform') + nacl.setPRNG = function (fn) { + randombytes = fn; + }; -/* :: -import type {Callback, Datastore, Query, QueryResult} from 'interface-datastore' -*/ + (function () { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? self.crypto || self.msCrypto : null; -/** - * Wraps a given datastore into a keytransform which - * makes a given prefix transparent. - * - * For example, if the prefix is `new Key(/hello)` a call - * to `store.put(new Key('/world'), mydata)` would store the data under - * `/hello/world`. - * - */ -class NamespaceDatastore/* :: */ extends KeytransformDatastore /* :: */ { - /* :: prefix: Key */ + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function (x, n) { + var i, + v = new Uint8Array(n); - constructor (child/* : Datastore */, prefix/* : Key */) { - super(child, { - convert (key/* : Key */)/* : Key */ { - return prefix.child(key) - }, - invert (key/* : Key */)/* : Key */ { - if (prefix.toString() === '/') { - return key + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } - if (!prefix.isAncestorOf(key)) { - throw new Error(`Expected prefix: (${prefix.toString()}) in key: ${key.toString()}`) + for (i = 0; i < n; i++) { + x[i] = v[i]; } - return new Key(key.toString().slice(prefix.toString().length), false) - } - }) - - this.prefix = prefix - } + cleanup(v); + }); + } else if (typeof require !== 'undefined') { + // Node.js. + crypto = require('crypto'); - query (q /* : Query */)/* : QueryResult */ { - if (q.prefix && this.prefix.toString() !== '/') { - return super.query(Object.assign({}, q, { - prefix: this.prefix.child(new Key(q.prefix)).toString() - })) - } - return super.query(q) - } -} + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function (x, n) { + var i, + v = crypto.randomBytes(n); -module.exports = NamespaceDatastore + for (i = 0; i < n; i++) { + x[i] = v[i]; + } -},{"./keytransform":172,"interface-datastore":405}],175:[function(require,module,exports){ -/* @flow */ -'use strict' - -module.exports = `This is a repository of IPLD objects. Each IPLD object is in a single file, -named .data. Where is the -"base32" encoding of the CID (as specified in -https://github.com/multiformats/multibase) without the 'B' prefix. -All the object files are placed in a tree of directories, based on a -function of the CID. This is a form of sharding similar to -the objects directory in git repositories. Previously, we used -prefixes, we now use the next-to-last two charters. - func NextToLast(base32cid string) { - nextToLastLen := 2 - offset := len(base32cid) - nextToLastLen - 1 - return str[offset : offset+nextToLastLen] - } -For example, an object with a base58 CIDv1 of - zb2rhYSxw4ZjuzgCnWSt19Q94ERaeFhu9uSqRgjSdx9bsgM6f -has a base32 CIDv1 of - BAFKREIA22FLID5AJ2KU7URG47MDLROZIH6YF2KALU2PWEFPVI37YLKRSCA -and will be placed at - SC/AFKREIA22FLID5AJ2KU7URG47MDLROZIH6YF2KALU2PWEFPVI37YLKRSCA.data -with 'SC' being the last-to-next two characters and the 'B' at the -beginning of the CIDv1 string is the multibase prefix that is not -stored in the filename. -` - -},{}],176:[function(require,module,exports){ -/* @flow */ -'use strict' + cleanup(v); + }); + } + } + })(); +})(typeof module !== 'undefined' && module.exports ? module.exports : self.nacl = self.nacl || {}); -const leftPad = require('left-pad') -const Key = require('interface-datastore').Key +},{"crypto":undefined}],145:[function(require,module,exports){ +'use strict'; -const readme = require('./shard-readme') +var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; // pre-compute lookup table -// eslint-disable-next-line -/*:: import type {Datastore, Callback} from 'interface-datastore' +var ALPHABET_MAP = {}; -export interface ShardV1 { - name: string; - param: number; - fun(string): string; - toString(): string; +for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous'); + ALPHABET_MAP[x] = z; } -*/ -const PREFIX = exports.PREFIX = '/repo/flatfs/shard/' -const SHARDING_FN = exports.SHARDING_FN = 'SHARDING' -exports.README_FN = '_README' +function polymodStep(pre) { + var b = pre >> 25; + return (pre & 0x1FFFFFF) << 5 ^ -(b >> 0 & 1) & 0x3b6a57b2 ^ -(b >> 1 & 1) & 0x26508e6d ^ -(b >> 2 & 1) & 0x1ea119fa ^ -(b >> 3 & 1) & 0x3d4233dd ^ -(b >> 4 & 1) & 0x2a1462b3; +} -class Shard { - /* :: name: string */ - /* :: param: number */ - /* :: _padding: string */ +function prefixChk(prefix) { + var chk = 1; - constructor (param /* : number */) { - this.param = param + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) throw new Error('Invalid prefix (' + prefix + ')'); + chk = polymodStep(chk) ^ c >> 5; } - fun (str /* : string */) /* : string */ { - throw new Error('implement me') - } + chk = polymodStep(chk); - toString () /* : string */ { - return `${PREFIX}v1/${this.name}/${this.param}` + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ v & 0x1f; } + + return chk; } -class Prefix extends Shard { - constructor (prefixLen /* : number */) { - super(prefixLen) - this._padding = leftPad('', prefixLen, '_') - this.name = 'prefix' - } +function encode(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) throw new TypeError('Exceeds length limit'); + prefix = prefix.toLowerCase(); // determine chk mod - fun (noslash /* : string */) /* : string */ { - return (noslash + this._padding).slice(0, this.param) - } -} + var chk = prefixChk(prefix); + var result = prefix + '1'; -class Suffix extends Shard { - constructor (suffixLen /* : number */) { - super(suffixLen) - this._padding = leftPad('', suffixLen, '_') - this.name = 'suffix' + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if (x >> 5 !== 0) throw new Error('Non 5-bit word'); + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); } - fun (noslash /* : string */) /* : string */ { - const s = this._padding + noslash - return s.slice(s.length - this.param) + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); } -} -class NextToLast extends Shard { - constructor (suffixLen /* : number */) { - super(suffixLen) - this._padding = leftPad('', suffixLen + 1, '_') - this.name = 'next-to-last' - } + chk ^= 1; - fun (noslash /* : string */) /* : string */ { - const s = this._padding + noslash - const offset = s.length - this.param - 1 - return s.slice(offset, offset + this.param) + for (i = 0; i < 6; ++i) { + var v = chk >> (5 - i) * 5 & 0x1f; + result += ALPHABET.charAt(v); } + + return result; } -/** - * Convert a given string to the matching sharding function. - * - * @param {string} str - * @returns {ShardV1} - */ -function parseShardFun (str /* : string */) /* : ShardV1 */ { - str = str.trim() +function decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) throw new TypeError(str + ' too short'); + if (str.length > LIMIT) throw new TypeError('Exceeds length limit'); // don't allow mixed case + + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) throw new Error('Mixed-case string ' + str); + str = lowered; + var split = str.lastIndexOf('1'); + if (split === -1) throw new Error('No separator character for ' + str); + if (split === 0) throw new Error('Missing prefix for ' + str); + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) throw new Error('Data too short'); + var chk = prefixChk(prefix); + var words = []; - if (str.length === 0) { - throw new Error('empty shard string') - } + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) throw new Error('Unknown character ' + c); + chk = polymodStep(chk) ^ v; // not in the checksum? - if (!str.startsWith(PREFIX)) { - throw new Error(`invalid or no path prefix: ${str}`) + if (i + 6 >= wordChars.length) continue; + words.push(v); } - const parts = str.slice(PREFIX.length).split('/') - const version = parts[0] + if (chk !== 1) throw new Error('Invalid checksum for ' + str); + return { + prefix: prefix, + words: words + }; +} - if (version !== 'v1') { - throw new Error(`expect 'v1' version, got '${version}'`) - } +function convert(data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + var result = []; - const name = parts[1] + for (var i = 0; i < data.length; ++i) { + value = value << inBits | data[i]; + bits += inBits; - if (!parts[2]) { - throw new Error('missing param') + while (bits >= outBits) { + bits -= outBits; + result.push(value >> bits & maxV); + } } - const param = parseInt(parts[2], 10) - - switch (name) { - case 'prefix': - return new Prefix(param) - case 'suffix': - return new Suffix(param) - case 'next-to-last': - return new NextToLast(param) - default: - throw new Error(`unkown sharding function: ${name}`) + if (pad) { + if (bits > 0) { + result.push(value << outBits - bits & maxV); + } + } else { + if (bits >= inBits) throw new Error('Excess padding'); + if (value << outBits - bits & maxV) throw new Error('Non-zero padding'); } -} -exports.readShardFun = (path /* : string */, store /* : Datastore */, callback /* : Callback */) /* : void */ => { - const key = new Key(path).child(new Key(SHARDING_FN)) - const get = typeof store.getRaw === 'function' ? store.getRaw.bind(store) : store.get.bind(store) - - get(key, (err, res) => { - if (err) { - return callback(err) - } + return result; +} - let shard - try { - shard = parseShardFun((res || '').toString().trim()) - } catch (err) { - return callback(err) - } +function toWords(bytes) { + return convert(bytes, 8, 5, true); +} - callback(null, shard) - }) +function fromWords(words) { + return convert(words, 5, 8, false); } -exports.readme = readme -exports.parseShardFun = parseShardFun -exports.Prefix = Prefix -exports.Suffix = Suffix -exports.NextToLast = NextToLast +module.exports = { + decode: decode, + encode: encode, + toWords: toWords, + fromWords: fromWords +}; -},{"./shard-readme":175,"interface-datastore":405,"left-pad":638}],177:[function(require,module,exports){ -/* @flow */ -'use strict' +},{}],146:[function(require,module,exports){ +"use strict"; -const waterfall = require('async/waterfall') -const parallel = require('async/parallel') -const Key = require('interface-datastore').Key +var INTEGER_START = 0x69; // 'i' -const sh = require('./shard') -const KeytransformStore = require('./keytransform') +var STRING_DELIM = 0x3A; // ':' -const shardKey = new Key(sh.SHARDING_FN) -const shardReadmeKey = new Key(sh.README_FN) +var DICTIONARY_START = 0x64; // 'd' -/* :: -import type {Datastore, Batch, Query, QueryResult, Callback} from 'interface-datastore' +var LIST_START = 0x6C; // 'l' -import type {ShardV1} from './shard' -*/ +var END_OF_TYPE = 0x65; // 'e' /** - * Backend independent abstraction of go-ds-flatfs. + * replaces parseInt(buffer.toString('ascii', start, end)). + * For strings with less then ~30 charachters, this is actually a lot faster. * - * Wraps another datastore such that all values are stored - * sharded according to the given sharding function. + * @param {Buffer} data + * @param {Number} start + * @param {Number} end + * @return {Number} calculated number */ -class ShardingDatastore { - /* :: shard: ShardV1 */ - /* :: child: Datastore */ - constructor (store /* : Datastore */, shard /* : ShardV1 */) { - this.child = new KeytransformStore(store, { - convert: this._convertKey.bind(this), - invert: this._invertKey.bind(this) - }) - this.shard = shard - } +function getIntFromBuffer(buffer, start, end) { + var sum = 0; + var sign = 1; - open (callback /* : Callback */) /* : void */ { - this.child.open(callback) - } + for (var i = start; i < end; i++) { + var num = buffer[i]; - _convertKey (key/* : Key */)/* : Key */ { - const s = key.toString() - if (s === shardKey.toString() || s === shardReadmeKey.toString()) { - return key + if (num < 58 && num >= 48) { + sum = sum * 10 + (num - 48); + continue; } - const parent = new Key(this.shard.fun(s)) - return parent.child(key) - } + if (i === start && num === 43) { + // + + continue; + } - _invertKey (key/* : Key */)/* : Key */ { - const s = key.toString() - if (s === shardKey.toString() || s === shardReadmeKey.toString()) { - return key + if (i === start && num === 45) { + // - + sign = -1; + continue; + } + + if (num === 46) { + // . + // its a float. break here. + break; } - return Key.withNamespaces(key.list().slice(1)) + + throw new Error('not a number: buffer[' + i + '] = ' + num); } - static createOrOpen (store /* : Datastore */, shard /* : ShardV1 */, callback /* : Callback */) /* : void */ { - ShardingDatastore.create(store, shard, err => { - if (err && err.message !== 'datastore exists') { - return callback(err) - } + return sum * sign; +} +/** + * Decodes bencoded data. + * + * @param {Buffer} data + * @param {Number} start (optional) + * @param {Number} end (optional) + * @param {String} encoding (optional) + * @return {Object|Array|Buffer|String|Number} + */ - ShardingDatastore.open(store, callback) - }) + +function decode(data, start, end, encoding) { + if (data == null || data.length === 0) { + return null; } - static open (store /* : Datastore */, callback /* : Callback */) /* : void */ { - waterfall([ - (cb) => sh.readShardFun('/', store, cb), - (shard, cb) => { - cb(null, new ShardingDatastore(store, shard)) - } - ], callback) + if (typeof start !== 'number' && encoding == null) { + encoding = start; + start = undefined; } - static create (store /* : Datastore */, shard /* : ShardV1 */, callback /* : Callback */) /* : void */ { - store.has(shardKey, (err, exists) => { - if (err) { - return callback(err) - } + if (typeof end !== 'number' && encoding == null) { + encoding = end; + end = undefined; + } - if (!exists) { - const put = typeof store.putRaw === 'function' ? store.putRaw.bind(store) : store.put.bind(store) - return parallel([ - (cb) => put(shardKey, Buffer.from(shard.toString() + '\n'), cb), - (cb) => put(shardReadmeKey, Buffer.from(sh.readme), cb) - ], err => callback(err)) - } + decode.position = 0; + decode.encoding = encoding || null; + decode.data = !Buffer.isBuffer(data) ? new Buffer(data) : data.slice(start, end); + decode.bytes = decode.data.length; + return decode.next(); +} - sh.readShardFun('/', store, (err, diskShard) => { - if (err) { - return callback(err) - } +decode.bytes = 0; +decode.position = 0; +decode.data = null; +decode.encoding = null; - const a = (diskShard || '').toString() - const b = shard.toString() - if (a !== b) { - return callback(new Error(`specified fun ${b} does not match repo shard fun ${a}`)) - } +decode.next = function () { + switch (decode.data[decode.position]) { + case DICTIONARY_START: + return decode.dictionary(); - callback(new Error('datastore exists')) - }) - }) - } + case LIST_START: + return decode.list(); - put (key /* : Key */, val /* : Buffer */, callback /* : Callback */) /* : void */ { - this.child.put(key, val, callback) - } + case INTEGER_START: + return decode.integer(); - get (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.get(key, callback) + default: + return decode.buffer(); } +}; - has (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.has(key, callback) - } +decode.find = function (chr) { + var i = decode.position; + var c = decode.data.length; + var d = decode.data; - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.delete(key, callback) + while (i < c) { + if (d[i] === chr) return i; + i++; } - batch () /* : Batch */ { - return this.child.batch() - } + throw new Error('Invalid data: Missing delimiter "' + String.fromCharCode(chr) + '" [0x' + chr.toString(16) + ']'); +}; - query (q /* : Query */) /* : QueryResult */ { - const tq/* : Query */ = { - keysOnly: q.keysOnly, - offset: q.offset, - limit: q.limit, - filters: [ - (e, cb) => cb(null, e.key.toString() !== shardKey.toString()), - (e, cb) => cb(null, e.key.toString() !== shardReadmeKey.toString()) - ] - } +decode.dictionary = function () { + decode.position++; + var dict = {}; - if (q.prefix != null) { - tq.filters.push((e, cb) => { - cb(null, this._invertKey(e.key).toString().startsWith(q.prefix)) - }) - } + while (decode.data[decode.position] !== END_OF_TYPE) { + dict[decode.buffer()] = decode.next(); + } - if (q.filters != null) { - const filters = q.filters.map((f) => (e, cb) => { - f(Object.assign({}, e, { - key: this._invertKey(e.key) - }), cb) - }) - tq.filters = tq.filters.concat(filters) - } + decode.position++; + return dict; +}; - if (q.orders != null) { - tq.orders = q.orders.map((o) => (res, cb) => { - res.forEach((e) => { e.key = this._invertKey(e.key) }) - o(res, (err, ordered) => { - if (err) { - return cb(err) - } - ordered.forEach((e) => { e.key = this._convertKey(e.key) }) - cb(null, ordered) - }) - }) - } +decode.list = function () { + decode.position++; + var lst = []; - return this.child.query(tq) + while (decode.data[decode.position] !== END_OF_TYPE) { + lst.push(decode.next()); } - close (callback /* : Callback */) /* : void */ { - this.child.close(callback) - } -} + decode.position++; + return lst; +}; -module.exports = ShardingDatastore +decode.integer = function () { + var end = decode.find(END_OF_TYPE); + var number = getIntFromBuffer(decode.data, decode.position + 1, end); + decode.position += end + 1 - decode.position; + return number; +}; -},{"./keytransform":172,"./shard":176,"async/parallel":55,"async/waterfall":64,"interface-datastore":405}],178:[function(require,module,exports){ -/* @flow */ -'use strict' +decode.buffer = function () { + var sep = decode.find(STRING_DELIM); + var length = getIntFromBuffer(decode.data, decode.position, sep); + var end = ++sep + length; + decode.position = end; + return decode.encoding ? decode.data.toString(decode.encoding, sep, end) : decode.data.slice(sep, end); +}; -const each = require('async/each') -const whilst = require('async/whilst') +module.exports = decode; -/* :: -import type {Key, Datastore, Callback, Batch, Query, QueryResult} from 'interface-datastore' -*/ +},{}],147:[function(require,module,exports){ +"use strict"; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } +var Buffer = require('safe-buffer').Buffer; /** - * A datastore that can combine multiple stores. Puts and deletes - * will write through to all datastores. Has and get will - * try each store sequentially. Query will always try the - * last one first. + * Encodes data in bencode. * + * @param {Buffer|Array|String|Object|Number|Boolean} data + * @return {Buffer} */ -class TieredDatastore /* :: */ { - /* :: stores: Array> */ - constructor (stores /* : Array> */) { - this.stores = stores.slice() - } - open (callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.open(cb) - }, callback) - } +function encode(data, buffer, offset) { + var buffers = []; + var result = null; - put (key /* : Key */, value /* : Value */, callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.put(key, value, cb) - }, callback) - } + encode._encode(buffers, data); - get (key /* : Key */, callback /* : Callback */) /* : void */ { - const storeLength = this.stores.length - let done = false - let i = 0 - whilst(() => !done && i < storeLength, cb => { - const store = this.stores[i++] - store.get(key, (err, res) => { - if (err == null) { - done = true - return cb(null, res) - } - cb() - }) - }, callback) + result = Buffer.concat(buffers); + encode.bytes = result.length; + + if (Buffer.isBuffer(buffer)) { + result.copy(buffer, offset); + return buffer; } - has (key /* : Key */, callback /* : Callback */) /* : void */ { - const storeLength = this.stores.length - let done = false - let i = 0 - whilst(() => !done && i < storeLength, cb => { - const store = this.stores[i++] - store.has(key, (err, exists) => { - if (err == null) { - done = true - return cb(null, exists) - } - cb() - }) - }, callback) + return result; +} + +encode.bytes = -1; +encode._floatConversionDetected = false; + +encode._encode = function (buffers, data) { + if (Buffer.isBuffer(data)) { + buffers.push(Buffer.from(data.length + ':')); + buffers.push(data); + return; } - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.delete(key, cb) - }, callback) + if (data == null) { + return; } - close (callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.close(cb) - }, callback) + switch (_typeof(data)) { + case 'string': + encode.buffer(buffers, data); + break; + + case 'number': + encode.number(buffers, data); + break; + + case 'object': + data.constructor === Array ? encode.list(buffers, data) : encode.dict(buffers, data); + break; + + case 'boolean': + encode.number(buffers, data ? 1 : 0); + break; } +}; - batch () /* : Batch */ { - const batches = this.stores.map(store => store.batch()) +var buffE = Buffer.from('e'); +var buffD = Buffer.from('d'); +var buffL = Buffer.from('l'); - return { - put: (key /* : Key */, value /* : Value */) /* : void */ => { - batches.forEach(b => b.put(key, value)) - }, - delete: (key /* : Key */) /* : void */ => { - batches.forEach(b => b.delete(key)) - }, - commit: (callback /* : Callback */) /* : void */ => { - each(batches, (b, cb) => { - b.commit(cb) - }, callback) - } - } +encode.buffer = function (buffers, data) { + buffers.push(Buffer.from(Buffer.byteLength(data) + ':' + data)); +}; + +encode.number = function (buffers, data) { + var maxLo = 0x80000000; + var hi = data / maxLo << 0; + var lo = data % maxLo << 0; + var val = hi * maxLo + lo; + buffers.push(Buffer.from('i' + val + 'e')); + + if (val !== data && !encode._floatConversionDetected) { + encode._floatConversionDetected = true; + console.warn('WARNING: Possible data corruption detected with value "' + data + '":', 'Bencoding only defines support for integers, value was converted to "' + val + '"'); + console.trace(); } +}; + +encode.dict = function (buffers, data) { + buffers.push(buffD); + var j = 0; + var k; // fix for issue #13 - sorted dicts - query (q /* : Query */) /* : QueryResult */ { - return this.stores[this.stores.length - 1].query(q) + var keys = Object.keys(data).sort(); + var kl = keys.length; + + for (; j < kl; j++) { + k = keys[j]; + if (data[k] == null) continue; + encode.buffer(buffers, k); + + encode._encode(buffers, data[k]); } -} -module.exports = TieredDatastore + buffers.push(buffE); +}; -},{"async/each":24,"async/whilst":65}],179:[function(require,module,exports){ -/* @flow */ -'use strict' +encode.list = function (buffers, data) { + var i = 0; + var c = data.length; + buffers.push(buffL); -/* :: import type {Batch, Query, QueryResult, Callback} from 'interface-datastore' */ + for (; i < c; i++) { + if (data[i] == null) continue; -const fs = require('graceful-fs') -const pull = require('pull-stream') -const glob = require('glob') -const setImmediate = require('async/setImmediate') -const waterfall = require('async/series') -const each = require('async/each') -const mkdirp = require('mkdirp') -const writeFile = require('write-file-atomic') -const path = require('path') + encode._encode(buffers, data[i]); + } -const asyncFilter = require('interface-datastore').utils.asyncFilter -const asyncSort = require('interface-datastore').utils.asyncSort -const Key = require('interface-datastore').Key + buffers.push(buffE); +}; -/* :: export type FsInputOptions = { - createIfMissing?: bool, - errorIfExists?: bool, - extension?: string -} +module.exports = encode; -type FsOptions = { - createIfMissing: bool, - errorIfExists: bool, - extension: string -} -*/ +},{"safe-buffer":2812}],148:[function(require,module,exports){ +"use strict"; +var bencode = module.exports; +bencode.encode = require('./encode'); +bencode.decode = require('./decode'); /** - * A datastore backed by the file system. - * - * Keys need to be sanitized before use, as they are written - * to the file system as is. + * Determines the amount of bytes + * needed to encode the given value + * @param {Object|Array|Buffer|String|Number|Boolean} value + * @return {Number} byteCount */ -class FsDatastore { - /* :: path: string */ - /* :: opts: FsOptions */ - constructor (location /* : string */, opts /* : ?FsInputOptions */) { - this.path = path.resolve(location) - this.opts = Object.assign({}, { - createIfMissing: true, - errorIfExists: false, - extension: '.data' - }, opts) +bencode.byteLength = bencode.encodingLength = function (value) { + return bencode.encode(value).length; +}; - if (this.opts.createIfMissing) { - this._openOrCreate() - } else { - this._open() - } - } +},{"./decode":146,"./encode":147}],149:[function(require,module,exports){ +"use strict"; - open (callback /* : Callback */) /* : void */ { - this._openOrCreate() - setImmediate(callback) - } +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - /** - * Check if the path actually exists. - * @private - * @returns {void} +; + +(function (globalObject) { + 'use strict'; + /* + * bignumber.js v9.0.0 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2019 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * */ - _open () { - if (!fs.existsSync(this.path)) { - throw new Error(`Datastore directory: ${this.path} does not exist`) - } - if (this.opts.errorIfExists) { - throw new Error(`Datastore directory: ${this.path} already exists`) - } - } + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, + // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 - /** - * Create the directory to hold our data. - * - * @private - * @returns {void} + /* + * Create and return a BigNumber constructor. */ - _create () { - mkdirp.sync(this.path, { fs: fs }) - } - /** - * Tries to open, and creates if the open fails. - * - * @private - * @returns {void} - */ - _openOrCreate () { - try { - this._open() - } catch (err) { - if (err.message.match('does not exist')) { - this._create() - return - } + function clone(configObject) { + var div, + convertBase, + parseNumeric, + P = BigNumber.prototype = { + constructor: BigNumber, + toString: null, + valueOf: null + }, + ONE = new BigNumber(1), + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, + // 0 to MAX + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, + // 0 to 8 + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, + // 0 to -MAX + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, + // 0 to MAX + // RANGE : [MIN_EXP, MAX_EXP] + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, + // -1 to -MAX + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, + // 1 to MAX + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, + // true or false + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, + // 0 to 9 + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, + // 0 to MAX + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', + // non-breaking space + suffix: '' + }, + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; //------------------------------------------------------------------------------------------ + // CONSTRUCTOR - throw err - } - } + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ - /** - * Calculate the directory and file name for a given key. - * - * @private - * @param {Key} key - * @returns {{string, string}} - */ - _encode (key /* : Key */) /* : {dir: string, file: string} */ { - const parent = key.parent().toString() - const dir = path.join(this.path, parent) - const name = key.toString().slice(parent.length) - const file = path.join(dir, name + this.opts.extension) + function BigNumber(v, b) { + var alphabet, + c, + caseChanged, + e, + i, + isNum, + len, + str, + x = this; // Enable constructor call without `new`. + + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } - return { - dir: dir, - file: file - } - } + return; + } - /** - * Calculate the original key, given the file name. - * - * @private - * @param {string} file - * @returns {Key} - */ - _decode (file /* : string */) /* : Key */ { - const ext = this.opts.extension - if (path.extname(file) !== ext) { - throw new Error(`Invalid extension: ${path.extname(file)}`) - } + if ((isNum = typeof v == 'number') && v * 0 == 0) { + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; // Fast path for integers, where n < 2147483648 (2**31). - const keyname = file - .slice(this.path.length, -ext.length) - .split(path.sep) - .join('/') - return new Key(keyname) - } + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++) { + ; + } - /** - * Write to the file system without extension. - * - * @param {Key} key - * @param {Buffer} val - * @param {function(Error)} callback - * @returns {void} - */ - putRaw (key /* : Key */, val /* : Buffer */, callback /* : Callback */) /* : void */ { - const parts = this._encode(key) - const file = parts.file.slice(0, -this.opts.extension.length) - waterfall([ - (cb) => mkdirp(parts.dir, { fs: fs }, cb), - (cb) => writeFile(file, val, cb) - ], (err) => callback(err)) - } + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } - /** - * Store the given value under the key. - * - * @param {Key} key - * @param {Buffer} val - * @param {function(Error)} callback - * @returns {void} - */ - put (key /* : Key */, val /* : Buffer */, callback /* : Callback */) /* : void */ { - const parts = this._encode(key) - waterfall([ - (cb) => mkdirp(parts.dir, { fs: fs }, cb), - (cb) => writeFile(parts.file, val, cb) - ], (err) => callback(err)) - } + return; + } - /** - * Read from the file system without extension. - * - * @param {Key} key - * @param {function(Error, Buffer)} callback - * @returns {void} - */ - getRaw (key /* : Key */, callback /* : Callback */) /* : void */ { - const parts = this._encode(key) - let file = parts.file - file = file.slice(0, -this.opts.extension.length) - fs.readFile(file, callback) - } + str = String(v); + } else { + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } // Decimal point? - /** - * Read from the file system. - * - * @param {Key} key - * @param {function(Error, Buffer)} callback - * @returns {void} - */ - get (key /* : Key */, callback /* : Callback */) /* : void */ { - const parts = this._encode(key) - fs.readFile(parts.file, callback) - } - /** - * Check for the existence of the given key. - * - * @param {Key} key - * @param {function(Error, bool)} callback - * @returns {void} - */ - has (key /* : Key */, callback /* : Callback */) /* : void */ { - const parts = this._encode(key) - fs.access(parts.file, err => { - callback(null, !err) - }) - } + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); // Exponential form? - /** - * Delete the record under the given key. - * - * @param {Key} key - * @param {function(Error)} callback - * @returns {void} - */ - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - const parts = this._encode(key) - fs.unlink(parts.file, (err) => { - // Avoid injection of additional params, we only need the error - callback(err) - }) - } + if ((i = str.search(/e/i)) > 0) { + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + // Integer. + e = str.length; + } + } else { + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. - /** - * Create a new batch object. - * - * @returns {Batch} - */ - batch () /* : Batch */ { - const puts = [] - const deletes = [] - return { - put (key /* : Key */, value /* : Buffer */) /* : void */ { - puts.push({ key: key, value: value }) - }, - delete (key /* : Key */) /* : void */ { - deletes.push(key) - }, - commit: (callback /* : (err: ?Error) => void */) => { - waterfall([ - (cb) => each(puts, (p, cb) => { - this.put(p.key, p.value, cb) - }, cb), - (cb) => each(deletes, (k, cb) => { - this.delete(k, cb) - }, cb) - ], (err) => callback(err)) - } - } - } + if (b == 10) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } - /** - * Query the store. - * - * @param {Object} q - * @returns {PullStream} - */ - query (q /* : Query */) /* : QueryResult */ { - // glob expects a POSIX path - let prefix = q.prefix || '**' - let pattern = path - .join(this.path, prefix, '*' + this.opts.extension) - .split(path.sep) - .join('/') - let tasks = [pull.values(glob.sync(pattern))] + str = String(v); - if (!q.keysOnly) { - tasks.push(pull.asyncMap((f, cb) => { - fs.readFile(f, (err, buf) => { - if (err) { - return cb(err) + if (isNum = typeof v == 'number') { + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error(tooManyDigits + v); } - cb(null, { - key: this._decode(f), - value: buf - }) - }) - })) - } else { - tasks.push(pull.map(f => ({ key: this._decode(f) }))) - } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } - if (q.filters != null) { - tasks = tasks.concat(q.filters.map(asyncFilter)) - } + alphabet = ALPHABET.slice(0, b); + e = i = 0; // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. - if (q.orders != null) { - tasks = tasks.concat(q.orders.map(asyncSort)) - } + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } - if (q.offset != null) { - let i = 0 - tasks.push(pull.filter(() => i++ >= q.offset)) - } + return parseNumeric(x, String(v), isNum, b); + } + } // Prevent later check for length on converted number. - if (q.limit != null) { - tasks.push(pull.take(q.limit)) - } - return pull.apply(null, tasks) - } + isNum = false; + str = convertBase(str, b, 10, x.s); // Decimal point? - /** - * Close the store. - * - * @param {function(Error)} callback - * @returns {void} - */ - close (callback /* : (err: ?Error) => void */) /* : void */ { - setImmediate(callback) - } -} + if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');else e = str.length; + } // Determine leading zeros. -module.exports = FsDatastore -},{"async/each":24,"async/series":58,"async/setImmediate":59,"glob":347,"graceful-fs":350,"interface-datastore":405,"mkdirp":958,"path":undefined,"pull-stream":1175,"write-file-atomic":1338}],180:[function(require,module,exports){ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + for (i = 0; str.charCodeAt(i) === 48; i++) { + ; + } // Determine trailing zeros. -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); -/** - * Colors. - */ + for (len = str.length; str.charCodeAt(--len) === 48;) { + ; + } -exports.colors = [ - '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', - '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', - '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', - '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', - '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', - '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', - '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', - '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', - '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', - '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', - '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; + if (str = str.slice(i, ++len)) { + len -= i; // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + if (isNum && BigNumber.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error(tooManyDigits + x.s * v); + } // Overflow? -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + if ((e = e - i - 1) > MAX_EXP) { + // Infinity. + x.c = x.e = null; // Underflow? + } else if (e < MIN_EXP) { + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; // Transform base + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } -/** - * Colorize log arguments if enabled. - * - * @api public - */ + for (; i--; str += '0') { + ; + } -function formatArgs(args) { - var useColors = this.useColors; + x.c.push(+str); + } + } else { + // Zero. + x.c = [x.e = 0]; + } + } // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + if (_typeof(obj) == 'object') { + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + + + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + + + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' - if (!useColors) return; - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); - args.splice(lastC, 0, c); -} + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error(bignumberError + p + ' cannot be zero: ' + v); + } + } + } // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error(bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error(bignumberError + p + ' not true or false: ' + v); + } + } // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' - return r; -} -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (_typeof(v) == 'object') FORMAT = v;else throw Error(bignumberError + p + ' not an object: ' + v); + } // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' -exports.enable(load()); -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; // Disallow if only one character, + // or if it contains '+', '-', '.', whitespace, or a repeated character. -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} + if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) { + ALPHABET = v; + } else { + throw Error(bignumberError + p + ' invalid: ' + v); + } + } + } else { + // '[BigNumber Error] Object expected: {v}' + throw Error(bignumberError + 'Object expected: ' + obj); + } + } -},{"./debug":181}],181:[function(require,module,exports){ + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + var i, + n, + c = v.c, + e = v.e, + s = v.s; -/** - * Active `debug` instances. - */ -exports.instances = []; + out: if ({}.toString.call(c) == '[object Array]') { + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } // Calculate number of digits that c[0] should have, based on the exponent. -/** - * The currently active debug mode names, and names to skip. - */ -exports.names = []; -exports.skips = []; + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ + if (String(c[0]).length == i) { + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } // Last element cannot be zero, unless it is the only element. -exports.formatters = {}; -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + if (n !== 0) return true; + } + } // Infinity/NaN -function selectColor(namespace) { - var hash = 0, i; + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + throw Error(bignumberError + 'Invalid BigNumber: ' + v); + }; + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ -function createDebug(namespace) { + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, P.lt); + }; + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ - var prevTime; - function debug() { - // disabled? - if (!debug.enabled) return; + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, P.gt); + }; + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ - var self = debug; - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + BigNumber.random = function () { + var pow2_53 = 0x20000000000000; // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } + var random53bitInt = Math.random() * pow2_53 & 0x1fffff ? function () { + return mathfloor(Math.random() * pow2_53); + } : function () { + return (Math.random() * 0x40000000 | 0) * 0x800000 + (Math.random() * 0x800000 | 0); + }; + return function (dp) { + var a, + b, + e, + k, + v, + i = 0, + c = [], + rand = new BigNumber(ONE); + if (dp == null) dp = DECIMAL_PLACES;else intCheck(dp, 0, MAX); + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } - args[0] = exports.coerce(args[0]); + i = k / 2; // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + // buffer + a = crypto.randomBytes(k *= 7); - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } + for (; i < k;) { + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = (a[i] & 31) * 0x1000000000000 + a[i + 1] * 0x10000000000 + a[i + 2] * 0x100000000 + a[i + 3] * 0x1000000 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + i = k / 7; + } else { + CRYPTO = false; + throw Error(bignumberError + 'crypto unavailable'); + } + } // Use Math.random. - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + if (!CRYPTO) { + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; + k = c[--i]; + dp %= LOG_BASE; // Convert trailing digits to zeros according to dp. - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } // Remove trailing elements which are zero. - exports.instances.push(debug); - return debug; -} + for (; c[i] === 0; c.pop(), i--) { + ; + } // Zero? -function destroy () { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } -} -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + if (i < 0) { + c = [e = 0]; + } else { + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1; c[0] === 0; c.splice(0, 1), e -= LOG_BASE) { + ; + } // Count the digits of the first element of c to determine leading zeros, and... -function enable(namespaces) { - exports.save(namespaces); - exports.names = []; - exports.skips = []; + for (i = 1, v = c[0]; v >= 10; v /= 10, i++) { + ; + } // adjust the exponent accordingly. - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } + if (i < LOG_BASE) e -= LOG_BASE - i; + } - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } -} + rand.e = e; + rand.c = c; + return rand; + }; + }(); + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ -/** - * Disable debug output. - * - * @api public - */ -function disable() { - exports.enable(''); -} + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + for (; i < args.length;) { + sum = sum.plus(args[i++]); + } -function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} + return sum; + }; // PRIVATE FUNCTIONS + // Called by BigNumber and BigNumber.prototype.toString. -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} + convertBase = function () { + var decimal = '0123456789'; + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ -},{"ms":966}],182:[function(require,module,exports){ -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; -if (typeof process === 'undefined' || process.type === 'renderer') { - module.exports = require('./browser.js'); -} else { - module.exports = require('./node.js'); -} + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) { + ; + } -},{"./browser.js":180,"./node.js":183}],183:[function(require,module,exports){ -/** - * Module dependencies. - */ + arr[0] += alphabet.indexOf(str.charAt(i++)); -var tty = require('tty'); -var util = require('util'); + for (j = 0; j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + return arr.reverse(); + } // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. -exports = module.exports = require('./debug'); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -/** - * Colors. - */ + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, + d, + e, + k, + r, + x, + xc, + y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; // Non-integer. -exports.colors = [ 6, 2, 3, 4, 5, 1 ]; + if (i >= 0) { + k = POW_PRECISION; // Unlimited precision. -try { - var supportsColor = require('supports-color'); - if (supportsColor && supportsColor.level >= 2) { - exports.colors = [ - 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, - 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, - 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, - 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, - 205, 206, 207, 208, 209, 214, 215, 220, 221 - ]; - } -} catch (err) { - // swallow - we only care if `supports-color` is available; it doesn't have to be. -} + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), 10, baseOut, decimal); + y.e = y.c.length; + } // Convert the number as integer. -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); // xc now represents str as an integer and converted to baseOut. e is the exponent. - obj[prop] = val; - return obj; -}, {}); + e = k = xc.length; // Remove trailing zeros. -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + for (; xc[--k] == 0; xc.pop()) { + ; + } // Zero? -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(process.stderr.fd); -} -/** - * Map %o to `util.inspect()`, all on a single line. - */ + if (!xc[0]) return alphabet.charAt(0); // Does str represent an integer? If so, no need for the division. -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; // The sign is needed for correct rounding. -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } // xc now represents str converted to baseOut. + // THe index of the rounding digit. -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + d = e + dp + 1; // The rounding digit: the digit to the right of the digit that may be rounded up. -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + i = xc[d]; // Look at the rounding digits and mode to determine whether to round up. - if (useColors) { - var c = this.color; - var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); - var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + if (d < 1 || !xc[0]) { + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + // Truncate xc to the required number of decimal places. + xc.length = d; // Round up? -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } else { - return new Date().toISOString() + ' '; - } -} + if (r) { + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } // Determine trailing zeros. -function log() { - return process.stderr.write(util.format.apply(util, arguments) + '\n'); -} -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + for (k = xc.length; !xc[--k];) { + ; + } // E.g. [4, 11, 15] becomes 4bf. -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])) { + ; + } // Add leading zeros, decimal point and trailing zeros as required. -function load() { - return process.env.DEBUG; -} -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + str = toFixedPoint(str, e, alphabet.charAt(0)); + } // The caller will add the sign. -function init (debug) { - debug.inspectOpts = {}; - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + return str; + }; + }(); // Perform division in the specified base. Called by div and convertBase. -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ -exports.enable(load()); + div = function () { + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, + temp, + xlo, + xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; -},{"./debug":181,"supports-color":1306,"tty":undefined,"util":undefined}],184:[function(require,module,exports){ -/*! - * @description Recursive object extending - * @author Viacheslav Lotsmanov - * @license MIT - * - * The MIT License (MIT) - * - * Copyright (c) 2013-2018 Viacheslav Lotsmanov - * - * 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. - */ + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } -'use strict'; + if (carry) x = [carry].concat(x); + return x; + } -function isSpecificValue(val) { - return ( - val instanceof Buffer - || val instanceof Date - || val instanceof RegExp - ) ? true : false; -} + function compare(a, b, aL, bL) { + var i, cmp; -function cloneSpecificValue(val) { - if (val instanceof Buffer) { - var x = Buffer.alloc - ? Buffer.alloc(val.length) - : new Buffer(val.length); - val.copy(x); - return x; - } else if (val instanceof Date) { - return new Date(val.getTime()); - } else if (val instanceof RegExp) { - return new RegExp(val); - } else { - throw new Error('Unexpected situation'); - } -} + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i = cmp = 0; i < aL; i++) { + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } -/** - * Recursive cloning array. - */ -function deepCloneArray(arr) { - var clone = []; - arr.forEach(function (item, index) { - if (typeof item === 'object' && item !== null) { - if (Array.isArray(item)) { - clone[index] = deepCloneArray(item); - } else if (isSpecificValue(item)) { - clone[index] = cloneSpecificValue(item); - } else { - clone[index] = deepExtend({}, item); - } - } else { - clone[index] = item; - } - }); - return clone; -} + return cmp; + } -function safeGetProperty(object, property) { - return property === '__proto__' ? undefined : object[property]; -} + function subtract(a, b, aL, base) { + var i = 0; // Subtract b from a. -/** - * Extening object that entered in first argument. - * - * Returns extended object or false if have no target object or incorrect type. - * - * If you wish to clone source object (without modify it), just use empty new - * object as first argument, like this: - * deepExtend({}, yourObj_1, [yourObj_N]); - */ -var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { - if (arguments.length < 1 || typeof arguments[0] !== 'object') { - return false; - } + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } // Remove leading zeros. - if (arguments.length < 2) { - return arguments[0]; - } - var target = arguments[0]; + for (; !a[0] && a.length > 1; a.splice(0, 1)) { + ; + } + } // x: dividend, y: divisor. - // convert arguments to array and cut off target object - var args = Array.prototype.slice.call(arguments, 1); - var val, src, clone; + return function (x, y, dp, rm, base) { + var cmp, + e, + i, + more, + n, + prod, + prodL, + q, + qc, + rem, + remL, + rem0, + xi, + xL, + yc0, + yL, + yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; // Either NaN, Infinity or 0? - args.forEach(function (obj) { - // skip argument if isn't an object, is null, or is an array - if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { - return; - } + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber( // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0); + } - Object.keys(obj).forEach(function (key) { - src = safeGetProperty(target, key); // source value - val = safeGetProperty(obj, key); // new value + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; - // recursion prevention - if (val === target) { - return; + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. - /** - * if new value isn't object then just overwrite by new value - * instead of extending. - */ - } else if (typeof val !== 'object' || val === null) { - target[key] = val; - return; - // just clone arrays (and recursive clone objects inside) - } else if (Array.isArray(val)) { - target[key] = deepCloneArray(val); - return; + for (i = 0; yc[i] == (xc[i] || 0); i++) { + ; + } - // custom cloning and overwrite for specific objects - } else if (isSpecificValue(val)) { - target[key] = cloneSpecificValue(val); - return; + if (yc[i] > (xc[i] || 0)) e--; - // overwrite by new value if source isn't object or array - } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { - target[key] = deepExtend({}, val); - return; + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } - // source value and new value is objects both, extending... - } else { - target[key] = deepExtend(src, val); - return; - } - }); - }); + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; // Add zeros to make remainder as long as divisor. - return target; -}; + for (; remL < yL; rem[remL++] = 0) { + ; + } -},{}],185:[function(require,module,exports){ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.deepmerge = factory()); -}(this, (function () { 'use strict'; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; // Compare divisor and remainder. + + cmp = compare(yc, rem, yL, remL); // If divisor < remainder. + + if (cmp < 0) { + // Calculate trial digit, n. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); // n is how many times the divisor goes into the current remainder. + + n = mathfloor(rem0 / yc0); // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + // n may be > base only when base is 3. + if (n >= base) n = base - 1; // product = divisor * trial digit. + + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + + while (compare(prod, rem, prodL, remL) == 1) { + n--; // Subtract divisor from product. + + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } // product = divisor + + + prod = yc.slice(); + prodL = prod.length; + } -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; + if (prodL < remL) prod = [0].concat(prod); // Subtract product from remainder. -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} + subtract(rem, prod, remL, base); + remL = rem.length; // If product was < remainder. -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); + if (cmp == -1) { + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; // Subtract divisor from remainder. - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) -} + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + // Add the next digit, n, to the result array. -// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 -var canUseSymbol = typeof Symbol === 'function' && Symbol.for; -var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} + qc[i++] = n; // Update the remainder. -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); -function cloneIfNecessary(value, optionsArgument) { - var clone = optionsArgument && optionsArgument.clone === true; - return (clone && isMergeableObject(value)) ? deepmerge(emptyTarget(value), value, optionsArgument) : value -} + more = rem[0] != null; // Leading zero? -function defaultArrayMerge(target, source, optionsArgument) { - var destination = target.slice(); - source.forEach(function(e, i) { - if (typeof destination[i] === 'undefined') { - destination[i] = cloneIfNecessary(e, optionsArgument); - } else if (isMergeableObject(e)) { - destination[i] = deepmerge(target[i], e, optionsArgument); - } else if (target.indexOf(e) === -1) { - destination.push(cloneIfNecessary(e, optionsArgument)); + if (!qc[0]) qc.splice(0, 1); } - }); - return destination -} -function mergeObject(target, source, optionsArgument) { - var destination = {}; - if (isMergeableObject(target)) { - Object.keys(target).forEach(function(key) { - destination[key] = cloneIfNecessary(target[key], optionsArgument); - }); - } - Object.keys(source).forEach(function(key) { - if (!isMergeableObject(source[key]) || !target[key]) { - destination[key] = cloneIfNecessary(source[key], optionsArgument); + if (base == BASE) { + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++) { + ; + } + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); // Caller is convertBase. } else { - destination[key] = deepmerge(target[key], source[key], optionsArgument); + q.e = e; + q.r = +more; } - }); - return destination -} -function deepmerge(target, source, optionsArgument) { - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var options = optionsArgument || { arrayMerge: defaultArrayMerge }; - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + return q; + }; + }(); + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ - if (!sourceAndTargetTypesMatch) { - return cloneIfNecessary(source, optionsArgument) - } else if (sourceIsArray) { - var arrayMerge = options.arrayMerge || defaultArrayMerge; - return arrayMerge(target, source, optionsArgument) - } else { - return mergeObject(target, source, optionsArgument) - } -} -deepmerge.all = function deepmergeAll(array, optionsArgument) { - if (!Array.isArray(array) || array.length < 2) { - throw new Error('first argument should be an array with at least two elements') - } + function format(n, i, rm, id) { + var c0, e, ne, len, str; + if (rm == null) rm = ROUNDING_MODE;else intCheck(rm, 0, 8); + if (!n.c) return n.toString(); + c0 = n.c[0]; + ne = n.e; - // we are sure there are at least 2 values, so it is safe to have no initial value - return array.reduce(function(prev, next) { - return deepmerge(prev, next, optionsArgument) - }) -}; + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); // n.e may have changed if the value was rounded up. + + e = n.e; + str = coeffToString(n.c); + len = str.length; // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + // Exponential notation. + + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + // Append zeros? + for (; len < i; str += '0', len++) { + ; + } -var deepmerge_1 = deepmerge; + str = toExponential(str, e); // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); // Append zeros? -return deepmerge_1; + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0') { + ; + } + } else { + i += e - len; -}))); + if (i > 0) { + if (e + 1 == len) str += '.'; -},{}],186:[function(require,module,exports){ -var util = require('util') -var AbstractIterator = require('abstract-leveldown').AbstractIterator + for (; i--; str += '0') { + ; + } + } + } + } + } -function DeferredIterator (options) { - AbstractIterator.call(this, options) + return n.s < 0 && c0 ? '-' + str : str; + } // Handle BigNumber.max and BigNumber.min. - this._options = options - this._iterator = null - this._operations = [] -} -util.inherits(DeferredIterator, AbstractIterator) + function maxOrMin(args, method) { + var n, + i = 1, + m = new BigNumber(args[0]); -DeferredIterator.prototype.setDb = function (db) { - var it = this._iterator = db.iterator(this._options) - this._operations.forEach(function (op) { - it[op.method].apply(it, op.args) - }) -} + for (; i < args.length; i++) { + n = new BigNumber(args[i]); // If any number is NaN, return NaN. -DeferredIterator.prototype._operation = function (method, args) { - if (this._iterator) return this._iterator[method].apply(this._iterator, args) - this._operations.push({ method: method, args: args }) -} + if (!n.s) { + m = n; + break; + } else if (method.call(m, n)) { + m = n; + } + } -'next end'.split(' ').forEach(function (m) { - DeferredIterator.prototype['_' + m] = function () { - this._operation(m, arguments) - } -}) + return m; + } + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ -module.exports = DeferredIterator -},{"abstract-leveldown":191,"util":undefined}],187:[function(require,module,exports){ -var util = require('util') -var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN -var DeferredIterator = require('./deferred-iterator') -var deferrables = 'put get del batch'.split(' ') + function normalise(n, c, e) { + var i = 1, + j = c.length; // Remove trailing zeros. -function DeferredLevelDOWN (db) { - AbstractLevelDOWN.call(this, '') - this._db = db - this._operations = [] - this._iterators = [] - closed(this) -} + for (; !c[--j]; c.pop()) { + ; + } // Calculate the base 10 exponent. First get the number of digits of c[0]. -util.inherits(DeferredLevelDOWN, AbstractLevelDOWN) -DeferredLevelDOWN.prototype._open = function (options, callback) { - var self = this + for (j = c[0]; j >= 10; j /= 10, i++) { + ; + } // Overflow? - this._db.open(options, function (err) { - if (err) return callback(err) - self._operations.forEach(function (op) { - self._db[op.method].apply(self._db, op.args) - }) - self._operations = [] - self._iterators.forEach(function (it) { - it.setDb(self._db) - }) - self._iterators = [] - open(self) - callback() - }) -} + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + // Infinity. + n.c = n.e = null; // Underflow? + } else if (e < MIN_EXP) { + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } -DeferredLevelDOWN.prototype._close = function (callback) { - var self = this + return n; + } // Handle values that fail the validity test in BigNumber. - this._db.close(function (err) { - if (err) return callback(err) - closed(self) - callback() - }) -} -function open (self) { - deferrables.concat('iterator').forEach(function (m) { - self['_' + m] = function () { - return this._db[m].apply(this._db, arguments) - } - }) - if (self._db.approximateSize) { - self.approximateSize = function () { - return this._db.approximateSize.apply(this._db, arguments) - } - } -} + parseNumeric = function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); // No exception on ±Infinity or NaN. -function closed (self) { - deferrables.forEach(function (m) { - self['_' + m] = function () { - this._operations.push({ method: m, args: arguments }) - } - }) - if (typeof self._db.approximateSize === 'function') { - self.approximateSize = function () { - this._operations.push({ - method: 'approximateSize', - args: arguments - }) - } - } - self._iterator = function (options) { - var it = new DeferredIterator(options) - this._iterators.push(it) - return it - } -} + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); -DeferredLevelDOWN.prototype._serializeKey = function (key) { - return key -} + if (b) { + base = b; // E.g. '1.' to '1', '.1' to '0.1' -DeferredLevelDOWN.prototype._serializeValue = function (value) { - return value -} + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } -module.exports = DeferredLevelDOWN -module.exports.DeferredIterator = DeferredIterator + if (str != s) return new BigNumber(s, base); + } // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' -},{"./deferred-iterator":186,"abstract-leveldown":191,"util":undefined}],188:[function(require,module,exports){ -/* Copyright (c) 2017 Rod Vagg, MIT License */ -function AbstractChainedBatch (db) { - this._db = db - this._operations = [] - this._written = false -} + if (BigNumber.DEBUG) { + throw Error(bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } // NaN -AbstractChainedBatch.prototype._serializeKey = function (key) { - return this._db._serializeKey(key) -} -AbstractChainedBatch.prototype._serializeValue = function (value) { - return this._db._serializeValue(value) -} + x.s = null; + } -AbstractChainedBatch.prototype._checkWritten = function () { - if (this._written) { - throw new Error('write() already called on this batch') - } -} + x.c = x.e = null; + }; + }(); + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ -AbstractChainedBatch.prototype.put = function (key, value) { - this._checkWritten() - var err = this._db._checkKey(key, 'key') - if (err) { throw err } + function round(x, sd, rm, r) { + var d, + i, + j, + k, + n, + ni, + rd, + xc = x.c, + pows10 = POWS_TEN; // if x is not Infinity or NaN... + + if (xc) { + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++) { + ; + } - key = this._serializeKey(key) - value = this._serializeValue(value) + i = sd - d; // If the rounding digit is in the first element of xc... - this._put(key, value) + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; // Get the rounding digit at index j of n. - return this -} + rd = n / pows10[d - j - 1] % 10 | 0; + } else { + ni = mathceil((i + 1) / LOG_BASE); -AbstractChainedBatch.prototype._put = function (key, value) { - this._operations.push({ type: 'put', key: key, value: value }) -} + if (ni >= xc.length) { + if (r) { + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)) { + ; + } -AbstractChainedBatch.prototype.del = function (key) { - this._checkWritten() + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; // Get the number of digits of n. - var err = this._db._checkKey(key, 'key') - if (err) { throw err } + for (d = 1; k >= 10; k /= 10, d++) { + ; + } // Get the index of rd within n. - key = this._serializeKey(key) - this._del(key) - return this -} + i %= LOG_BASE; // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. -AbstractChainedBatch.prototype._del = function (key) { - this._operations.push({ type: 'del', key: key }) -} + j = i - LOG_BASE + d; // Get the rounding digit at index j of n. -AbstractChainedBatch.prototype.clear = function () { - this._checkWritten() - this._operations = [] - this._clear() + rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; + } + } - return this -} + r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7)); -AbstractChainedBatch.prototype._clear = function noop () {} + if (sd < 1 || !xc[0]) { + xc.length = 0; -AbstractChainedBatch.prototype.write = function (options, callback) { - this._checkWritten() + if (r) { + // Convert sd to decimal places. + sd -= x.e + 1; // 1, 0.1, 0.01, 0.001, 0.0001 etc. - if (typeof options === 'function') { callback = options } - if (typeof callback !== 'function') { - throw new Error('write() requires a callback argument') - } - if (typeof options !== 'object') { options = {} } + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + // Zero. + xc[0] = x.e = 0; + } - this._written = true + return x; + } // Remove excess digits. - // @ts-ignore - if (typeof this._write === 'function') { return this._write(callback) } - if (typeof this._db._batch === 'function') { - return this._db._batch(this._operations, options, callback) - } + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. - process.nextTick(callback) -} + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } // Round up? -module.exports = AbstractChainedBatch -},{}],189:[function(require,module,exports){ -/* Copyright (c) 2017 Rod Vagg, MIT License */ + if (r) { + for (;;) { + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++) { + ; + } -function AbstractIterator (db) { - this.db = db - this._ended = false - this._nexting = false -} + j = xc[0] += k; -AbstractIterator.prototype.next = function (callback) { - var self = this + for (k = 1; j >= 10; j /= 10, k++) { + ; + } // if i != k the length has increased. - if (typeof callback !== 'function') { - throw new Error('next() requires a callback argument') - } - if (self._ended) { - process.nextTick(callback, new Error('cannot call next() after end()')) - return self - } + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } - if (self._nexting) { - process.nextTick(callback, new Error('cannot call next() before previous next() has completed')) - return self - } + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } // Remove trailing zeros. - self._nexting = true - self._next(function () { - self._nexting = false - callback.apply(null, arguments) - }) - return self -} + for (i = xc.length; xc[--i] === 0; xc.pop()) { + ; + } + } // Overflow? Infinity. -AbstractIterator.prototype._next = function (callback) { - process.nextTick(callback) -} -AbstractIterator.prototype.end = function (callback) { - if (typeof callback !== 'function') { - throw new Error('end() requires a callback argument') - } + if (x.e > MAX_EXP) { + x.c = x.e = null; // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } - if (this._ended) { - return process.nextTick(callback, new Error('end() already called on iterator')) - } + return x; + } - this._ended = true - this._end(callback) -} + function valueOf(n) { + var str, + e = n.e; + if (e === null) return n.toString(); + str = coeffToString(n.c); + str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, '0'); + return n.s < 0 ? '-' + str : str; + } // PROTOTYPE/INSTANCE METHODS -AbstractIterator.prototype._end = function (callback) { - process.nextTick(callback) -} + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ -module.exports = AbstractIterator -},{}],190:[function(require,module,exports){ -/* Copyright (c) 2017 Rod Vagg, MIT License */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ -const xtend = require('xtend') -const AbstractIterator = require('./abstract-iterator') -const AbstractChainedBatch = require('./abstract-chained-batch') -const hasOwnProperty = Object.prototype.hasOwnProperty -const rangeOptions = 'start end gt gte lt lte'.split(' ') -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) { - throw new Error('constructor requires at least a location argument') - } + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ - if (typeof location !== 'string') { - throw new Error('constructor requires a location string argument') - } - this.location = location - this.status = 'new' -} + P.decimalPlaces = P.dp = function (dp, rm) { + var c, + n, + v, + x = this; -AbstractLevelDOWN.prototype.open = function (options, callback) { - var self = this - var oldStatus = this.status + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE;else intCheck(rm, 0, 8); + return round(new BigNumber(x), dp + x.e + 1, rm); + } - if (typeof options === 'function') { callback = options } + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; // Subtract the number of trailing zeros of the last number. - if (typeof callback !== 'function') { - throw new Error('open() requires a callback argument') - } + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--) { + ; + } + if (n < 0) n = 0; + return n; + }; + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ - if (typeof options !== 'object') { options = {} } - options.createIfMissing = options.createIfMissing !== false - options.errorIfExists = !!options.errorIfExists + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ - this.status = 'opening' - this._open(options, function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'open' - callback() - }) -} -AbstractLevelDOWN.prototype._open = function (options, callback) { - process.nextTick(callback) -} + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ -AbstractLevelDOWN.prototype.close = function (callback) { - var self = this - var oldStatus = this.status - if (typeof callback !== 'function') { - throw new Error('close() requires a callback argument') - } + P.exponentiatedBy = P.pow = function (n, m) { + var half, + isModExp, + i, + k, + more, + nIsBig, + nIsNeg, + nIsOdd, + y, + x = this; + n = new BigNumber(n); // Allow NaN and ±Infinity, but not other non-integers. - this.status = 'closing' - this._close(function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'closed' - callback() - }) -} + if (n.c && !n.isInteger()) { + throw Error(bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } -AbstractLevelDOWN.prototype._close = function (callback) { - process.nextTick(callback) -} + if (m != null) m = new BigNumber(m); // Exponent of MAX_SAFE_INTEGER is 15. -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - if (typeof options === 'function') { callback = options } + nIsBig = n.e > 14; // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. - if (typeof callback !== 'function') { - throw new Error('get() requires a callback argument') - } + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n))); + return m ? y.mod(m) : y; + } - var err = this._checkKey(key, 'key') - if (err) return process.nextTick(callback, err) + nIsNeg = n.s < 0; - key = this._serializeKey(key) + if (m) { + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + if (isModExp) x = x.mod(m); // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; // If x >= 1, k = ±Infinity. - if (typeof options !== 'object') { options = {} } + if (x.e > -1) k = 1 / k; // If n is negative return ±0, else return ±Infinity. - options.asBuffer = options.asBuffer !== false + return new BigNumber(nIsNeg ? 1 / k : k); + } else if (POW_PRECISION) { + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } - this._get(key, options, callback) -} + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } -AbstractLevelDOWN.prototype._get = function (key, options, callback) { - process.nextTick(function () { callback(new Error('NotFound')) }) -} + y = new BigNumber(ONE); // Performs 54 loop iterations for n of 9007199254740991. -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - if (typeof options === 'function') { callback = options } + for (;;) { + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; - if (typeof callback !== 'function') { - throw new Error('put() requires a callback argument') - } + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } - var err = this._checkKey(key, 'key') - if (err) return process.nextTick(callback, err) + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); - key = this._serializeKey(key) - value = this._serializeValue(value) + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } - if (typeof options !== 'object') { options = {} } + x = x.times(x); - this._put(key, value, options, callback) -} + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } -AbstractLevelDOWN.prototype._put = function (key, value, options, callback) { - process.nextTick(callback) -} + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - if (typeof options === 'function') { callback = options } - if (typeof callback !== 'function') { - throw new Error('del() requires a callback argument') - } + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE;else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ - var err = this._checkKey(key, 'key') - if (err) return process.nextTick(callback, err) - key = this._serializeKey(key) + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ - if (typeof options !== 'object') { options = {} } - this._del(key, options, callback) -} + P.isFinite = function () { + return !!this.c; + }; + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ -AbstractLevelDOWN.prototype._del = function (key, options, callback) { - process.nextTick(callback) -} -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) { return this._chainedBatch() } + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ - if (typeof options === 'function') { callback = options } - if (typeof array === 'function') { callback = array } + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + }; + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ - if (typeof callback !== 'function') { - throw new Error('batch(array) requires a callback argument') - } - if (!Array.isArray(array)) { - return process.nextTick(callback, new Error('batch(array) requires an array argument')) - } + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ - if (!options || typeof options !== 'object') { options = {} } - var serialized = new Array(array.length) + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ - for (var i = 0; i < array.length; i++) { - if (typeof array[i] !== 'object' || array[i] === null) { - return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`')) - } - var e = xtend(array[i]) + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ - if (e.type !== 'put' && e.type !== 'del') { - return process.nextTick(callback, new Error("`type` must be 'put' or 'del'")) - } - var err = this._checkKey(e.key, 'key') - if (err) return process.nextTick(callback, err) + P.isNaN = function () { + return !this.s; + }; + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ - e.key = this._serializeKey(e.key) - if (e.type === 'put') { e.value = this._serializeValue(e.value) } + P.isNegative = function () { + return this.s < 0; + }; + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ - serialized[i] = e - } - this._batch(serialized, options, callback) -} + P.isPositive = function () { + return this.s > 0; + }; + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ -AbstractLevelDOWN.prototype._batch = function (array, options, callback) { - process.nextTick(callback) -} -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - options = cleanRangeOptions(options) + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ - options.reverse = !!options.reverse - options.keys = options.keys !== false - options.values = options.values !== false - options.limit = 'limit' in options ? options.limit : -1 - options.keyAsBuffer = options.keyAsBuffer !== false - options.valueAsBuffer = options.valueAsBuffer !== false - return options -} + P.minus = function (y, b) { + var i, + j, + t, + xLTy, + x = this, + a = x.s; + y = new BigNumber(y, b); + b = y.s; // Either NaN? -function cleanRangeOptions (options) { - var result = {} + if (!a || !b) return new BigNumber(NaN); // Signs differ? - for (var k in options) { - if (!hasOwnProperty.call(options, k)) continue - if (isRangeOption(k) && isEmptyRangeOption(options[k])) continue + if (a != b) { + y.s = -b; + return x.plus(y); + } - result[k] = options[k] - } + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; - return result -} + if (!xe || !ye) { + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); // Either zero? -function isRangeOption (k) { - return rangeOptions.indexOf(k) !== -1 -} + if (!xc[0] || !yc[0]) { + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } -function isEmptyRangeOption (v) { - return v === '' || v == null || isEmptyBuffer(v) -} + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); // Determine which is the bigger number. -function isEmptyBuffer (v) { - return Buffer.isBuffer(v) && v.length === 0 -} + if (a = xe - ye) { + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options !== 'object') { options = {} } - options = this._setupIteratorOptions(options) - return this._iterator(options) -} + t.reverse(); // Prepend zeros to equalise exponents. -AbstractLevelDOWN.prototype._iterator = function (options) { - return new AbstractIterator(this) -} + for (b = a; b--; t.push(0)) { + ; + } -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) -} + t.reverse(); + } else { + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; -AbstractLevelDOWN.prototype._serializeKey = function (key) { - return Buffer.isBuffer(key) ? key : String(key) -} + for (a = b = 0; b < j; b++) { + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } // x < y? Point xc to the array of the bigger number. -AbstractLevelDOWN.prototype._serializeValue = function (value) { - if (value == null) return '' - return Buffer.isBuffer(value) || process.browser ? value : String(value) -} -AbstractLevelDOWN.prototype._checkKey = function (obj, type) { - if (obj === null || obj === undefined) { - return new Error(type + ' cannot be `null` or `undefined`') - } + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; + b = (j = yc.length) - (i = xc.length); // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. - if (Buffer.isBuffer(obj) && obj.length === 0) { - return new Error(type + ' cannot be an empty Buffer') - } + if (b > 0) for (; b--; xc[i++] = 0) { + ; + } + b = BASE - 1; // Subtract yc from xc. - if (String(obj) === '') { - return new Error(type + ' cannot be an empty String') - } -} + for (; j > a;) { + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b) { + ; + } -module.exports = AbstractLevelDOWN + --xc[i]; + xc[j] += BASE; + } -},{"./abstract-chained-batch":188,"./abstract-iterator":189,"xtend":1356}],191:[function(require,module,exports){ -exports.AbstractLevelDOWN = require('./abstract-leveldown') -exports.AbstractIterator = require('./abstract-iterator') -exports.AbstractChainedBatch = require('./abstract-chained-batch') + xc[j] -= yc[j]; + } // Remove leading zeros and adjust exponent accordingly. -},{"./abstract-chained-batch":188,"./abstract-iterator":189,"./abstract-leveldown":190}],192:[function(require,module,exports){ -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ -/** - * Module dependencies. - */ + for (; xc[0] == 0; xc.splice(0, 1), --ye) { + ; + } // Zero? -var callSiteToString = require('./lib/compat').callSiteToString -var eventListenerCount = require('./lib/compat').eventListenerCount -var relative = require('path').relative -/** - * Module exports. - */ + if (!xc[0]) { + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. -module.exports = depd -/** - * Get the path to base files on. - */ + return normalise(y, xc, ye); + }; + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ -var basePath = process.cwd() -/** - * Determine if namespace is contained in the string. - */ + P.modulo = P.mod = function (y, b) { + var q, + s, + x = this; + y = new BigNumber(y, b); // Return NaN if x is Infinity or NaN, or y is NaN or zero. -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } - for (var i = 0; i < vals.length; i++) { - var val = vals[i] + if (MODULO_MODE == 9) { + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true - } - } + y = x.minus(q.times(y)); // To match JavaScript %, ensure sign of zero is sign of dividend. - return false -} + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + return y; + }; + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ -/** - * Convert a data descriptor to accessor descriptor. - */ -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value + P.multipliedBy = P.times = function (y, b) { + var c, + e, + i, + j, + k, + m, + xcL, + xlo, + xhi, + ycL, + ylo, + yhi, + zc, + base, + sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; // Either NaN, ±Infinity or ±0? + + if (!xc || !yc || !xc[0] || !yc[0]) { + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; // Return ±Infinity if either is ±Infinity. - descriptor.get = function getter () { return value } + if (!xc || !yc) { + y.c = y.e = null; // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } - } + return y; + } - delete descriptor.value - delete descriptor.writable + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; // Ensure xc points to longer array and xcL to its length. - Object.defineProperty(obj, prop, descriptor) + if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; // Initialise the result array with zeros. - return descriptor -} + for (i = xcL + ycL, zc = []; i--; zc.push(0)) { + ; + } -/** - * Create arguments string to keep arity. - */ + base = BASE; + sqrtBase = SQRT_BASE; -function createArgumentsString (arity) { - var str = '' + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; - for (var i = 0; i < arity; i++) { - str += ', arg' + i - } + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } - return str.substr(2) -} + zc[j] = c; + } -/** - * Create stack string from stack. - */ + if (c) { + ++e; + } else { + zc.splice(0, 1); + } -function createStackString (stack) { - var str = this.name + ': ' + this.namespace + return normalise(y, zc, e); + }; + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ - if (this.message) { - str += ' deprecated ' + this.message - } - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ - return str -} -/** - * Create deprecate for namespace in caller. - */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + y = new BigNumber(y, b); + b = y.s; // Either NaN? -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } + if (!a || !b) return new BigNumber(NaN); // Signs differ? - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] + if (a != b) { + y.s = -b; + return x.minus(y); + } - function deprecate (message) { - // call to self as log - log.call(deprecate, message) - } + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) + if (!xe || !ye) { + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. - deprecate.function = wrapfunction - deprecate.property = wrapproperty + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } - return deprecate -} + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. -/** - * Determine if namespace is ignored. - */ + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } + t.reverse(); - var str = process.env.NO_DEPRECATION || '' + for (; a--; t.push(0)) { + ; + } - // namespace ignored - return containsNamespace(str, namespace) -} + t.reverse(); + } -/** - * Determine if namespace is traced. - */ + a = xc.length; + b = yc.length; // Point xc to the longer array, and b to the shorter length. -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true - } + if (a - b < 0) t = yc, yc = xc, xc = t, b = a; // Only start adding at yc.length - 1 as the further digits of xc can be ignored. - var str = process.env.TRACE_DEPRECATION || '' + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } - // namespace traced - return containsNamespace(str, namespace) -} + if (a) { + xc = [a].concat(xc); + ++ye; + } // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible -/** - * Display deprecation message. - */ -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + return normalise(y, xc, ye); + }; + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ - // abort early if no destination - if (!haslisteners && this._ignored) { - return - } - var caller - var callFile - var callSite - var depSite - var i = 0 - var seen = false - var stack = getStack() - var file = this._file + P.precision = P.sd = function (sd, rm) { + var c, + n, + v, + x = this; - if (site) { - // provided site - depSite = site - callSite = callSiteLocation(stack[1]) - callSite.name = depSite.name - file = callSite[0] - } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite - } + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE;else intCheck(rm, 0, 8); + return round(new BigNumber(x), sd, rm); + } - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break - } - } + if (v = c[v]) { + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--) { + ; + } // Add the number of digits of the first element. - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined - if (key !== undefined && key in this._warned) { - // already warned - return - } + for (v = c[0]; v >= 10; v /= 10, n++) { + ; + } + } - this._warned[key] = true + if (sd && x.e + 1 > n) n = x.e + 1; + return n; + }; + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return - } + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ - // format and write message - var format = process.stderr.isTTY - ? formatColor - : formatPlain - var output = format.call(this, msg, caller, stack.slice(i)) - process.stderr.write(output + '\n', 'utf8') -} -/** - * Get call site location as array. - */ + P.squareRoot = P.sqrt = function () { + var m, + n, + r, + rep, + t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); // Negative/NaN/Infinity/zero? -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } // Initial estimate. - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } - var site = [file, line, colm] + s = Math.sqrt(+valueOf(x)); // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - site.callSite = callSite - site.name = callSite.getFunctionName() + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); - return site -} + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } -/** - * Generate a default message from the site. - */ + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + + + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; // Newton-Raphson iteration. + + for (;;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + + if (n == '9999' || !rep && n == '4999') { + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name + dp += 4; + s += 4; + rep = 1; + } else { + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } - // make useful anonymous name - if (!funcName) { - funcName = '' - } + break; + } + } + } + } - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} + return format(this, dp, rm, 1); + }; + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ -/** - * Format deprecation message without color. - */ -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg + return format(this, dp, rm); + }; + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } - return formatted - } + P.toFormat = function (dp, rm, format) { + var str, + x = this; - if (caller) { - formatted += ' at ' + formatLocation(caller) - } + if (format == null) { + if (dp != null && rm && _typeof(rm) == 'object') { + format = rm; + rm = null; + } else if (dp && _typeof(dp) == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (_typeof(format) != 'object') { + throw Error(bignumberError + 'Argument not an object: ' + format); + } - return formatted -} + str = x.toFixed(dp, rm); -/** - * Format deprecation message with color. - */ + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + if (g2) i = g1, g1 = g2, g2 = i, len -= i; -function formatColor (msg, caller, stack) { - var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan - ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow - ' \x1b[0m' + msg + '\x1b[39m' // reset + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan - } + for (; i < len; i += g1) { + intPart += groupSeparator + intDigits.substr(i, g1); + } - return formatted - } + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } + str = fractionPart ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), '$&' + (format.fractionGroupSeparator || '')) : fractionPart) : intPart; + } - return formatted -} + return (format.prefix || '') + str + (format.suffix || ''); + }; + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ -/** - * Format call site location. - */ -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] -} + P.toFraction = function (md) { + var d, + d0, + d1, + d2, + e, + exp, + n, + n0, + n1, + q, + r, + s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); // Throw if md is less than one or is not an integer, unless it is Infinity. + + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error(bignumberError + 'Argument ' + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? e > 0 ? d : n1 : n; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); // n0 = d1 = 0 + + n0.c[0] = 0; + + for (;;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; // Determine which fraction is closer to x, n0/d0 or n1/d1 + + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + /* + * Return the value of this BigNumber converted to a number primitive. + */ -/** - * Get the stack as array of call sites. - */ -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace + P.toNumber = function () { + return +valueOf(this); + }; + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) - // capture the stack - Error.captureStackTrace(obj) + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ - // slice this function off the top - var stack = obj.stack.slice(1) - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; // Infinity or NaN? - return stack -} + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } -/** - * Capture call site stack from v8. - */ + if (s < 0 && n.c[0]) str = '-' + str; + } -function prepareObjectStackTrace (obj, stack) { - return stack -} + return str; + }; + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ -/** - * Return a wrapped function in a deprecation message. - */ -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) + P._isBigNumber = true; + if (configObject != null) BigNumber.set(configObject); + return BigNumber; + } // PRIVATE HELPER FUNCTIONS + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. - site.name = fn.name - // eslint-disable-next-line no-eval - var deprecatedfn = eval('(function (' + args + ') {\n' + - '"use strict"\n' + - 'log.call(deprecate, message, site)\n' + - 'return fn.apply(this, arguments)\n' + - '})') + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } // Return a coefficient array as a string of base 10 digits. - return deprecatedfn -} -/** - * Wrap property in a deprecation message. - */ + function coeffToString(a) { + var s, + z, + i = 1, + j = a.length, + r = a[0] + ''; -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + for (; z--; s = '0' + s) { + ; + } - if (!descriptor) { - throw new TypeError('must call property on owner object') - } + r += s; + } // Determine trailing zeros. - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) + for (j = r.length; r.charCodeAt(--j) === 48;) { + ; + } - // set site name - site.name = prop + return r.slice(0, j + 1 || 1); + } // Compare the value of BigNumbers x and y. - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } - var get = descriptor.get - var set = descriptor.set + function compare(x, y) { + var a, + b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; // Either NaN? - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) - } - } + if (!i || !j) return null; + a = xc && !xc[0]; + b = yc && !yc[0]; // Either zero? - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) - } - } + if (a || b) return a ? b ? 0 : -j : i; // Signs differ? - Object.defineProperty(obj, prop, descriptor) -} + if (i != j) return i; + a = i < 0; + b = k == l; // Either Infinity? -/** - * Create DeprecationError for deprecation - */ + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; // Compare exponents. -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString + if (!b) return k > l ^ a ? 1 : -1; + j = (k = xc.length) < (l = yc.length) ? k : l; // Compare digit by digit. - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) - - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) + for (i = 0; i < j; i++) { + if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + } // Compare lengths. - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString - } - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error(bignumberError + (name || 'Argument') + (typeof n == 'number' ? n < min || n > max ? ' out of range: ' : ' not an integer: ' : ' not a primitive number: ') + String(n)); } - }) - - return error -} - -},{"./lib/compat":195,"path":undefined}],193:[function(require,module,exports){ -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - */ - -module.exports = callSiteToString - -/** - * Format a CallSite file location to a string. - */ + } // Assumes finite n. -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() - } - } else { - fileName = callSite.getFileName() + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; } - if (fileName) { - fileLocation += fileName - - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber - - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } - } + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + (e < 0 ? 'e' : 'e+') + e; } - return fileLocation || 'unknown source' -} - -/** - * Format a CallSite to a string. - */ - -function callSiteToString (callSite) { - var addSuffix = true - var fileLocation = callSiteFileLocation(callSite) - var functionName = callSite.getFunctionName() - var isConstructor = callSite.isConstructor() - var isMethodCall = !(callSite.isToplevel() || isConstructor) - var line = '' - - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) + function toFixedPoint(str, e, z) { + var len, zs; // Negative exponent? - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' + if (e < 0) { + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z) { + ; } - line += functionName - - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } + str = zs + str; // Positive exponent } else { - line += typeName + '.' + (methodName || '') - } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } - - if (addSuffix) { - line += ' (' + fileLocation + ')' - } - - return line -} - -/** - * Get constructor name of reviver. - */ + len = str.length; // Append zeros. -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null -} - -},{}],194:[function(require,module,exports){ -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + if (++e > len) { + for (zs = z, e -= len; --e; zs += z) { + ; + } -'use strict' + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } -/** - * Module exports. - * @public - */ + return str; + } // EXPORT -module.exports = eventListenerCount -/** - * Get the count of listeners on an event emitter of a specific type. - */ + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; // AMD. -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length -} + if (typeof define == 'function' && define.amd) { + define(function () { + return BigNumber; + }); // Node.js and other environments that support module.exports. + } else if (typeof module != 'undefined' && module.exports) { + module.exports = BigNumber; // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } -},{}],195:[function(require,module,exports){ -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + globalObject.BigNumber = BigNumber; + } +})(void 0); -'use strict' +},{}],150:[function(require,module,exports){ +(function (__filename){ +"use strict"; /** * Module dependencies. - * @private */ +var fs = require('fs'), + path = require('path'), + fileURLToPath = require('file-uri-to-path'), + join = path.join, + dirname = path.dirname, + exists = fs.accessSync && function (path) { + try { + fs.accessSync(path); + } catch (e) { + return false; + } -var EventEmitter = require('events').EventEmitter - + return true; +} || fs.existsSync || path.existsSync, + defaults = { + arrow: process.env.NODE_BINDINGS_ARROW || ' → ', + compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled', + platform: process.platform, + arch: process.arch, + nodePreGyp: 'node-v' + process.versions.modules + '-' + process.platform + '-' + process.arch, + version: process.versions.node, + bindings: 'bindings.node', + "try": [// node-gyp's linked version in the "build" dir + ['module_root', 'build', 'bindings'], // node-waf and gyp_addon (a.k.a node-gyp) + ['module_root', 'build', 'Debug', 'bindings'], ['module_root', 'build', 'Release', 'bindings'], // Debug files, for development (legacy behavior, remove for node v0.9) + ['module_root', 'out', 'Debug', 'bindings'], ['module_root', 'Debug', 'bindings'], // Release files, but manually compiled (legacy behavior, remove for node v0.9) + ['module_root', 'out', 'Release', 'bindings'], ['module_root', 'Release', 'bindings'], // Legacy from node-waf, node <= 0.4.x + ['module_root', 'build', 'default', 'bindings'], // Production "Release" buildtype binary (meh...) + ['module_root', 'compiled', 'version', 'platform', 'arch', 'bindings'], // node-qbs builds + ['module_root', 'addon-build', 'release', 'install-root', 'bindings'], ['module_root', 'addon-build', 'debug', 'install-root', 'bindings'], ['module_root', 'addon-build', 'default', 'install-root', 'bindings'], // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch} + ['module_root', 'lib', 'binding', 'nodePreGyp', 'bindings']] +}; /** - * Module exports. - * @public + * The main `bindings()` function loads the compiled bindings for a given module. + * It uses V8's Error API to determine the parent filename that this function is + * being invoked from, which is then used to find the root directory. */ -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - function prepareObjectStackTrace (obj, stack) { - return stack - } +function bindings(opts) { + // Argument surgery + if (typeof opts == 'string') { + opts = { + bindings: opts + }; + } else if (!opts) { + opts = {}; + } // maps `defaults` onto `opts` object + - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 + Object.keys(defaults).map(function (i) { + if (!(i in opts)) opts[i] = defaults[i]; + }); // Get the module root - // capture the stack - Error.captureStackTrace(obj) + if (!opts.module_root) { + opts.module_root = exports.getRoot(exports.getFileName()); + } // Ensure the given bindings name ends with .node - // slice the stack - var stack = obj.stack.slice() - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit + if (path.extname(opts.bindings) != '.node') { + opts.bindings += '.node'; + } // https://github.com/webpack/webpack/issues/4175#issuecomment-342931035 - return stack[0].toString ? toString : require('./callsite-tostring') -}) -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || require('./event-listener-count') -}) + var requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require; + var tries = [], + i = 0, + l = opts["try"].length, + n, + b, + err; -/** - * Define a lazy property. - */ + for (; i < l; i++) { + n = join.apply(null, opts["try"][i].map(function (p) { + return opts[p] || p; + })); + tries.push(n); -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() + try { + b = opts.path ? requireFunc.resolve(n) : requireFunc(n); - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) + if (!opts.path) { + b.path = n; + } - return val + return b; + } catch (e) { + if (e.code !== 'MODULE_NOT_FOUND' && e.code !== 'QUALIFIED_PATH_RESOLUTION_FAILED' && !/not find/i.test(e.message)) { + throw e; + } + } } - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) + err = new Error('Could not locate the bindings file. Tried:\n' + tries.map(function (a) { + return opts.arrow + a; + }).join('\n')); + err.tries = tries; + throw err; } +module.exports = exports = bindings; /** - * Call toString() on the obj + * Gets the filename of the JavaScript file that invokes this function. + * Used to help find the root directory of a module. + * Optionally accepts an filename argument to skip when searching for the invoking filename */ -function toString (obj) { - return obj.toString() -} +exports.getFileName = function getFileName(calling_file) { + var origPST = Error.prepareStackTrace, + origSTL = Error.stackTraceLimit, + dummy = {}, + fileName; + Error.stackTraceLimit = 10; -},{"./callsite-tostring":193,"./event-listener-count":194,"events":undefined}],196:[function(require,module,exports){ -/*! - * destroy - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ + Error.prepareStackTrace = function (e, st) { + for (var i = 0, l = st.length; i < l; i++) { + fileName = st[i].getFileName(); + + if (fileName !== __filename) { + if (calling_file) { + if (fileName !== calling_file) { + return; + } + } else { + return; + } + } + } + }; // run the 'prepareStackTrace' function above -'use strict' -/** - * Module dependencies. - * @private - */ + Error.captureStackTrace(dummy); + dummy.stack; // cleanup -var ReadStream = require('fs').ReadStream -var Stream = require('stream') + Error.prepareStackTrace = origPST; + Error.stackTraceLimit = origSTL; // handle filename that starts with "file://" -/** - * Module exports. - * @public - */ + var fileSchema = 'file://'; -module.exports = destroy + if (fileName.indexOf(fileSchema) === 0) { + fileName = fileURLToPath(fileName); + } + return fileName; +}; /** - * Destroy a stream. + * Gets the root directory of a module, given an arbitrary filename + * somewhere in the module tree. The "root directory" is the directory + * containing the `package.json` file. * - * @param {object} stream - * @public + * In: /home/nate/node-native-module/lib/index.js + * Out: /home/nate/node-native-module */ -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } - if (!(stream instanceof Stream)) { - return stream - } +exports.getRoot = function getRoot(file) { + var dir = dirname(file), + prev; - if (typeof stream.destroy === 'function') { - stream.destroy() - } + while (true) { + if (dir === '.') { + // Avoids an infinite loop in rare cases, like the REPL + dir = process.cwd(); + } - return stream -} + if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) { + // Found the 'package.json' file or 'node_modules' dir; we're done + return dir; + } -/** - * Destroy a ReadStream. - * - * @param {object} stream - * @private - */ + if (prev === dir) { + // Got to the top + throw new Error('Could not find module root given file: "' + file + '". Do you have a `package.json` file? '); + } // Try the parent dir next -function destroyReadStream(stream) { - stream.destroy() - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) + prev = dir; + dir = join(dir, '..'); } +}; - return stream -} - -/** - * On open handler to close stream. - * @private - */ - -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() - } -} +}).call(this,require("path").join(__dirname,"node_modules","bindings","bindings.js")) +},{"file-uri-to-path":828,"fs":undefined,"path":undefined}],151:[function(require,module,exports){ +"use strict"; -},{"fs":undefined,"stream":undefined}],197:[function(require,module,exports){ -'use strict' +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -exports.toString = function (klass) { - switch (klass) { - case 1: return 'IN' - case 2: return 'CS' - case 3: return 'CH' - case 4: return 'HS' - case 255: return 'ANY' - } - return 'UNKNOWN_' + klass -} +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -exports.toClass = function (name) { - switch (name.toUpperCase()) { - case 'IN': return 1 - case 'CS': return 2 - case 'CH': return 3 - case 'HS': return 4 - case 'ANY': return 255 - } - return 0 -} +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -},{}],198:[function(require,module,exports){ -'use strict' +Object.defineProperty(exports, "__esModule", { + value: true +}); -const types = require('./types') -const rcodes = require('./rcodes') -const opcodes = require('./opcodes') -const classes = require('./classes') -const ip = require('ip') -const Buffer = require('safe-buffer').Buffer +var crypto = require("./crypto"); -const QUERY_FLAG = 0 -const RESPONSE_FLAG = 1 << 15 -const FLUSH_MASK = 1 << 15 -const NOT_FLUSH_MASK = ~FLUSH_MASK -const QU_MASK = 1 << 15 -const NOT_QU_MASK = ~QU_MASK +var bs58check = require('bs58check'); -const name = exports.txt = exports.name = {} +var ecc = require('tiny-secp256k1'); -name.encode = function (str, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(name.encodingLength(str)) - if (!offset) offset = 0 - const oldOffset = offset +var typeforce = require('typeforce'); - // strip leading and trailing . - const n = str.replace(/^\.|\.$/gm, '') - if (n.length) { - const list = n.split('.') +var wif = require('wif'); - for (let i = 0; i < list.length; i++) { - const len = buf.write(list[i], offset + 1) - buf[offset] = len - offset += len + 1 - } +var UINT256_TYPE = typeforce.BufferN(32); +var NETWORK_TYPE = typeforce.compile({ + wif: typeforce.UInt8, + bip32: { + "public": typeforce.UInt32, + "private": typeforce.UInt32 + } +}); +var BITCOIN = { + wif: 0x80, + bip32: { + "public": 0x0488b21e, + "private": 0x0488ade4 } +}; +var HIGHEST_BIT = 0x80000000; +var UINT31_MAX = Math.pow(2, 31) - 1; - buf[offset++] = 0 +function BIP32Path(value) { + return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null; +} - name.encode.bytes = offset - oldOffset - return buf +function UInt31(value) { + return typeforce.UInt32(value) && value <= UINT31_MAX; } -name.encode.bytes = 0 +var BIP32 = +/*#__PURE__*/ +function () { + function BIP32(__D, __Q, chainCode, network) { + var __DEPTH = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; -name.decode = function (buf, offset) { - if (!offset) offset = 0 + var __INDEX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; - const list = [] - const oldOffset = offset - let len = buf[offset++] + var __PARENT_FINGERPRINT = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0x00000000; - if (len === 0) { - name.decode.bytes = 1 - return '.' - } - if (len >= 0xc0) { - const res = name.decode(buf, buf.readUInt16BE(offset - 1) - 0xc000) - name.decode.bytes = 2 - return res + _classCallCheck(this, BIP32); + + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce(NETWORK_TYPE, network); } - while (len) { - if (len >= 0xc0) { - list.push(name.decode(buf, buf.readUInt16BE(offset - 1) - 0xc000)) - offset++ - break + _createClass(BIP32, [{ + key: "isNeutered", + // Private === not neutered + // Public === neutered + value: function isNeutered() { + return this.__D === undefined; } + }, { + key: "neutered", + value: function neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); + } + }, { + key: "toBase58", + value: function toBase58() { + var network = this.network; + var version = !this.isNeutered() ? network.bip32["private"] : network.bip32["public"]; + var buffer = Buffer.allocUnsafe(78); // 4 bytes: version bytes - list.push(buf.toString('utf-8', offset, offset + len)) - offset += len - len = buf[offset++] - } - - name.decode.bytes = offset - oldOffset - return list.join('.') -} + buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... -name.decode.bytes = 0 + buffer.writeUInt8(this.depth, 4); // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) -name.encodingLength = function (n) { - if (n === '.') return 1 - return Buffer.byteLength(n) + 2 -} + buffer.writeUInt32BE(this.parentFingerprint, 5); // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) -const string = {} + buffer.writeUInt32BE(this.index, 9); // 32 bytes: the chain code -string.encode = function (s, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(string.encodingLength(s)) - if (!offset) offset = 0 + this.chainCode.copy(buffer, 13); // 33 bytes: the public key or private key data - const len = buf.write(s, offset + 1) - buf[offset] = len - string.encode.bytes = len + 1 - return buf -} + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); // 33 bytes: the public key + } else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } -string.encode.bytes = 0 + return bs58check.encode(buffer); + } + }, { + key: "toWIF", + value: function toWIF() { + if (!this.privateKey) throw new TypeError('Missing private key'); + return wif.encode(this.network.wif, this.privateKey, true); + } // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions -string.decode = function (buf, offset) { - if (!offset) offset = 0 + }, { + key: "derive", + value: function derive(index) { + typeforce(typeforce.UInt32, index); + var isHardened = index >= HIGHEST_BIT; + var data = Buffer.allocUnsafe(37); // Hardened child + + if (isHardened) { + if (this.isNeutered()) throw new TypeError('Missing private key for hardened child key'); // data = 0x00 || ser256(kpar) || ser32(index) + + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); // Normal child + } else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } - const len = buf[offset] - const s = buf.toString('utf-8', offset + 1, offset + 1 + len) - string.decode.bytes = len + 1 - return s -} + var I = crypto.hmacSHA512(this.chainCode, data); + var IL = I.slice(0, 32); + var IR = I.slice(32); // if parse256(IL) >= n, proceed with the next value for i -string.decode.bytes = 0 + if (!ecc.isPrivate(IL)) return this.derive(index + 1); // Private parent key -> private child key -string.encodingLength = function (s) { - return Buffer.byteLength(s) + 1 -} + var hd; -const header = {} + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + var ki = ecc.privateAdd(this.privateKey, IL); // In case ki == 0, proceed with the next value for i -header.encode = function (h, buf, offset) { - if (!buf) buf = header.encodingLength(h) - if (!offset) offset = 0 + if (ki == null) return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); // Public parent key -> public child key + } else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + var Ki = ecc.pointAddScalar(this.publicKey, IL, true); // In case Ki is the point at infinity, proceed with the next value for i - const flags = (h.flags || 0) & 32767 - const type = h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG + if (Ki === null) return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } - buf.writeUInt16BE(h.id || 0, offset) - buf.writeUInt16BE(flags | type, offset + 2) - buf.writeUInt16BE(h.questions.length, offset + 4) - buf.writeUInt16BE(h.answers.length, offset + 6) - buf.writeUInt16BE(h.authorities.length, offset + 8) - buf.writeUInt16BE(h.additionals.length, offset + 10) + return hd; + } + }, { + key: "deriveHardened", + value: function deriveHardened(index) { + typeforce(UInt31, index); // Only derives hardened private keys by default - return buf -} + return this.derive(index + HIGHEST_BIT); + } + }, { + key: "derivePath", + value: function derivePath(path) { + typeforce(BIP32Path, path); + var splitPath = path.split('/'); -header.encode.bytes = 12 + if (splitPath[0] === 'm') { + if (this.parentFingerprint) throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } -header.decode = function (buf, offset) { - if (!offset) offset = 0 - if (buf.length < 12) throw new Error('Header must be 12 bytes') - const flags = buf.readUInt16BE(offset + 2) + return splitPath.reduce(function (prevHd, indexStr) { + var index; - return { - id: buf.readUInt16BE(offset), - type: flags & RESPONSE_FLAG ? 'response' : 'query', - flags: flags & 32767, - flag_qr: ((flags >> 15) & 0x1) === 1, - opcode: opcodes.toString((flags >> 11) & 0xf), - flag_aa: ((flags >> 10) & 0x1) === 1, - flag_tc: ((flags >> 9) & 0x1) === 1, - flag_rd: ((flags >> 8) & 0x1) === 1, - flag_ra: ((flags >> 7) & 0x1) === 1, - flag_z: ((flags >> 6) & 0x1) === 1, - flag_ad: ((flags >> 5) & 0x1) === 1, - flag_cd: ((flags >> 4) & 0x1) === 1, - rcode: rcodes.toString(flags & 0xf), - questions: new Array(buf.readUInt16BE(offset + 4)), - answers: new Array(buf.readUInt16BE(offset + 6)), - authorities: new Array(buf.readUInt16BE(offset + 8)), - additionals: new Array(buf.readUInt16BE(offset + 10)) - } -} + if (indexStr.slice(-1) === "'") { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + }, { + key: "sign", + value: function sign(hash) { + var lowR = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (!this.privateKey) throw new Error('Missing private key'); -header.decode.bytes = 12 + if (lowR === false) { + return ecc.sign(hash, this.privateKey); + } else { + var sig = ecc.sign(hash, this.privateKey); + var extraData = Buffer.alloc(32, 0); + var counter = 0; // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up -header.encodingLength = function () { - return 12 -} + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.privateKey, extraData); + } -const runknown = exports.unknown = {} + return sig; + } + } + }, { + key: "verify", + value: function verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + }, { + key: "depth", + get: function get() { + return this.__DEPTH; + } + }, { + key: "index", + get: function get() { + return this.__INDEX; + } + }, { + key: "parentFingerprint", + get: function get() { + return this.__PARENT_FINGERPRINT; + } + }, { + key: "publicKey", + get: function get() { + if (this.__Q === undefined) this.__Q = ecc.pointFromScalar(this.__D, true); + return this.__Q; + } + }, { + key: "privateKey", + get: function get() { + return this.__D; + } + }, { + key: "identifier", + get: function get() { + return crypto.hash160(this.publicKey); + } + }, { + key: "fingerprint", + get: function get() { + return this.identifier.slice(0, 4); + } + }]); -runknown.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(runknown.encodingLength(data)) - if (!offset) offset = 0 + return BIP32; +}(); - buf.writeUInt16BE(data.length, offset) - data.copy(buf, offset + 2) +function fromBase58(inString, network) { + var buffer = bs58check.decode(inString); + if (buffer.length !== 78) throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; // 4 bytes: version bytes - runknown.encode.bytes = data.length + 2 - return buf -} + var version = buffer.readUInt32BE(0); + if (version !== network.bip32["private"] && version !== network.bip32["public"]) throw new TypeError('Invalid network version'); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... -runknown.encode.bytes = 0 + var depth = buffer[4]; // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) -runknown.decode = function (buf, offset) { - if (!offset) offset = 0 + var parentFingerprint = buffer.readUInt32BE(5); - const len = buf.readUInt16BE(offset) - const data = buf.slice(offset + 2, offset + 2 + len) - runknown.decode.bytes = len + 2 - return data -} + if (depth === 0) { + if (parentFingerprint !== 0x00000000) throw new TypeError('Invalid parent fingerprint'); + } // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) -runknown.decode.bytes = 0 -runknown.encodingLength = function (data) { - return data.length + 2 -} + var index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) throw new TypeError('Invalid index'); // 32 bytes: the chain code -const rns = exports.ns = {} + var chainCode = buffer.slice(13, 45); + var hd; // 33 bytes: private key data (0x00 + k) -rns.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(rns.encodingLength(data)) - if (!offset) offset = 0 + if (version === network.bip32["private"]) { + if (buffer.readUInt8(45) !== 0x00) throw new TypeError('Invalid private key'); + var k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); // 33 bytes: public key data (0x02 + X or 0x03 + X) + } else { + var X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + } - name.encode(data, buf, offset + 2) - buf.writeUInt16BE(name.encode.bytes, offset) - rns.encode.bytes = name.encode.bytes + 2 - return buf + return hd; } -rns.encode.bytes = 0 +exports.fromBase58 = fromBase58; -rns.decode = function (buf, offset) { - if (!offset) offset = 0 - - const len = buf.readUInt16BE(offset) - const dd = name.decode(buf, offset + 2) - - rns.decode.bytes = len + 2 - return dd +function fromPrivateKey(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); } -rns.decode.bytes = 0 +exports.fromPrivateKey = fromPrivateKey; -rns.encodingLength = function (data) { - return name.encodingLength(data) + 2 +function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE + }, { + privateKey: privateKey, + chainCode: chainCode + }); + network = network || BITCOIN; + if (!ecc.isPrivate(privateKey)) throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); } -const rsoa = exports.soa = {} - -rsoa.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(rsoa.encodingLength(data)) - if (!offset) offset = 0 - - const oldOffset = offset - offset += 2 - name.encode(data.mname, buf, offset) - offset += name.encode.bytes - name.encode(data.rname, buf, offset) - offset += name.encode.bytes - buf.writeUInt32BE(data.serial || 0, offset) - offset += 4 - buf.writeUInt32BE(data.refresh || 0, offset) - offset += 4 - buf.writeUInt32BE(data.retry || 0, offset) - offset += 4 - buf.writeUInt32BE(data.expire || 0, offset) - offset += 4 - buf.writeUInt32BE(data.minimum || 0, offset) - offset += 4 - - buf.writeUInt16BE(offset - oldOffset - 2, oldOffset) - rsoa.encode.bytes = offset - oldOffset - return buf -} - -rsoa.encode.bytes = 0 - -rsoa.decode = function (buf, offset) { - if (!offset) offset = 0 +function fromPublicKey(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); +} - const oldOffset = offset +exports.fromPublicKey = fromPublicKey; - const data = {} - offset += 2 - data.mname = name.decode(buf, offset) - offset += name.decode.bytes - data.rname = name.decode(buf, offset) - offset += name.decode.bytes - data.serial = buf.readUInt32BE(offset) - offset += 4 - data.refresh = buf.readUInt32BE(offset) - offset += 4 - data.retry = buf.readUInt32BE(offset) - offset += 4 - data.expire = buf.readUInt32BE(offset) - offset += 4 - data.minimum = buf.readUInt32BE(offset) - offset += 4 +function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce({ + publicKey: typeforce.BufferN(33), + chainCode: UINT256_TYPE + }, { + publicKey: publicKey, + chainCode: chainCode + }); + network = network || BITCOIN; // verify the X coordinate is a point on the curve - rsoa.decode.bytes = offset - oldOffset - return data + if (!ecc.isPoint(publicKey)) throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); } -rsoa.decode.bytes = 0 - -rsoa.encodingLength = function (data) { - return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname) +function fromSeed(seed, network) { + typeforce(typeforce.Buffer, seed); + if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + var I = crypto.hmacSHA512(Buffer.from('Bitcoin seed', 'utf8'), seed); + var IL = I.slice(0, 32); + var IR = I.slice(32); + return fromPrivateKey(IL, IR, network); } -const rtxt = exports.txt = {} - -rtxt.encode = function (data, buf, offset) { - if (!Array.isArray(data)) data = [data] - for (let i = 0; i < data.length; i++) { - if (typeof data[i] === 'string') { - data[i] = Buffer.from(data[i]) - } - if (!Buffer.isBuffer(data[i])) { - throw new Error('Must be a Buffer') - } - } +exports.fromSeed = fromSeed; - if (!buf) buf = Buffer.allocUnsafe(rtxt.encodingLength(data)) - if (!offset) offset = 0 - - const oldOffset = offset - offset += 2 +},{"./crypto":152,"bs58check":263,"tiny-secp256k1":2922,"typeforce":2945,"wif":2991}],152:[function(require,module,exports){ +"use strict"; - data.forEach(function (d) { - buf[offset++] = d.length - d.copy(buf, offset, 0, d.length) - offset += d.length - }) +Object.defineProperty(exports, "__esModule", { + value: true +}); - buf.writeUInt16BE(offset - oldOffset - 2, oldOffset) - rtxt.encode.bytes = offset - oldOffset - return buf -} +var createHash = require('create-hash'); -rtxt.encode.bytes = 0 +var createHmac = require('create-hmac'); -rtxt.decode = function (buf, offset) { - if (!offset) offset = 0 - const oldOffset = offset - let remaining = buf.readUInt16BE(offset) - offset += 2 +function hash160(buffer) { + var sha256Hash = createHash('sha256').update(buffer).digest(); - let data = [] - while (remaining > 0) { - const len = buf[offset++] - --remaining - if (remaining < len) { - throw new Error('Buffer overflow') - } - data.push(buf.slice(offset, offset + len)) - offset += len - remaining -= len + try { + return createHash('rmd160').update(sha256Hash).digest(); + } catch (err) { + return createHash('ripemd160').update(sha256Hash).digest(); } - - rtxt.decode.bytes = offset - oldOffset - return data } -rtxt.decode.bytes = 0 +exports.hash160 = hash160; -rtxt.encodingLength = function (data) { - if (!Array.isArray(data)) data = [data] - let length = 2 - data.forEach(function (buf) { - if (typeof buf === 'string') { - length += Buffer.byteLength(buf) + 1 - } else { - length += buf.length + 1 - } - }) - return length +function hmacSHA512(key, data) { + return createHmac('sha512', key).update(data).digest(); } -const rnull = exports.null = {} - -rnull.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(rnull.encodingLength(data)) - if (!offset) offset = 0 - - if (typeof data === 'string') data = Buffer.from(data) - if (!data) data = Buffer.allocUnsafe(0) - - const oldOffset = offset - offset += 2 +exports.hmacSHA512 = hmacSHA512; - const len = data.length - data.copy(buf, offset, 0, len) - offset += len +},{"create-hash":620,"create-hmac":621}],153:[function(require,module,exports){ +"use strict"; - buf.writeUInt16BE(offset - oldOffset - 2, oldOffset) - rnull.encode.bytes = offset - oldOffset - return buf -} +Object.defineProperty(exports, "__esModule", { + value: true +}); -rnull.encode.bytes = 0 +var bip32_1 = require("./bip32"); -rnull.decode = function (buf, offset) { - if (!offset) offset = 0 - const oldOffset = offset - const len = buf.readUInt16BE(offset) +exports.fromSeed = bip32_1.fromSeed; +exports.fromBase58 = bip32_1.fromBase58; +exports.fromPublicKey = bip32_1.fromPublicKey; +exports.fromPrivateKey = bip32_1.fromPrivateKey; - offset += 2 +},{"./bip32":151}],154:[function(require,module,exports){ +"use strict"; - const data = buf.slice(offset, offset + len) - offset += len +// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki +// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] +// NOTE: SIGHASH byte ignored AND restricted, truncate before use +var Buffer = require('safe-buffer').Buffer; - rnull.decode.bytes = offset - oldOffset - return data +function check(buffer) { + if (buffer.length < 8) return false; + if (buffer.length > 72) return false; + if (buffer[0] !== 0x30) return false; + if (buffer[1] !== buffer.length - 2) return false; + if (buffer[2] !== 0x02) return false; + var lenR = buffer[3]; + if (lenR === 0) return false; + if (5 + lenR >= buffer.length) return false; + if (buffer[4 + lenR] !== 0x02) return false; + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false; + if (6 + lenR + lenS !== buffer.length) return false; + if (buffer[4] & 0x80) return false; + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) return false; + if (buffer[lenR + 6] & 0x80) return false; + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) return false; + return true; } -rnull.decode.bytes = 0 +function decode(buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short'); + if (buffer.length > 72) throw new Error('DER sequence length is too long'); + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence'); + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid'); + if (buffer[2] !== 0x02) throw new Error('Expected DER integer'); + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero'); + if (5 + lenR >= buffer.length) throw new Error('R length is too long'); + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)'); + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero'); + if (6 + lenR + lenS !== buffer.length) throw new Error('S length is invalid'); + if (buffer[4] & 0x80) throw new Error('R value is negative'); + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) throw new Error('R value excessively padded'); + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative'); + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded'); // non-BIP66 - extract R, S values -rnull.encodingLength = function (data) { - if (!data) return 2 - return (Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data)) + 2 + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) + }; } +/* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 +*/ -const rhinfo = exports.hinfo = {} - -rhinfo.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(rhinfo.encodingLength(data)) - if (!offset) offset = 0 - const oldOffset = offset - offset += 2 - string.encode(data.cpu, buf, offset) - offset += string.encode.bytes - string.encode(data.os, buf, offset) - offset += string.encode.bytes - buf.writeUInt16BE(offset - oldOffset - 2, oldOffset) - rhinfo.encode.bytes = offset - oldOffset - return buf +function encode(r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero'); + if (lenS === 0) throw new Error('S length is zero'); + if (lenR > 33) throw new Error('R length is too long'); + if (lenS > 33) throw new Error('S length is too long'); + if (r[0] & 0x80) throw new Error('R value is negative'); + if (s[0] & 0x80) throw new Error('S value is negative'); + if (lenR > 1 && r[0] === 0x00 && !(r[1] & 0x80)) throw new Error('R value excessively padded'); + if (lenS > 1 && s[0] === 0x00 && !(s[1] & 0x80)) throw new Error('S value excessively padded'); + var signature = Buffer.allocUnsafe(6 + lenR + lenS); // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + return signature; } -rhinfo.encode.bytes = 0 +module.exports = { + check: check, + decode: decode, + encode: encode +}; -rhinfo.decode = function (buf, offset) { - if (!offset) offset = 0 +},{"safe-buffer":2812}],155:[function(require,module,exports){ +"use strict"; - const oldOffset = offset +module.exports = Bitboot; - const data = {} - offset += 2 - data.cpu = string.decode(buf, offset) - offset += string.decode.bytes - data.os = string.decode(buf, offset) - offset += string.decode.bytes - rhinfo.decode.bytes = offset - oldOffset - return data -} +var EventEmitter = require('events').EventEmitter; -rhinfo.decode.bytes = 0 +var inherits = require('util').inherits; -rhinfo.encodingLength = function (data) { - return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2 -} +var crypto = require('crypto'); -const rptr = exports.ptr = {} -const rcname = exports.cname = rptr -const rdname = exports.dname = rptr +var DHT = require('bittorrent-dht'); -rptr.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(rptr.encodingLength(data)) - if (!offset) offset = 0 +var KBucket = require('k-bucket'); - name.encode(data, buf, offset + 2) - buf.writeUInt16BE(name.encode.bytes, offset) - rptr.encode.bytes = name.encode.bytes + 2 - return buf -} +var debug = require('debug'); -rptr.encode.bytes = 0 +var bitwise = require('bitwise'); -rptr.decode = function (buf, offset) { - if (!offset) offset = 0 +inherits(Bitboot, EventEmitter); - const data = name.decode(buf, offset + 2) - rptr.decode.bytes = name.decode.bytes + 2 - return data +function Bitboot(rallyName, opts) { + if (!opts) opts = {}; + var self = this; + this.rallyName = rallyName; + this.rallyId = crypto.createHash('sha1').update(this.rallyName).digest(); + this.destroyed = false; + this.dht = null; + this._interval = null; + this.debug = debug('bitboot'); + EventEmitter.call(this); + process.nextTick(bootstrap); + this.debug('Using rally point ' + this.rallyName + ' (' + this.rallyId.toString('hex') + ')'); + + function bootstrap() { + if (self.destroyed) return; + var id = crypto.randomBytes(20); + id[0] = self.rallyId[0]; + id[1] = self.rallyId[1]; + id[18] = self.rallyId[18]; + id[19] = self.rallyId[19]; + self.dht = self._createDHT(id, opts.bootstrap !== false); + } } -rptr.decode.bytes = 0 +Bitboot.prototype.destroy = function (cb) { + this.debug('destroying all connections'); -rptr.encodingLength = function (data) { - return name.encodingLength(data) + 2 -} + if (this.destroyed && cb) { + process.nextTick(cb); + } else if (!this.destroyed) { + if (this._interval) clearInterval(this._interval); + this.destroyed = true; + this.dht.destroy(cb); + } +}; -const rsrv = exports.srv = {} +Bitboot.prototype._createDHT = function (id, bootstrap) { + var dht = new DHT({ + id: id, + bootstrap: bootstrap + }); + var self = this; + var dmsg = 'Joining network with id ' + id.toString('hex') + ' (distance to rally ' + KBucket.distance(id, this.rallyId) + ')'; + this.debug(dmsg); + dht.on('error', onerror); + dht.on('ready', onready); -rsrv.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(rsrv.encodingLength(data)) - if (!offset) offset = 0 + function onerror(err) { + self.emit('error', err); + } - buf.writeUInt16BE(data.priority || 0, offset + 2) - buf.writeUInt16BE(data.weight || 0, offset + 4) - buf.writeUInt16BE(data.port || 0, offset + 6) - name.encode(data.target, buf, offset + 8) + function onready() { + self.emit('rejoin', dht.nodeId); - const len = name.encode.bytes + 6 - buf.writeUInt16BE(len, offset) + if (!self._interval && bootstrap) { + // first run, so search and set interval for future searches + self.debug('Searching, and creating interval for future searches'); + search(); + self._interval = setInterval(search, 1000 * 60); + } + } - rsrv.encode.bytes = len + 2 - return buf -} + function search() { + self._search(); + } -rsrv.encode.bytes = 0 + return dht; +}; -rsrv.decode = function (buf, offset) { - if (!offset) offset = 0 +Bitboot.prototype._search = function () { + // get all nodes close to the rally point + this.debug('Searching for nodes near rally point'); + var self = this; + var query = { + q: 'find_node', + a: { + id: this.dht.nodeId, + target: this.rallyId + } + }; - const len = buf.readUInt16BE(offset) + this.dht._rpc.closest(this.rallyId, query, null, finished); - const data = {} - data.priority = buf.readUInt16BE(offset + 2) - data.weight = buf.readUInt16BE(offset + 4) - data.port = buf.readUInt16BE(offset + 6) - data.target = name.decode(buf, offset + 8) + function finished(err) { + if (err) self.emit('error', err);else self._attemptCommunication(); + } +}; - rsrv.decode.bytes = len + 2 - return data -} +Bitboot.prototype._attemptCommunication = function () { + if (this.dht.nodes.count() === 0) { + this.emit('error', 'Could not connect to any nodes on the DHT. Are you connected to the internet?'); + return; + } -rsrv.decode.bytes = 0 + var closest = this.dht.nodes.closest(this.rallyId, 40); -rsrv.encodingLength = function (data) { - return 8 + name.encodingLength(data.target) -} + var peers = this._extractPeers(closest); -const rcaa = exports.caa = {} + var mydist = KBucket.distance(this.dht.nodeId, this.rallyId); + var closestdist = KBucket.distance(closest[0].id, this.rallyId); // emit all peers found -rcaa.ISSUER_CRITICAL = 1 << 7 + this.emit('peers', peers); -rcaa.encode = function (data, buf, offset) { - const len = rcaa.encodingLength(data) + if (mydist <= closestdist) { + this.debug('We are already at the rally point. Keep hanging out.'); + } else if (peers.length === 0) { + this.debug('No peers found, so it\'s up to us to hang out at the rally point'); + this.debug('The closest other node is ' + closest[0].id.toString('hex')); - if (!buf) buf = Buffer.allocUnsafe(rcaa.encodingLength(data)) - if (!offset) offset = 0 + this._waddleCloser(closest); + } else if (!peers[0].id.equals(closest[0].id) && mydist > closestdist) { + this.debug('Peers exist but far away - it\'s up to us to go to the rally point'); - if (data.issuerCritical) { - data.flags = rcaa.ISSUER_CRITICAL + this._waddleCloser(closest); + } else if (peers[0].id.equals(closest[0].id)) { + this.debug('Another peer is already at the rally point - so we won\'t move.'); } +}; - buf.writeUInt16BE(len - 2, offset) - offset += 2 - buf.writeUInt8(data.flags || 0, offset) - offset += 1 - string.encode(data.tag, buf, offset) - offset += string.encode.bytes - buf.write(data.value, offset) - offset += Buffer.byteLength(data.value) - - rcaa.encode.bytes = len - return buf -} +Bitboot.prototype._waddleCloser = function (closest) { + var self = this; + this.dht.destroy(restart); + this.debug('Waddling closer to the rally point destroying old DHT connection'); -rcaa.encode.bytes = 0 + function restart() { + self.debug('Old DHT connection destroyed'); -rcaa.decode = function (buf, offset) { - if (!offset) offset = 0 + var id = self._twiddleMarch(closest[0].id); - const len = buf.readUInt16BE(offset) - offset += 2 + self.dht = self._createDHT(id, true); + self.dht.on('ready', sayhi); + } // make sure other close nodes know about us - const oldOffset = offset - const data = {} - data.flags = buf.readUInt8(offset) - offset += 1 - data.tag = string.decode(buf, offset) - offset += string.decode.bytes - data.value = buf.toString('utf-8', offset, oldOffset + len) - data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL) + function sayhi() { + self.debug('Saying hi to ' + closest.length + ' nodes so they know about us'); - rcaa.decode.bytes = len + 2 + for (var i = 0; i < closest.length; i++) { + self.dht.addNode(closest[i]); + } + } +}; - return data -} +Bitboot.prototype._extractPeers = function (nodes) { + var peers = []; -rcaa.decode.bytes = 0 + for (var i = 0; i < nodes.length; i++) { + var validid = nodes[i].id[18] === this.rallyId[18] && nodes[i].id[19] === this.rallyId[19]; -rcaa.encodingLength = function (data) { - return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2 -} + if (validid && !nodes[i].id.equals(this.dht.nodeId)) { + peers.push(nodes[i]); + } + } -const rmx = exports.mx = {} + return peers; +}; // This function moves an initial node id closer to the target node id +// until it beats the closest id. It returns the new id as a buffer. -rmx.encode = function (data, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(rmx.encodingLength(data)) - if (!offset) offset = 0 - const oldOffset = offset - offset += 2 - buf.writeUInt16BE(data.preference || 0, offset) - offset += 2 - name.encode(data.exchange, buf, offset) - offset += name.encode.bytes +Bitboot.prototype._twiddleMarch = function (closest) { + var xdistance = KBucket.distance(closest, this.rallyId); + var targetBits = bitwise.readBuffer(this.rallyId); + var resultBits = bitwise.readBuffer(this.dht.nodeId); + var result = null; + var rdistance = null; - buf.writeUInt16BE(offset - oldOffset - 2, oldOffset) - rmx.encode.bytes = offset - oldOffset - return buf -} + for (var leftIndex = 0; leftIndex < resultBits.length; leftIndex++) { + // next line - start at length-17 because -1 is last position, then move two bytes (16 bits) + // to the left since the last two bytes are already going to match the target + for (var rightIndex = resultBits.length - 17; rightIndex >= leftIndex; rightIndex--) { + if (resultBits[rightIndex] !== targetBits[rightIndex]) { + resultBits[rightIndex] = targetBits[rightIndex]; + result = bitwise.createBuffer(resultBits); + rdistance = KBucket.distance(result, this.rallyId); + if (rdistance < xdistance) return result; -rmx.encode.bytes = 0 + if (rightIndex !== leftIndex) { + resultBits[rightIndex] = bitwise.not([resultBits[rightIndex]])[0]; + result = bitwise.createBuffer(resultBits); + } + } + } + } -rmx.decode = function (buf, offset) { - if (!offset) offset = 0 + return result; +}; - const oldOffset = offset +},{"bittorrent-dht":207,"bitwise":210,"crypto":undefined,"debug":158,"events":undefined,"k-bucket":1519,"util":undefined}],156:[function(require,module,exports){ +"use strict"; - const data = {} - offset += 2 - data.preference = buf.readUInt16BE(offset) - offset += 2 - data.exchange = name.decode(buf, offset) - offset += name.decode.bytes +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - rmx.decode.bytes = offset - oldOffset - return data -} +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); +/** + * Colors. + */ -rmx.encodingLength = function (data) { - return 4 + name.encodingLength(data.exchange) -} +exports.colors = ['lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson']; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ -const ra = exports.a = {} +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 -ra.encode = function (host, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(ra.encodingLength(host)) - if (!offset) offset = 0 - buf.writeUInt16BE(4, offset) - offset += 2 - ip.toBuffer(host, buf, offset) - ra.encode.bytes = 6 - return buf + return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // double check webkit in userAgent just in case we are in a worker + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -ra.encode.bytes = 0 - -ra.decode = function (buf, offset) { - if (!offset) offset = 0 - - offset += 2 - const host = ip.toString(buf, offset, 4) - ra.decode.bytes = 6 - return host -} -ra.decode.bytes = 0 +exports.formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; +/** + * Colorize log arguments if enabled. + * + * @api public + */ -ra.encodingLength = function () { - return 6 -} -const raaaa = exports.aaaa = {} +function formatArgs(args) { + var useColors = this.useColors; + args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); + if (!useColors) return; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into -raaaa.encode = function (host, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(raaaa.encodingLength(host)) - if (!offset) offset = 0 + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function (match) { + if ('%%' === match) return; + index++; - buf.writeUInt16BE(16, offset) - offset += 2 - ip.toBuffer(host, buf, offset) - raaaa.encode.bytes = 18 - return buf + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + args.splice(lastC, 0, c); } +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -raaaa.encode.bytes = 0 - -raaaa.decode = function (buf, offset) { - if (!offset) offset = 0 - offset += 2 - const host = ip.toString(buf, offset, 16) - raaaa.decode.bytes = 18 - return host +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === (typeof console === "undefined" ? "undefined" : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments); } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -raaaa.decode.bytes = 0 -raaaa.encodingLength = function () { - return 18 +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch (e) {} } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -const roption = exports.option = {} - -roption.encode = function (option, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(roption.encodingLength(option)) - if (!offset) offset = 0 - const oldOffset = offset - - buf.writeUInt16BE(option.code, offset) - offset += 2 - buf.writeUInt16BE(option.data.length, offset) - offset += 2 - option.data.copy(buf, offset) - offset += option.data.length - roption.encode.bytes = offset - oldOffset - return buf -} +function load() { + var r; -roption.encode.bytes = 0 + try { + r = exports.storage.debug; + } catch (e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG -roption.decode = function (buf, offset) { - if (!offset) offset = 0 - const option = {} - option.code = buf.readUInt16BE(offset) - const len = buf.readUInt16BE(offset + 2) - option.data = buf.slice(offset + 4, offset + 4 + len) + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - roption.decode.bytes = len + 4 - return option + return r; } +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ -roption.decode.bytes = 0 -roption.encodingLength = function (option) { - return option.data.length + 4 +exports.enable(load()); +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } -const ropt = exports.opt = {} +},{"./debug":157}],157:[function(require,module,exports){ +"use strict"; -ropt.encode = function (options, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(ropt.encodingLength(options)) - if (!offset) offset = 0 - const oldOffset = offset +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); +/** + * The currently active debug mode names, and names to skip. + */ - const rdlen = encodingLengthList(options, roption) - buf.writeUInt16BE(rdlen, offset) - offset = encodeList(options, roption, buf, offset + 2) +exports.names = []; +exports.skips = []; +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ - ropt.encode.bytes = offset - oldOffset - return buf -} +exports.formatters = {}; +/** + * Previous log timestamp. + */ -ropt.encode.bytes = 0 +var prevTime; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -ropt.decode = function (buf, offset) { - if (!offset) offset = 0 - const oldOffset = offset +function selectColor(namespace) { + var hash = 0, + i; - const options = [] - let rdlen = buf.readUInt16BE(offset) - offset += 2 - let o = 0 - while (rdlen > 0) { - options[o++] = roption.decode(buf, offset) - offset += roption.decode.bytes - rdlen -= roption.decode.bytes + for (i in namespace) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } - ropt.decode.bytes = offset - oldOffset - return options -} -ropt.decode.bytes = 0 - -ropt.encodingLength = function (options) { - return 2 + encodingLengthList(options || [], roption) + return exports.colors[Math.abs(hash) % exports.colors.length]; } +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -const renc = exports.record = function (type) { - switch (type.toUpperCase()) { - case 'A': return ra - case 'PTR': return rptr - case 'CNAME': return rcname - case 'DNAME': return rdname - case 'TXT': return rtxt - case 'NULL': return rnull - case 'AAAA': return raaaa - case 'SRV': return rsrv - case 'HINFO': return rhinfo - case 'CAA': return rcaa - case 'NS': return rns - case 'SOA': return rsoa - case 'MX': return rmx - case 'OPT': return ropt - } - return runknown -} - -const answer = exports.answer = {} - -answer.encode = function (a, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(answer.encodingLength(a)) - if (!offset) offset = 0 - const oldOffset = offset +function createDebug(namespace) { + function debug() { + // disabled? + if (!debug.enabled) return; + var self = debug; // set `diff` timestamp - name.encode(a.name, buf, offset) - offset += name.encode.bytes + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; // turn the `arguments` into a proper Array - buf.writeUInt16BE(types.toType(a.type), offset) + var args = new Array(arguments.length); - if (a.type.toUpperCase() === 'OPT') { - if (a.name !== '.') { - throw new Error('OPT name must be root.') + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; } - buf.writeUInt16BE(a.updPayloadSize || 4096, offset + 2) - buf.writeUInt8(a.extendedRcode || 0, offset + 4) - buf.writeUInt8(a.ednsVersion || 0, offset + 5) - buf.writeUInt16BE(a.flags || 0, offset + 6) - - offset += 8 - ropt.encode(a.options || [], buf, offset) - offset += ropt.encode.bytes - } else { - let klass = classes.toClass(a.class === undefined ? 'IN' : a.class) - if (a.flush) klass |= FLUSH_MASK // the 1st bit of the class is the flush bit - buf.writeUInt16BE(klass, offset + 2) - buf.writeUInt32BE(a.ttl || 0, offset + 4) - offset += 8 - const enc = renc(a.type) - enc.encode(a.data, buf, offset) - offset += enc.encode.bytes - } + args[0] = exports.coerce(args[0]); - answer.encode.bytes = offset - oldOffset - return buf -} + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } // apply any `formatters` transformations -answer.encode.bytes = 0 -answer.decode = function (buf, offset) { - if (!offset) offset = 0 + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; - const a = {} - const oldOffset = offset + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` - a.name = name.decode(buf, offset) - offset += name.decode.bytes - a.type = types.toString(buf.readUInt16BE(offset)) - if (a.type === 'OPT') { - a.udpPayloadSize = buf.readUInt16BE(offset + 2) - a.extendedRcode = buf.readUInt8(offset + 4) - a.ednsVersion = buf.readUInt8(offset + 5) - a.flags = buf.readUInt16BE(offset + 6) - a.flag_do = ((a.flags >> 15) & 0x1) === 1 - a.options = ropt.decode(buf, offset + 8) - offset += 8 + ropt.decode.bytes - } else { - const klass = buf.readUInt16BE(offset + 2) - a.ttl = buf.readUInt32BE(offset + 4) + args.splice(index, 1); + index--; + } - a.class = classes.toString(klass & NOT_FLUSH_MASK) - a.flush = !!(klass & FLUSH_MASK) + return match; + }); // apply env-specific formatting (colors, etc.) - const enc = renc(a.type) - a.data = enc.decode(buf, offset + 8) - offset += 8 + enc.decode.bytes + exports.formatArgs.call(self, args); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); } - answer.decode.bytes = offset - oldOffset - return a -} + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); // env-specific initialization logic for debug instances -answer.decode.bytes = 0 + if ('function' === typeof exports.init) { + exports.init(debug); + } -answer.encodingLength = function (a) { - return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(a.data || a.options) + return debug; } +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ -const question = exports.question = {} -question.encode = function (q, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(question.encodingLength(q)) - if (!offset) offset = 0 +function enable(namespaces) { + exports.save(namespaces); + exports.names = []; + exports.skips = []; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - const oldOffset = offset + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings - name.encode(q.name, buf, offset) - offset += name.encode.bytes + namespaces = split[i].replace(/\*/g, '.*?'); - buf.writeUInt16BE(types.toType(q.type), offset) - offset += 2 + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} +/** + * Disable debug output. + * + * @api public + */ - buf.writeUInt16BE(classes.toClass(q.class === undefined ? 'IN' : q.class), offset) - offset += 2 - question.encode.bytes = offset - oldOffset - return q +function disable() { + exports.enable(''); } +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ -question.encode.bytes = 0 - -question.decode = function (buf, offset) { - if (!offset) offset = 0 - const oldOffset = offset - const q = {} +function enabled(name) { + var i, len; - q.name = name.decode(buf, offset) - offset += name.decode.bytes + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } - q.type = types.toString(buf.readUInt16BE(offset)) - offset += 2 + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } - q.class = classes.toString(buf.readUInt16BE(offset)) - offset += 2 + return false; +} +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - const qu = !!(q.class & QU_MASK) - if (qu) q.class &= NOT_QU_MASK - question.decode.bytes = offset - oldOffset - return q +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; } -question.decode.bytes = 0 +},{"ms":2319}],158:[function(require,module,exports){ +"use strict"; -question.encodingLength = function (q) { - return name.encodingLength(q.name) + 4 +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); } -exports.AUTHORITATIVE_ANSWER = 1 << 10 -exports.TRUNCATED_RESPONSE = 1 << 9 -exports.RECURSION_DESIRED = 1 << 8 -exports.RECURSION_AVAILABLE = 1 << 7 -exports.AUTHENTIC_DATA = 1 << 5 -exports.CHECKING_DISABLED = 1 << 4 -exports.DNSSEC_OK = 1 << 15 +},{"./browser.js":156,"./node.js":159}],159:[function(require,module,exports){ +"use strict"; -exports.encode = function (result, buf, offset) { - if (!buf) buf = Buffer.allocUnsafe(exports.encodingLength(result)) - if (!offset) offset = 0 +/** + * Module dependencies. + */ +var tty = require('tty'); - const oldOffset = offset +var util = require('util'); +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - if (!result.questions) result.questions = [] - if (!result.answers) result.answers = [] - if (!result.authorities) result.authorities = [] - if (!result.additionals) result.additionals = [] - header.encode(result, buf, offset) - offset += header.encode.bytes +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +/** + * Colors. + */ - offset = encodeList(result.questions, question, buf, offset) - offset = encodeList(result.answers, answer, buf, offset) - offset = encodeList(result.authorities, answer, buf, offset) - offset = encodeList(result.additionals, answer, buf, offset) +exports.colors = [6, 2, 3, 4, 5, 1]; +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - exports.encode.bytes = offset - oldOffset +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) { + return k.toUpperCase(); + }); // coerce string value into JS value - return buf -} + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true;else if (/^(no|off|false|disabled)$/i.test(val)) val = false;else if (val === 'null') val = null;else val = Number(val); + obj[prop] = val; + return obj; +}, {}); +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ -exports.encode.bytes = 0 +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; -exports.decode = function (buf, offset) { - if (!offset) offset = 0 +if (1 !== fd && 2 !== fd) { + util.deprecate(function () {}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')(); +} - const oldOffset = offset - const result = header.decode(buf, offset) - offset += header.decode.bytes +var stream = 1 === fd ? process.stdout : 2 === fd ? process.stderr : createWritableStdioStream(fd); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - offset = decodeList(result.questions, question, buf, offset) - offset = decodeList(result.answers, answer, buf, offset) - offset = decodeList(result.authorities, answer, buf, offset) - offset = decodeList(result.additionals, answer, buf, offset) +function useColors() { + return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(fd); +} +/** + * Map %o to `util.inspect()`, all on a single line. + */ - exports.decode.bytes = offset - oldOffset - return result -} +exports.formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split('\n').map(function (str) { + return str.trim(); + }).join(' '); +}; +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ -exports.decode.bytes = 0 -exports.encodingLength = function (result) { - return header.encodingLength(result) + - encodingLengthList(result.questions || [], question) + - encodingLengthList(result.answers || [], answer) + - encodingLengthList(result.authorities || [], answer) + - encodingLengthList(result.additionals || [], answer) -} +exports.formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -exports.streamEncode = function (result) { - const buf = exports.encode(result) - const sbuf = Buffer.allocUnsafe(2) - sbuf.writeUInt16BE(buf.byteLength) - const combine = Buffer.concat([sbuf, buf]) - exports.streamEncode.bytes = combine.byteLength - return combine -} -exports.streamEncode.bytes = 0 +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; -exports.streamDecode = function (sbuf) { - const len = sbuf.readUInt16BE(0) - if (sbuf.byteLength < len + 2) { - // not enough data - return null + if (useColors) { + var c = this.color; + var prefix = " \x1B[3" + c + ';1m' + name + ' ' + "\x1B[0m"; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push("\x1B[3" + c + 'm+' + exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = new Date().toUTCString() + ' ' + name + ' ' + args[0]; } - const result = exports.decode(sbuf.slice(2)) - exports.streamDecode.bytes = exports.decode.bytes - return result } +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ -exports.streamDecode.bytes = 0 -function encodingLengthList (list, enc) { - let len = 0 - for (let i = 0; i < list.length; i++) len += enc.encodingLength(list[i]) - return len +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -function encodeList (list, enc, buf, offset) { - for (let i = 0; i < list.length; i++) { - enc.encode(list[i], buf, offset) - offset += enc.encode.bytes - } - return offset -} -function decodeList (list, enc, buf, offset) { - for (let i = 0; i < list.length; i++) { - list[i] = enc.decode(buf, offset) - offset += enc.decode.bytes +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; } - return offset } - -},{"./classes":197,"./opcodes":199,"./rcodes":200,"./types":201,"ip":419,"safe-buffer":1256}],199:[function(require,module,exports){ -'use strict' - -/* - * Traditional DNS header OPCODEs (4-bits) defined by IANA in - * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-5 +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -exports.toString = function (opcode) { - switch (opcode) { - case 0: return 'QUERY' - case 1: return 'IQUERY' - case 2: return 'STATUS' - case 3: return 'OPCODE_3' - case 4: return 'NOTIFY' - case 5: return 'UPDATE' - case 6: return 'OPCODE_6' - case 7: return 'OPCODE_7' - case 8: return 'OPCODE_8' - case 9: return 'OPCODE_9' - case 10: return 'OPCODE_10' - case 11: return 'OPCODE_11' - case 12: return 'OPCODE_12' - case 13: return 'OPCODE_13' - case 14: return 'OPCODE_14' - case 15: return 'OPCODE_15' - } - return 'OPCODE_' + opcode -} - -exports.toOpcode = function (code) { - switch (code.toUpperCase()) { - case 'QUERY': return 0 - case 'IQUERY': return 1 - case 'STATUS': return 2 - case 'OPCODE_3': return 3 - case 'NOTIFY': return 4 - case 'UPDATE': return 5 - case 'OPCODE_6': return 6 - case 'OPCODE_7': return 7 - case 'OPCODE_8': return 8 - case 'OPCODE_9': return 9 - case 'OPCODE_10': return 10 - case 'OPCODE_11': return 11 - case 'OPCODE_12': return 12 - case 'OPCODE_13': return 13 - case 'OPCODE_14': return 14 - case 'OPCODE_15': return 15 - } - return 0 -} - -},{}],200:[function(require,module,exports){ -'use strict' - -/* - * Traditional DNS header RCODEs (4-bits) defined by IANA in - * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml - */ -exports.toString = function (rcode) { - switch (rcode) { - case 0: return 'NOERROR' - case 1: return 'FORMERR' - case 2: return 'SERVFAIL' - case 3: return 'NXDOMAIN' - case 4: return 'NOTIMP' - case 5: return 'REFUSED' - case 6: return 'YXDOMAIN' - case 7: return 'YXRRSET' - case 8: return 'NXRRSET' - case 9: return 'NOTAUTH' - case 10: return 'NOTZONE' - case 11: return 'RCODE_11' - case 12: return 'RCODE_12' - case 13: return 'RCODE_13' - case 14: return 'RCODE_14' - case 15: return 'RCODE_15' - } - return 'RCODE_' + rcode +function load() { + return process.env.DEBUG; } +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ -exports.toRcode = function (code) { - switch (code.toUpperCase()) { - case 'NOERROR': return 0 - case 'FORMERR': return 1 - case 'SERVFAIL': return 2 - case 'NXDOMAIN': return 3 - case 'NOTIMP': return 4 - case 'REFUSED': return 5 - case 'YXDOMAIN': return 6 - case 'YXRRSET': return 7 - case 'NXRRSET': return 8 - case 'NOTAUTH': return 9 - case 'NOTZONE': return 10 - case 'RCODE_11': return 11 - case 'RCODE_12': return 12 - case 'RCODE_13': return 13 - case 'RCODE_14': return 14 - case 'RCODE_15': return 15 - } - return 0 -} - -},{}],201:[function(require,module,exports){ -'use strict' - -exports.toString = function (type) { - switch (type) { - case 1: return 'A' - case 10: return 'NULL' - case 28: return 'AAAA' - case 18: return 'AFSDB' - case 42: return 'APL' - case 257: return 'CAA' - case 60: return 'CDNSKEY' - case 59: return 'CDS' - case 37: return 'CERT' - case 5: return 'CNAME' - case 49: return 'DHCID' - case 32769: return 'DLV' - case 39: return 'DNAME' - case 48: return 'DNSKEY' - case 43: return 'DS' - case 55: return 'HIP' - case 13: return 'HINFO' - case 45: return 'IPSECKEY' - case 25: return 'KEY' - case 36: return 'KX' - case 29: return 'LOC' - case 15: return 'MX' - case 35: return 'NAPTR' - case 2: return 'NS' - case 47: return 'NSEC' - case 50: return 'NSEC3' - case 51: return 'NSEC3PARAM' - case 12: return 'PTR' - case 46: return 'RRSIG' - case 17: return 'RP' - case 24: return 'SIG' - case 6: return 'SOA' - case 99: return 'SPF' - case 33: return 'SRV' - case 44: return 'SSHFP' - case 32768: return 'TA' - case 249: return 'TKEY' - case 52: return 'TLSA' - case 250: return 'TSIG' - case 16: return 'TXT' - case 252: return 'AXFR' - case 251: return 'IXFR' - case 41: return 'OPT' - case 255: return 'ANY' - } - return 'UNKNOWN_' + type -} -exports.toType = function (name) { - switch (name.toUpperCase()) { - case 'A': return 1 - case 'NULL': return 10 - case 'AAAA': return 28 - case 'AFSDB': return 18 - case 'APL': return 42 - case 'CAA': return 257 - case 'CDNSKEY': return 60 - case 'CDS': return 59 - case 'CERT': return 37 - case 'CNAME': return 5 - case 'DHCID': return 49 - case 'DLV': return 32769 - case 'DNAME': return 39 - case 'DNSKEY': return 48 - case 'DS': return 43 - case 'HIP': return 55 - case 'HINFO': return 13 - case 'IPSECKEY': return 45 - case 'KEY': return 25 - case 'KX': return 36 - case 'LOC': return 29 - case 'MX': return 15 - case 'NAPTR': return 35 - case 'NS': return 2 - case 'NSEC': return 47 - case 'NSEC3': return 50 - case 'NSEC3PARAM': return 51 - case 'PTR': return 12 - case 'RRSIG': return 46 - case 'RP': return 17 - case 'SIG': return 24 - case 'SOA': return 6 - case 'SPF': return 99 - case 'SRV': return 33 - case 'SSHFP': return 44 - case 'TA': return 32768 - case 'TKEY': return 249 - case 'TLSA': return 52 - case 'TSIG': return 250 - case 'TXT': return 16 - case 'AXFR': return 252 - case 'IXFR': return 251 - case 'OPT': return 41 - case 'ANY': return 255 - case '*': return 255 - } - return 0 -} - -},{}],202:[function(require,module,exports){ -var stream = require('readable-stream') -var eos = require('end-of-stream') -var inherits = require('inherits') -var shift = require('stream-shift') - -var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) - ? Buffer.from([0]) - : new Buffer([0]) - -var onuncork = function(self, fn) { - if (self._corked) self.once('uncork', fn) - else fn() -} - -var autoDestroy = function (self, err) { - if (self._autoDestroy) self.destroy(err) -} - -var destroyer = function(self, end) { - return function(err) { - if (err) autoDestroy(self, err.message === 'premature close' ? null : err) - else if (end && !self._ended) self.end() - } -} - -var end = function(ws, fn) { - if (!ws) return fn() - if (ws._writableState && ws._writableState.finished) return fn() - if (ws._writableState) return ws.end(fn) - ws.end() - fn() -} - -var toStreams2 = function(rs) { - return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) -} - -var Duplexify = function(writable, readable, opts) { - if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) - stream.Duplex.call(this, opts) - - this._writable = null - this._readable = null - this._readable2 = null - - this._autoDestroy = !opts || opts.autoDestroy !== false - this._forwardDestroy = !opts || opts.destroy !== false - this._forwardEnd = !opts || opts.end !== false - this._corked = 1 // start corked - this._ondrain = null - this._drained = false - this._forwarding = false - this._unwrite = null - this._unread = null - this._ended = false - - this.destroyed = false - - if (writable) this.setWritable(writable) - if (readable) this.setReadable(readable) -} +function createWritableStdioStream(fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); // Note stream._type is used for test-module-load-list.js -inherits(Duplexify, stream.Duplex) + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 -Duplexify.obj = function(writable, readable, opts) { - if (!opts) opts = {} - opts.objectMode = true - opts.highWaterMark = 16 - return new Duplexify(writable, readable, opts) -} + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } -Duplexify.prototype.cork = function() { - if (++this._corked === 1) this.emit('cork') -} + break; -Duplexify.prototype.uncork = function() { - if (this._corked && --this._corked === 0) this.emit('uncork') -} + case 'FILE': + var fs = require('fs'); -Duplexify.prototype.setWritable = function(writable) { - if (this._unwrite) this._unwrite() + stream = new fs.SyncWriteStream(fd, { + autoClose: false + }); + stream._type = 'fs'; + break; - if (this.destroyed) { - if (writable && writable.destroy) writable.destroy() - return - } + case 'PIPE': + case 'TCP': + var net = require('net'); - if (writable === null || writable === false) { - this.end() - return - } + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd - var self = this - var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 - var ondrain = function() { - var ondrain = self._ondrain - self._ondrain = null - if (ondrain) ondrain() - } + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } - var clear = function() { - self._writable.removeListener('drain', ondrain) - unend() - } + break; - if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } // For supporting legacy API we put the FD here. - this._writable = writable - this._writable.on('drain', ondrain) - this._unwrite = clear - this.uncork() // always uncork setWritable + stream.fd = fd; + stream._isStdio = true; + return stream; } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -Duplexify.prototype.setReadable = function(readable) { - if (this._unread) this._unread() - - if (this.destroyed) { - if (readable && readable.destroy) readable.destroy() - return - } - - if (readable === null || readable === false) { - this.push(null) - this.resume() - return - } - var self = this - var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) +function init(debug) { + debug.inspectOpts = {}; + var keys = Object.keys(exports.inspectOpts); - var onreadable = function() { - self._forward() + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } +} +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - var onend = function() { - self.push(null) - } - var clear = function() { - self._readable2.removeListener('readable', onreadable) - self._readable2.removeListener('end', onend) - unend() - } +exports.enable(load()); - this._drained = true - this._readable = readable - this._readable2 = readable._readableState ? readable : toStreams2(readable) - this._readable2.on('readable', onreadable) - this._readable2.on('end', onend) - this._unread = clear +},{"./debug":157,"fs":undefined,"net":undefined,"tty":undefined,"util":undefined}],160:[function(require,module,exports){ +module.exports={ + "OP_FALSE": 0, + "OP_0": 0, + "OP_PUSHDATA1": 76, + "OP_PUSHDATA2": 77, + "OP_PUSHDATA4": 78, + "OP_1NEGATE": 79, + "OP_RESERVED": 80, + "OP_TRUE": 81, + "OP_1": 81, + "OP_2": 82, + "OP_3": 83, + "OP_4": 84, + "OP_5": 85, + "OP_6": 86, + "OP_7": 87, + "OP_8": 88, + "OP_9": 89, + "OP_10": 90, + "OP_11": 91, + "OP_12": 92, + "OP_13": 93, + "OP_14": 94, + "OP_15": 95, + "OP_16": 96, - this._forward() -} + "OP_NOP": 97, + "OP_VER": 98, + "OP_IF": 99, + "OP_NOTIF": 100, + "OP_VERIF": 101, + "OP_VERNOTIF": 102, + "OP_ELSE": 103, + "OP_ENDIF": 104, + "OP_VERIFY": 105, + "OP_RETURN": 106, -Duplexify.prototype._read = function() { - this._drained = true - this._forward() -} + "OP_TOALTSTACK": 107, + "OP_FROMALTSTACK": 108, + "OP_2DROP": 109, + "OP_2DUP": 110, + "OP_3DUP": 111, + "OP_2OVER": 112, + "OP_2ROT": 113, + "OP_2SWAP": 114, + "OP_IFDUP": 115, + "OP_DEPTH": 116, + "OP_DROP": 117, + "OP_DUP": 118, + "OP_NIP": 119, + "OP_OVER": 120, + "OP_PICK": 121, + "OP_ROLL": 122, + "OP_ROT": 123, + "OP_SWAP": 124, + "OP_TUCK": 125, -Duplexify.prototype._forward = function() { - if (this._forwarding || !this._readable2 || !this._drained) return - this._forwarding = true + "OP_CAT": 126, + "OP_SUBSTR": 127, + "OP_LEFT": 128, + "OP_RIGHT": 129, + "OP_SIZE": 130, - var data + "OP_INVERT": 131, + "OP_AND": 132, + "OP_OR": 133, + "OP_XOR": 134, + "OP_EQUAL": 135, + "OP_EQUALVERIFY": 136, + "OP_RESERVED1": 137, + "OP_RESERVED2": 138, - while (this._drained && (data = shift(this._readable2)) !== null) { - if (this.destroyed) continue - this._drained = this.push(data) - } + "OP_1ADD": 139, + "OP_1SUB": 140, + "OP_2MUL": 141, + "OP_2DIV": 142, + "OP_NEGATE": 143, + "OP_ABS": 144, + "OP_NOT": 145, + "OP_0NOTEQUAL": 146, + "OP_ADD": 147, + "OP_SUB": 148, + "OP_MUL": 149, + "OP_DIV": 150, + "OP_MOD": 151, + "OP_LSHIFT": 152, + "OP_RSHIFT": 153, - this._forwarding = false -} + "OP_BOOLAND": 154, + "OP_BOOLOR": 155, + "OP_NUMEQUAL": 156, + "OP_NUMEQUALVERIFY": 157, + "OP_NUMNOTEQUAL": 158, + "OP_LESSTHAN": 159, + "OP_GREATERTHAN": 160, + "OP_LESSTHANOREQUAL": 161, + "OP_GREATERTHANOREQUAL": 162, + "OP_MIN": 163, + "OP_MAX": 164, -Duplexify.prototype.destroy = function(err) { - if (this.destroyed) return - this.destroyed = true + "OP_WITHIN": 165, - var self = this - process.nextTick(function() { - self._destroy(err) - }) -} + "OP_RIPEMD160": 166, + "OP_SHA1": 167, + "OP_SHA256": 168, + "OP_HASH160": 169, + "OP_HASH256": 170, + "OP_CODESEPARATOR": 171, + "OP_CHECKSIG": 172, + "OP_CHECKSIGVERIFY": 173, + "OP_CHECKMULTISIG": 174, + "OP_CHECKMULTISIGVERIFY": 175, -Duplexify.prototype._destroy = function(err) { - if (err) { - var ondrain = this._ondrain - this._ondrain = null - if (ondrain) ondrain(err) - else this.emit('error', err) - } + "OP_NOP1": 176, + + "OP_NOP2": 177, + "OP_CHECKLOCKTIMEVERIFY": 177, - if (this._forwardDestroy) { - if (this._readable && this._readable.destroy) this._readable.destroy() - if (this._writable && this._writable.destroy) this._writable.destroy() - } + "OP_NOP3": 178, + "OP_CHECKSEQUENCEVERIFY": 178, + + "OP_NOP4": 179, + "OP_NOP5": 180, + "OP_NOP6": 181, + "OP_NOP7": 182, + "OP_NOP8": 183, + "OP_NOP9": 184, + "OP_NOP10": 185, - this.emit('close') + "OP_PUBKEYHASH": 253, + "OP_PUBKEY": 254, + "OP_INVALIDOPCODE": 255 } -Duplexify.prototype._write = function(data, enc, cb) { - if (this.destroyed) return cb() - if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) - if (data === SIGNAL_FLUSH) return this._finish(cb) - if (!this._writable) return cb() - - if (this._writable.write(data) === false) this._ondrain = cb - else cb() -} +},{}],161:[function(require,module,exports){ +"use strict"; +var OPS = require('./index.json'); -Duplexify.prototype._finish = function(cb) { - var self = this - this.emit('preend') - onuncork(this, function() { - end(self._forwardEnd && self._writable, function() { - // haxx to not emit prefinish twice - if (self._writableState.prefinished === false) self._writableState.prefinished = true - self.emit('prefinish') - onuncork(self, cb) - }) - }) -} +var map = {}; -Duplexify.prototype.end = function(data, enc, cb) { - if (typeof data === 'function') return this.end(null, null, data) - if (typeof enc === 'function') return this.end(data, null, enc) - this._ended = true - if (data) this.write(data) - if (!this._writableState.ending) this.write(SIGNAL_FLUSH) - return stream.Writable.prototype.end.call(this, cb) +for (var op in OPS) { + var code = OPS[op]; + map[code] = op; } -module.exports = Duplexify +module.exports = map; -},{"end-of-stream":232,"inherits":401,"readable-stream":1239,"stream-shift":1302}],203:[function(require,module,exports){ -var assert = require('assert') -var BigInteger = require('bigi') +},{"./index.json":160}],162:[function(require,module,exports){ +'use strict'; -var Point = require('./point') +Object.defineProperty(exports, '__esModule', { + value: true +}); -function Curve (p, a, b, Gx, Gy, n, h) { - this.p = p - this.a = a - this.b = b - this.G = Point.fromAffine(this, Gx, Gy) - this.n = n - this.h = h +var networks = require('./networks'); - this.infinity = new Point(this, null, null, BigInteger.ZERO) +var payments = require('./payments'); - // result caching - this.pOverFour = p.add(BigInteger.ONE).shiftRight(2) +var bscript = require('./script'); - // determine size of p in bytes - this.pLength = Math.floor((this.p.bitLength() + 7) / 8) -} +var types = require('./types'); -Curve.prototype.pointFromX = function (isOdd, x) { - var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p) - var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves +var bech32 = require('bech32'); - var y = beta - if (beta.isEven() ^ !isOdd) { - y = this.p.subtract(y) // -y % p - } +var bs58check = require('bs58check'); - return Point.fromAffine(this, x, y) -} +var typeforce = require('typeforce'); -Curve.prototype.isInfinity = function (Q) { - if (Q === this.infinity) return true +function fromBase58Check(address) { + var payload = bs58check.decode(address); // TODO: 4.0.0, move to "toOutputScript" - return Q.z.signum() === 0 && Q.y.signum() !== 0 + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + var version = payload.readUInt8(0); + var hash = payload.slice(1); + return { + version: version, + hash: hash + }; } -Curve.prototype.isOnCurve = function (Q) { - if (this.isInfinity(Q)) return true +exports.fromBase58Check = fromBase58Check; - var x = Q.affineX - var y = Q.affineY - var a = this.a - var b = this.b - var p = this.p +function fromBech32(address) { + var result = bech32.decode(address); + var data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer.from(data) + }; +} - // Check that xQ and yQ are integers in the interval [0, p - 1] - if (x.signum() < 0 || x.compareTo(p) >= 0) return false - if (y.signum() < 0 || y.compareTo(p) >= 0) return false +exports.fromBech32 = fromBech32; - // and check that y^2 = x^3 + ax + b (mod p) - var lhs = y.square().mod(p) - var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p) - return lhs.equals(rhs) +function toBase58Check(hash, version) { + typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments); + var payload = Buffer.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); } -/** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive - */ -Curve.prototype.validate = function (Q) { - // Check Q != O - assert(!this.isInfinity(Q), 'Point is at infinity') - assert(this.isOnCurve(Q), 'Point is not on the curve') - - // Check nQ = O (where Q is a scalar multiple of G) - var nQ = Q.multiply(this.n) - assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G') +exports.toBase58Check = toBase58Check; - return true +function toBech32(data, version, prefix) { + var words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); } -module.exports = Curve +exports.toBech32 = toBech32; -},{"./point":207,"assert":undefined,"bigi":77}],204:[function(require,module,exports){ -module.exports={ - "secp128r1": { - "p": "fffffffdffffffffffffffffffffffff", - "a": "fffffffdfffffffffffffffffffffffc", - "b": "e87579c11079f43dd824993c2cee5ed3", - "n": "fffffffe0000000075a30d1b9038a115", - "h": "01", - "Gx": "161ff7528b899b2d0c28607ca52c5b86", - "Gy": "cf5ac8395bafeb13c02da292dded7a83" - }, - "secp160k1": { - "p": "fffffffffffffffffffffffffffffffeffffac73", - "a": "00", - "b": "07", - "n": "0100000000000000000001b8fa16dfab9aca16b6b3", - "h": "01", - "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb", - "Gy": "938cf935318fdced6bc28286531733c3f03c4fee" - }, - "secp160r1": { - "p": "ffffffffffffffffffffffffffffffff7fffffff", - "a": "ffffffffffffffffffffffffffffffff7ffffffc", - "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45", - "n": "0100000000000000000001f4c8f927aed3ca752257", - "h": "01", - "Gx": "4a96b5688ef573284664698968c38bb913cbfc82", - "Gy": "23a628553168947d59dcc912042351377ac5fb32" - }, - "secp192k1": { - "p": "fffffffffffffffffffffffffffffffffffffffeffffee37", - "a": "00", - "b": "03", - "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d", - "h": "01", - "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d", - "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d" - }, - "secp192r1": { - "p": "fffffffffffffffffffffffffffffffeffffffffffffffff", - "a": "fffffffffffffffffffffffffffffffefffffffffffffffc", - "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", - "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831", - "h": "01", - "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", - "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811" - }, - "secp256k1": { - "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", - "a": "00", - "b": "07", - "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", - "h": "01", - "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", - "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8" - }, - "secp256r1": { - "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", - "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", - "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", - "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", - "h": "01", - "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", - "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5" - } -} - -},{}],205:[function(require,module,exports){ -var Point = require('./point') -var Curve = require('./curve') - -var getCurveByName = require('./names') - -module.exports = { - Curve: Curve, - Point: Point, - getCurveByName: getCurveByName -} +function fromOutputScript(output, network) { + // TODO: Network + network = network || networks.bitcoin; -},{"./curve":203,"./names":206,"./point":207}],206:[function(require,module,exports){ -var BigInteger = require('bigi') + try { + return payments.p2pkh({ + output: output, + network: network + }).address; + } catch (e) {} -var curves = require('./curves.json') -var Curve = require('./curve') + try { + return payments.p2sh({ + output: output, + network: network + }).address; + } catch (e) {} -function getCurveByName (name) { - var curve = curves[name] - if (!curve) return null + try { + return payments.p2wpkh({ + output: output, + network: network + }).address; + } catch (e) {} - var p = new BigInteger(curve.p, 16) - var a = new BigInteger(curve.a, 16) - var b = new BigInteger(curve.b, 16) - var n = new BigInteger(curve.n, 16) - var h = new BigInteger(curve.h, 16) - var Gx = new BigInteger(curve.Gx, 16) - var Gy = new BigInteger(curve.Gy, 16) + try { + return payments.p2wsh({ + output: output, + network: network + }).address; + } catch (e) {} - return new Curve(p, a, b, Gx, Gy, n, h) + throw new Error(bscript.toASM(output) + ' has no matching Address'); } -module.exports = getCurveByName +exports.fromOutputScript = fromOutputScript; -},{"./curve":203,"./curves.json":204,"bigi":77}],207:[function(require,module,exports){ -var assert = require('assert') -var Buffer = require('safe-buffer').Buffer -var BigInteger = require('bigi') +function toOutputScript(address, network) { + network = network || networks.bitcoin; + var decodeBase58; + var decodeBech32; -var THREE = BigInteger.valueOf(3) + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) return payments.p2pkh({ + hash: decodeBase58.hash + }).output; + if (decodeBase58.version === network.scriptHash) return payments.p2sh({ + hash: decodeBase58.hash + }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} -function Point (curve, x, y, z) { - assert.notStrictEqual(z, undefined, 'Missing Z coordinate') + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) throw new Error(address + ' has an invalid prefix'); - this.curve = curve - this.x = x - this.y = y - this.z = z - this._zInv = null + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) return payments.p2wpkh({ + hash: decodeBech32.data + }).output; + if (decodeBech32.data.length === 32) return payments.p2wsh({ + hash: decodeBech32.data + }).output; + } + } + } - this.compressed = true + throw new Error(address + ' has no matching Script'); } -Object.defineProperty(Point.prototype, 'zInv', { - get: function () { - if (this._zInv === null) { - this._zInv = this.z.modInverse(this.curve.p) - } +exports.toOutputScript = toOutputScript; - return this._zInv - } -}) +},{"./networks":169,"./payments":171,"./script":179,"./types":205,"bech32":145,"bs58check":263,"typeforce":2945}],163:[function(require,module,exports){ +'use strict'; -Object.defineProperty(Point.prototype, 'affineX', { - get: function () { - return this.x.multiply(this.zInv).mod(this.curve.p) - } -}) +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -Object.defineProperty(Point.prototype, 'affineY', { - get: function () { - return this.y.multiply(this.zInv).mod(this.curve.p) - } -}) +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -Point.fromAffine = function (curve, x, y) { - return new Point(curve, x, y, BigInteger.ONE) -} +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -Point.prototype.equals = function (other) { - if (other === this) return true - if (this.curve.isInfinity(this)) return this.curve.isInfinity(other) - if (this.curve.isInfinity(other)) return this.curve.isInfinity(this) +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - // u = Y2 * Z1 - Y1 * Z2 - var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p) +Object.defineProperty(exports, '__esModule', { + value: true +}); - if (u.signum() !== 0) return false +var bufferutils_1 = require('./bufferutils'); - // v = X2 * Z1 - X1 * Z2 - var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p) +var bcrypto = require('./crypto'); - return v.signum() === 0 -} +var transaction_1 = require('./transaction'); -Point.prototype.negate = function () { - var y = this.curve.p.subtract(this.y) +var types = require('./types'); - return new Point(this.curve, this.x, y, this.z) -} +var fastMerkleRoot = require('merkle-lib/fastRoot'); -Point.prototype.add = function (b) { - if (this.curve.isInfinity(this)) return b - if (this.curve.isInfinity(b)) return this +var typeforce = require('typeforce'); - var x1 = this.x - var y1 = this.y - var x2 = b.x - var y2 = b.y +var varuint = require('varuint-bitcoin'); - // u = Y2 * Z1 - Y1 * Z2 - var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p) - // v = X2 * Z1 - X1 * Z2 - var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p) +var errorMerkleNoTxes = new TypeError('Cannot compute merkle root for zero transactions'); +var errorWitnessNotSegwit = new TypeError('Cannot compute witness commit for non-segwit block'); - if (v.signum() === 0) { - if (u.signum() === 0) { - return this.twice() // this == b, so double - } +var Block = +/*#__PURE__*/ +function () { + function Block() { + _classCallCheck(this, Block); - return this.curve.infinity // this = -b, so infinity + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; } - var v2 = v.square() - var v3 = v2.multiply(v) - var x1v2 = x1.multiply(v2) - var zu2 = u.square().multiply(this.z) + _createClass(Block, [{ + key: "getWitnessCommit", + value: function getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p) - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p) - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p) + var witnessCommits = this.transactions[0].outs.filter(function (out) { + return out.script.slice(0, 6).equals(Buffer.from('6a24aa21a9ed', 'hex')); + }).map(function (out) { + return out.script.slice(6, 38); + }); + if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) - return new Point(this.curve, x3, y3, z3) -} + var result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer && result.length === 32)) return null; + return result; + } + }, { + key: "hasWitnessCommit", + value: function hasWitnessCommit() { + if (this.witnessCommit instanceof Buffer && this.witnessCommit.length === 32) return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + }, { + key: "hasWitness", + value: function hasWitness() { + return anyTxHasWitness(this.transactions); + } + }, { + key: "byteLength", + value: function byteLength(headersOnly) { + if (headersOnly || !this.transactions) return 80; + return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) { + return a + x.byteLength(); + }, 0); + } + }, { + key: "getHash", + value: function getHash() { + return bcrypto.hash256(this.toBuffer(true)); + } + }, { + key: "getId", + value: function getId() { + return bufferutils_1.reverseBuffer(this.getHash()).toString('hex'); + } + }, { + key: "getUTCDate", + value: function getUTCDate() { + var date = new Date(0); // epoch -Point.prototype.twice = function () { - if (this.curve.isInfinity(this)) return this - if (this.y.signum() === 0) return this.curve.infinity + date.setUTCSeconds(this.timestamp); + return date; + } // TODO: buffer, offset compatibility - var x1 = this.x - var y1 = this.y + }, { + key: "toBuffer", + value: function toBuffer(headersOnly) { + var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)); + var offset = 0; + + var writeSlice = function writeSlice(slice) { + slice.copy(buffer, offset); + offset += slice.length; + }; - var y1z1 = y1.multiply(this.z).mod(this.curve.p) - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p) - var a = this.curve.a + var writeInt32 = function writeInt32(i) { + buffer.writeInt32LE(i, offset); + offset += 4; + }; - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE) + var writeUInt32 = function writeUInt32(i) { + buffer.writeUInt32LE(i, offset); + offset += 4; + }; - if (a.signum() !== 0) { - w = w.add(this.z.square().multiply(a)) - } + writeInt32(this.version); + writeSlice(this.prevHash); + writeSlice(this.merkleRoot); + writeUInt32(this.timestamp); + writeUInt32(this.bits); + writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint.encode(this.transactions.length, buffer, offset); + offset += varuint.encode.bytes; + this.transactions.forEach(function (tx) { + var txSize = tx.byteLength(); // TODO: extract from toBuffer? + + tx.toBuffer(buffer, offset); + offset += txSize; + }); + return buffer; + } + }, { + key: "toHex", + value: function toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); + } + }, { + key: "checkTxRoots", + value: function checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + var hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return this.__checkMerkleRoot() && (hasWitnessCommit ? this.__checkWitnessCommit() : true); + } + }, { + key: "checkProofOfWork", + value: function checkProofOfWork() { + var hash = bufferutils_1.reverseBuffer(this.getHash()); + var target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; + } + }, { + key: "__checkMerkleRoot", + value: function __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; + } + }, { + key: "__checkWitnessCommit", + value: function __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + var actualWitnessCommit = Block.calculateMerkleRoot(this.transactions, true); + return this.witnessCommit.compare(actualWitnessCommit) === 0; + } + }], [{ + key: "fromBuffer", + value: function fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + var offset = 0; + + var readSlice = function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + }; - w = w.mod(this.curve.p) - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p) - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p) - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p) + var readUInt32 = function readUInt32() { + var i = buffer.readUInt32LE(offset); + offset += 4; + return i; + }; - return new Point(this.curve, x3, y3, z3) -} + var readInt32 = function readInt32() { + var i = buffer.readInt32LE(offset); + offset += 4; + return i; + }; -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -Point.prototype.multiply = function (k) { - if (this.curve.isInfinity(this)) return this - if (k.signum() === 0) return this.curve.infinity + var block = new Block(); + block.version = readInt32(); + block.prevHash = readSlice(32); + block.merkleRoot = readSlice(32); + block.timestamp = readUInt32(); + block.bits = readUInt32(); + block.nonce = readUInt32(); + if (buffer.length === 80) return block; + + var readVarInt = function readVarInt() { + var vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; + }; - var e = k - var h = e.multiply(THREE) + var readTransaction = function readTransaction() { + var tx = transaction_1.Transaction.fromBuffer(buffer.slice(offset), true); + offset += tx.byteLength(); + return tx; + }; - var neg = this.negate() - var R = this + var nTransactions = readVarInt(); + block.transactions = []; - for (var i = h.bitLength() - 2; i > 0; --i) { - var hBit = h.testBit(i) - var eBit = e.testBit(i) + for (var i = 0; i < nTransactions; ++i) { + var tx = readTransaction(); + block.transactions.push(tx); + } - R = R.twice() + var witnessCommit = block.getWitnessCommit(); // This Block contains a witness commit - if (hBit !== eBit) { - R = R.add(hBit ? this : neg) + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; } - } + }, { + key: "fromHex", + value: function fromHex(hex) { + return Block.fromBuffer(Buffer.from(hex, 'hex')); + } + }, { + key: "calculateTarget", + value: function calculateTarget(bits) { + var exponent = ((bits & 0xff000000) >> 24) - 3; + var mantissa = bits & 0x007fffff; + var target = Buffer.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; + } + }, { + key: "calculateMerkleRoot", + value: function calculateMerkleRoot(transactions, forWitness) { + typeforce([{ + getHash: types.Function + }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) throw errorWitnessNotSegwit; + var hashes = transactions.map(function (transaction) { + return transaction.getHash(forWitness); + }); + var rootHash = fastMerkleRoot(hashes, bcrypto.hash256); + return forWitness ? bcrypto.hash256(Buffer.concat([rootHash, transactions[0].ins[0].witness[0]])) : rootHash; + } + }]); + + return Block; +}(); - return R +exports.Block = Block; + +function txesHaveWitnessCommit(transactions) { + return transactions instanceof Array && transactions[0] && transactions[0].ins && transactions[0].ins instanceof Array && transactions[0].ins[0] && transactions[0].ins[0].witness && transactions[0].ins[0].witness instanceof Array && transactions[0].ins[0].witness.length > 0; } -// Compute this*j + x*k (simultaneous multiplication) -Point.prototype.multiplyTwo = function (j, x, k) { - var i = Math.max(j.bitLength(), k.bitLength()) - 1 - var R = this.curve.infinity - var both = this.add(x) +function anyTxHasWitness(transactions) { + return transactions instanceof Array && transactions.some(function (tx) { + return _typeof(tx) === 'object' && tx.ins instanceof Array && tx.ins.some(function (input) { + return _typeof(input) === 'object' && input.witness instanceof Array && input.witness.length > 0; + }); + }); +} - while (i >= 0) { - var jBit = j.testBit(i) - var kBit = k.testBit(i) +},{"./bufferutils":164,"./crypto":166,"./transaction":203,"./types":205,"merkle-lib/fastRoot":2294,"typeforce":2945,"varuint-bitcoin":2969}],164:[function(require,module,exports){ +'use strict'; - R = R.twice() +Object.defineProperty(exports, '__esModule', { + value: true +}); // https://github.com/feross/buffer/blob/master/index.js#L1127 - if (jBit) { - if (kBit) { - R = R.add(both) - } else { - R = R.add(this) - } - } else if (kBit) { - R = R.add(x) - } - --i - } +function verifuint(value, max) { + if (typeof value !== 'number') throw new Error('cannot write a non-number as a number'); + if (value < 0) throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) throw new Error('value has a fractional component'); +} - return R +function readUInt64LE(buffer, offset) { + var a = buffer.readUInt32LE(offset); + var b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; } -Point.prototype.getEncoded = function (compressed) { - if (compressed == null) compressed = this.compressed - if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00' +exports.readUInt64LE = readUInt64LE; - var x = this.affineX - var y = this.affineY - var byteLength = this.curve.pLength - var buffer +function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; +} - // 0x02/0x03 | X - if (compressed) { - buffer = Buffer.allocUnsafe(1 + byteLength) - buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) +exports.writeUInt64LE = writeUInt64LE; - // 0x04 | X | Y - } else { - buffer = Buffer.allocUnsafe(1 + byteLength + byteLength) - buffer.writeUInt8(0x04, 0) +function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + var j = buffer.length - 1; + var tmp = 0; - y.toBuffer(byteLength).copy(buffer, 1 + byteLength) + for (var i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; } - x.toBuffer(byteLength).copy(buffer, 1) - - return buffer + return buffer; } -Point.decodeFrom = function (curve, buffer) { - var type = buffer.readUInt8(0) - var compressed = (type !== 4) +exports.reverseBuffer = reverseBuffer; - var byteLength = Math.floor((curve.p.bitLength() + 7) / 8) - var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength)) +},{}],165:[function(require,module,exports){ +'use strict'; - var Q - if (compressed) { - assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length') - assert(type === 0x02 || type === 0x03, 'Invalid sequence tag') +Object.defineProperty(exports, '__esModule', { + value: true +}); - var isOdd = (type === 0x03) - Q = curve.pointFromX(isOdd, x) - } else { - assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length') +var script_1 = require('./script'); - var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength)) - Q = Point.fromAffine(curve, x, y) - } +var multisig = require('./templates/multisig'); - Q.compressed = compressed - return Q -} +var nullData = require('./templates/nulldata'); -Point.prototype.toString = function () { - if (this.curve.isInfinity(this)) return '(INFINITY)' +var pubKey = require('./templates/pubkey'); - return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')' -} +var pubKeyHash = require('./templates/pubkeyhash'); -module.exports = Point +var scriptHash = require('./templates/scripthash'); -},{"assert":undefined,"bigi":77,"safe-buffer":1256}],208:[function(require,module,exports){ -/*! - * ee-first - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ +var witnessCommitment = require('./templates/witnesscommitment'); -'use strict' +var witnessPubKeyHash = require('./templates/witnesspubkeyhash'); -/** - * Module exports. - * @public - */ +var witnessScriptHash = require('./templates/witnessscripthash'); -module.exports = first +var types = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment' +}; +exports.types = types; -/** - * Get the first event in a set of event emitters and event pairs. - * - * @param {array} stuff - * @param {function} done - * @public - */ +function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types.P2WPKH; + if (witnessScriptHash.output.check(script)) return types.P2WSH; + if (pubKeyHash.output.check(script)) return types.P2PKH; + if (scriptHash.output.check(script)) return types.P2SH; // XXX: optimization, below functions .decompile before use -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') + var chunks = script_1.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types.P2MS; + if (pubKey.output.check(chunks)) return types.P2PK; + if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types.NULLDATA; + return types.NONSTANDARD; +} - var cleanups = [] +exports.output = classifyOutput; - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] +function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + var chunks = script_1.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types.P2MS; + if (pubKey.input.check(chunks)) return types.P2PK; + return types.NONSTANDARD; +} - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') +exports.input = classifyInput; - var ee = arr[0] +function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + var chunks = script_1.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH; + return types.NONSTANDARD; +} - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) +exports.witness = classifyWitness; - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } +},{"./script":179,"./templates/multisig":182,"./templates/nulldata":185,"./templates/pubkey":186,"./templates/pubkeyhash":189,"./templates/scripthash":192,"./templates/witnesscommitment":195,"./templates/witnesspubkeyhash":197,"./templates/witnessscripthash":200}],166:[function(require,module,exports){ +'use strict'; - function callback() { - cleanup() - done.apply(null, arguments) - } +Object.defineProperty(exports, '__esModule', { + value: true +}); - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) - } - } +var createHash = require('create-hash'); - function thunk(fn) { - done = fn +function ripemd160(buffer) { + try { + return createHash('rmd160').update(buffer).digest(); + } catch (err) { + return createHash('ripemd160').update(buffer).digest(); } +} - thunk.cancel = cleanup +exports.ripemd160 = ripemd160; - return thunk +function sha1(buffer) { + return createHash('sha1').update(buffer).digest(); } -/** - * Create the event listener. - * @private - */ +exports.sha1 = sha1; -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null +function sha256(buffer) { + return createHash('sha256').update(buffer).digest(); +} - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } +exports.sha256 = sha256; - done(err, ee, event, args) - } +function hash160(buffer) { + return ripemd160(sha256(buffer)); } -},{}],209:[function(require,module,exports){ -'use strict'; - -var elliptic = exports; +exports.hash160 = hash160; -elliptic.version = require('../package.json').version; -elliptic.utils = require('./elliptic/utils'); -elliptic.rand = require('brorand'); -elliptic.curve = require('./elliptic/curve'); -elliptic.curves = require('./elliptic/curves'); +function hash256(buffer) { + return sha256(sha256(buffer)); +} -// Protocols -elliptic.ec = require('./elliptic/ec'); -elliptic.eddsa = require('./elliptic/eddsa'); +exports.hash256 = hash256; -},{"../package.json":224,"./elliptic/curve":212,"./elliptic/curves":215,"./elliptic/ec":216,"./elliptic/eddsa":219,"./elliptic/utils":223,"brorand":146}],210:[function(require,module,exports){ +},{"create-hash":620}],167:[function(require,module,exports){ 'use strict'; -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var getNAF = utils.getNAF; -var getJSF = utils.getJSF; -var assert = utils.assert; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function BaseCurve(type, conf) { - this.type = type; - this.p = new BN(conf.p, 16); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - // Useful for many curves - this.zero = new BN(0).toRed(this.red); - this.one = new BN(1).toRed(this.red); - this.two = new BN(2).toRed(this.red); +Object.defineProperty(exports, '__esModule', { + value: true +}); - // Curve configuration, optional - this.n = conf.n && new BN(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); +var NETWORKS = require('./networks'); - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); +var types = require('./types'); - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -module.exports = BaseCurve; +var ecc = require('tiny-secp256k1'); -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; +var randomBytes = require('randombytes'); -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; +var typeforce = require('typeforce'); -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert(p.precomputed); - var doubles = p._getDoubles(); +var wif = require('wif'); - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; +var isOptions = typeforce.maybe(typeforce.compile({ + compressed: types.maybe(types.Boolean), + network: types.maybe(types.Network) +})); - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } +var ECPair = +/*#__PURE__*/ +function () { + function ECPair(__D, __Q, options) { + _classCallCheck(this, ECPair); - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); + this.__D = __D; + this.__Q = __Q; + if (options === undefined) options = {}; + this.compressed = options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); } - return a.toP(); -}; - -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; + _createClass(ECPair, [{ + key: "toWIF", + value: function toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); + } + }, { + key: "sign", + value: function sign(hash) { + var lowR = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (!this.__D) throw new Error('Missing private key'); - // Get NAF form - var naf = getNAF(k, w); + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + var sig = ecc.sign(hash, this.__D); + var extraData = Buffer.alloc(32, 0); + var counter = 0; // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } - if (i < 0) - break; - var z = naf[i]; - assert(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); + return sig; + } } - } - return p.type === 'affine' ? acc.toP() : acc; -}; - -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; + }, { + key: "verify", + value: function verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + }, { + key: "privateKey", + get: function get() { + return this.__D; + } + }, { + key: "publicKey", + get: function get() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; + } + }]); - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } + return ECPair; +}(); - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; - } +function fromPrivateKey(buffer, options) { + typeforce(types.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) throw new TypeError('Private key not in range [1, n)'); + typeforce(isOptions, options); + return new ECPair(buffer, undefined, options); +} - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; +exports.fromPrivateKey = fromPrivateKey; - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } +function fromPublicKey(buffer, options) { + typeforce(ecc.isPoint, buffer); + typeforce(isOptions, options); + return new ECPair(undefined, buffer, options); +} - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; +exports.fromPublicKey = fromPublicKey; - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; +function fromWIF(wifString, network) { + var decoded = wif.decode(wifString); + var version = decoded.version; // list of networks? - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } + if (types.Array(network)) { + network = network.filter(function (x) { + return version === x.wif; + }).pop(); + if (!network) throw new Error('Unknown network version'); // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); } - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; - - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network + }); +} - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); +exports.fromWIF = fromWIF; - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; +function makeRandom(options) { + typeforce(isOptions, options); + if (options === undefined) options = {}; + var rng = options.rng || randomBytes; + var d; - if (jacobianResult) - return acc; - else - return acc.toP(); -}; + do { + d = rng(32); + typeforce(types.Buffer256bit, d); + } while (!ecc.isPrivate(d)); -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; + return fromPrivateKey(d, options); } -BaseCurve.BasePoint = BasePoint; -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; +exports.makeRandom = makeRandom; -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; +},{"./networks":169,"./types":205,"randombytes":2714,"tiny-secp256k1":2922,"typeforce":2945,"wif":2991}],168:[function(require,module,exports){ +'use strict'; -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils.toArray(bytes, enc); +Object.defineProperty(exports, '__esModule', { + value: true +}); - var len = this.p.byteLength(); +var bip32 = require('bip32'); - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert(bytes[bytes.length - 1] % 2 === 1); +exports.bip32 = bip32; - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); +var address = require('./address'); - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); - } - throw new Error('Unknown point format'); -}; +exports.address = address; -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; +var crypto = require('./crypto'); -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); +exports.crypto = crypto; - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); +var ECPair = require('./ecpair'); - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; -}; +exports.ECPair = ECPair; -BasePoint.prototype.encode = function encode(enc, compact) { - return utils.encode(this._encode(compact), enc); -}; +var networks = require('./networks'); -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; +exports.networks = networks; - var precomputed = { - doubles: null, - naf: null, - beta: null - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; +var payments = require('./payments'); - return this; -}; +exports.payments = payments; -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; +var script = require('./script'); - var doubles = this.precomputed.doubles; - if (!doubles) - return false; +exports.script = script; - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; +var block_1 = require('./block'); -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; +exports.Block = block_1.Block; - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; +var script_1 = require('./script'); -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; +exports.opcodes = script_1.OPS; - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; +var transaction_1 = require('./transaction'); -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; +exports.Transaction = transaction_1.Transaction; -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; +var transaction_builder_1 = require('./transaction_builder'); -},{"../../elliptic":209,"bn.js":125}],211:[function(require,module,exports){ -'use strict'; +exports.TransactionBuilder = transaction_builder_1.TransactionBuilder; -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; +},{"./address":162,"./block":163,"./crypto":166,"./ecpair":167,"./networks":169,"./payments":171,"./script":179,"./transaction":203,"./transaction_builder":204,"bip32":153}],169:[function(require,module,exports){ +'use strict'; -var assert = elliptic.utils.assert; +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + "public": 0x0488b21e, + "private": 0x0488ade4 + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80 +}; +exports.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + "public": 0x043587cf, + "private": 0x04358394 + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef +}; +exports.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + "public": 0x043587cf, + "private": 0x04358394 + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef +}; -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; +},{}],170:[function(require,module,exports){ +'use strict'; - Base.call(this, 'edwards', conf); +Object.defineProperty(exports, '__esModule', { + value: true +}); - this.a = new BN(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); +var networks_1 = require('../networks'); - assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits(EdwardsCurve, Base); -module.exports = EdwardsCurve; +var bscript = require('../script'); -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; +var lazy = require('./lazy'); -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); -}; +var typef = require('typeforce'); -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; +var OPS = bscript.OPS; -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every(function (x, i) { + return x.equals(b[i]); + }); +} // output: OP_RETURN ... - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); +function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ + validate: true + }, opts || {}); + typef({ + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + data: typef.maybe(typef.arrayOf(typef.Buffer)) + }, a); + var network = a.network || networks_1.bitcoin; + var o = { + network: network + }; + lazy.prop(o, 'output', function () { + if (!a.data) return; + return bscript.compile([OPS.OP_RETURN].concat(a.data)); + }); + lazy.prop(o, 'data', function () { + if (!a.output) return; + return bscript.decompile(a.output).slice(1); + }); // extended validation - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + if (opts.validate) { + if (a.output) { + var chunks = bscript.decompile(a.output); + if (chunks[0] !== OPS.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef.Buffer)) throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual(a.data, o.data)) throw new TypeError('Data mismatch'); + } + } - return this.point(x, y); -}; + return Object.assign(o, a); +} -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new BN(y, 16); - if (!y.red) - y = y.toRed(this.red); +exports.p2data = p2data; - // x^2 = (y^2 - 1) / (d y^2 + 1) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.one); - var rhs = y2.redMul(this.d).redAdd(this.one); - var x2 = lhs.redMul(rhs.redInvm()); +},{"../networks":169,"../script":179,"./lazy":172,"typeforce":2945}],171:[function(require,module,exports){ +'use strict'; - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } +Object.defineProperty(exports, '__esModule', { + value: true +}); - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); +var embed_1 = require('./embed'); - if (x.isOdd() !== odd) - x = x.redNeg(); +exports.embed = embed_1.p2data; - return this.point(x, y); -}; +var p2ms_1 = require('./p2ms'); -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; +exports.p2ms = p2ms_1.p2ms; - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); +var p2pk_1 = require('./p2pk'); - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); +exports.p2pk = p2pk_1.p2pk; - return lhs.cmp(rhs) === 0; -}; +var p2pkh_1 = require('./p2pkh'); -function Point(curve, x, y, z, t) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = z ? new BN(z, 16) : this.curve.one; - this.t = t && new BN(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits(Point, Base.BasePoint); +exports.p2pkh = p2pkh_1.p2pkh; -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; +var p2sh_1 = require('./p2sh'); -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); -}; +exports.p2sh = p2sh_1.p2sh; -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); -}; +var p2wpkh_1 = require('./p2wpkh'); -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; +exports.p2wpkh = p2wpkh_1.p2wpkh; -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - this.y.cmp(this.z) === 0; -}; +var p2wsh_1 = require('./p2wsh'); -Point.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S +exports.p2wsh = p2wsh_1.p2wsh; // TODO +// witness commitment - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; +},{"./embed":170,"./p2ms":173,"./p2pk":174,"./p2pkh":175,"./p2sh":176,"./p2wpkh":177,"./p2wsh":178}],172:[function(require,module,exports){ +'use strict'; -Point.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S +Object.defineProperty(exports, '__esModule', { + value: true +}); - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); +function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get: function get() { + var _value = f.call(this); - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); + this[name] = _value; + return _value; + }, + set: function set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true + }); } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; + }); +} -Point.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; +exports.prop = prop; - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; +function value(f) { + var _value; -Point.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M + return function () { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; +} - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; +exports.value = value; -Point.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S +},{}],173:[function(require,module,exports){ +'use strict'; - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); - } - return this.curve.point(nx, ny, nz); -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; +var networks_1 = require('../networks'); - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; +var bscript = require('../script'); -Point.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; +var lazy = require('./lazy'); -Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; +var OPS = bscript.OPS; -Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); -}; +var typef = require('typeforce'); -Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; +var ecc = require('tiny-secp256k1'); - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; +var OP_INT_BASE = OPS.OP_RESERVED; // OP_1 - 1 -Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every(function (x, i) { + return x.equals(b[i]); + }); +} // input: OP_0 [signatures ...] +// output: m [pubKeys ...] n OP_CHECKMULTISIG -Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; -Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; +function p2ms(a, opts) { + if (!a.input && !a.output && !(a.pubkeys && a.m !== undefined) && !a.signatures) throw new TypeError('Not enough data'); + opts = Object.assign({ + validate: true + }, opts || {}); + + function isAcceptableSignature(x) { + return bscript.isCanonicalScriptSignature(x) || (opts.allowIncomplete && x === OPS.OP_0) !== undefined; + } + + typef({ + network: typef.maybe(typef.Object), + m: typef.maybe(typef.Number), + n: typef.maybe(typef.Number), + output: typef.maybe(typef.Buffer), + pubkeys: typef.maybe(typef.arrayOf(ecc.isPoint)), + signatures: typef.maybe(typef.arrayOf(isAcceptableSignature)), + input: typef.maybe(typef.Buffer) + }, a); + var network = a.network || networks_1.bitcoin; + var o = { + network: network + }; + var chunks = []; + var decoded = false; + + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript.decompile(output); + o.m = chunks[0] - OP_INT_BASE; + o.n = chunks[chunks.length - 2] - OP_INT_BASE; + o.pubkeys = chunks.slice(1, -2); + } + + lazy.prop(o, 'output', function () { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript.compile([].concat(OP_INT_BASE + a.m, a.pubkeys, OP_INT_BASE + o.n, OPS.OP_CHECKMULTISIG)); + }); + lazy.prop(o, 'm', function () { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy.prop(o, 'n', function () { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy.prop(o, 'pubkeys', function () { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy.prop(o, 'signatures', function () { + if (!a.input) return; + return bscript.decompile(a.input).slice(1); + }); + lazy.prop(o, 'input', function () { + if (!a.signatures) return; + return bscript.compile([OPS.OP_0].concat(a.signatures)); + }); + lazy.prop(o, 'witness', function () { + if (!o.input) return; + return []; + }); // extended validation -Point.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef.Number(chunks[chunks.length - 2])) throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(function (x) { + return ecc.isPoint(x); + })) throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual(a.pubkeys, o.pubkeys)) throw new TypeError('Pubkeys mismatch'); + } -Point.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; + if (a.signatures) { + if (a.signatures.length < o.m) throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) throw new TypeError('Too many signatures provided'); + } - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; + if (a.input) { + if (a.input[0] !== OPS.OP_0) throw new TypeError('Input is invalid'); + if (o.signatures.length === 0 || !o.signatures.every(isAcceptableSignature)) throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual(a.signatures, o.signatures)) throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) throw new TypeError('Signature count mismatch'); + } } - return false; -}; -// Compatibility with BaseCurve -Point.prototype.toP = Point.prototype.normalize; -Point.prototype.mixedAdd = Point.prototype.add; + return Object.assign(o, a); +} + +exports.p2ms = p2ms; -},{"../../elliptic":209,"../curve":212,"bn.js":125,"inherits":401}],212:[function(require,module,exports){ +},{"../networks":169,"../script":179,"./lazy":172,"tiny-secp256k1":2922,"typeforce":2945}],174:[function(require,module,exports){ 'use strict'; -var curve = exports; +Object.defineProperty(exports, '__esModule', { + value: true +}); -curve.base = require('./base'); -curve.short = require('./short'); -curve.mont = require('./mont'); -curve.edwards = require('./edwards'); +var networks_1 = require('../networks'); -},{"./base":210,"./edwards":211,"./mont":213,"./short":214}],213:[function(require,module,exports){ -'use strict'; +var bscript = require('../script'); -var curve = require('../curve'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; +var lazy = require('./lazy'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; +var typef = require('typeforce'); -function MontCurve(conf) { - Base.call(this, 'mont', conf); +var OPS = bscript.OPS; - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.i4 = new BN(4).toRed(this.red).redInvm(); - this.two = new BN(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); -} -inherits(MontCurve, Base); -module.exports = MontCurve; +var ecc = require('tiny-secp256k1'); // input: {signature} +// output: {pubKey} OP_CHECKSIG -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); - return y.redSqr().cmp(rhs) === 0; -}; +function p2pk(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) throw new TypeError('Not enough data'); + opts = Object.assign({ + validate: true + }, opts || {}); + typef({ + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + pubkey: typef.maybe(ecc.isPoint), + signature: typef.maybe(bscript.isCanonicalScriptSignature), + input: typef.maybe(typef.Buffer) + }, a); + + var _chunks = lazy.value(function () { + return bscript.decompile(a.input); + }); -function Point(curve, x, z) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new BN(x, 16); - this.z = new BN(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); + var network = a.network || networks_1.bitcoin; + var o = { + network: network + }; + lazy.prop(o, 'output', function () { + if (!a.pubkey) return; + return bscript.compile([a.pubkey, OPS.OP_CHECKSIG]); + }); + lazy.prop(o, 'pubkey', function () { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy.prop(o, 'signature', function () { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', function () { + if (!a.signature) return; + return bscript.compile([a.signature]); + }); + lazy.prop(o, 'witness', function () { + if (!o.input) return; + return []; + }); // extended validation + + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS.OP_CHECKSIG) throw new TypeError('Output is invalid'); + if (!ecc.isPoint(o.pubkey)) throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) throw new TypeError('Pubkey mismatch'); + } + + if (a.signature) { + if (a.input && !a.input.equals(o.input)) throw new TypeError('Signature mismatch'); + } + + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(o.signature)) throw new TypeError('Input has invalid signature'); + } } + + return Object.assign(o, a); } -inherits(Point, Base.BasePoint); -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils.toArray(bytes, enc), 1); -}; +exports.p2pk = p2pk; -MontCurve.prototype.point = function point(x, z) { - return new Point(this, x, z); -}; +},{"../networks":169,"../script":179,"./lazy":172,"tiny-secp256k1":2922,"typeforce":2945}],175:[function(require,module,exports){ +'use strict'; -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -Point.prototype.precompute = function precompute() { - // No-op -}; +var bcrypto = require('../crypto'); -Point.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); -}; +var networks_1 = require('../networks'); -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1] || curve.one); -}; +var bscript = require('../script'); -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; +var lazy = require('./lazy'); -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; +var typef = require('typeforce'); -Point.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A +var OPS = bscript.OPS; - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; +var ecc = require('tiny-secp256k1'); -Point.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; +var bs58check = require('bs58check'); // input: {signature} {pubkey} +// output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG -Point.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; +function p2pkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) throw new TypeError('Not enough data'); + opts = Object.assign({ + validate: true + }, opts || {}); + typef({ + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(20)), + output: typef.maybe(typef.BufferN(25)), + pubkey: typef.maybe(ecc.isPoint), + signature: typef.maybe(bscript.isCanonicalScriptSignature), + input: typef.maybe(typef.Buffer) + }, a); + + var _address = lazy.value(function () { + var payload = bs58check.decode(a.address); + var version = payload.readUInt8(0); + var hash = payload.slice(1); + return { + version: version, + hash: hash + }; + }); -Point.prototype.mul = function mul(k) { - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q + var _chunks = lazy.value(function () { + return bscript.decompile(a.input); + }); - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); + var network = a.network || networks_1.bitcoin; + var o = { + network: network + }; + lazy.prop(o, 'address', function () { + if (!o.hash) return; + var payload = Buffer.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check.encode(payload); + }); + lazy.prop(o, 'hash', function () { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', function () { + if (!o.hash) return; + return bscript.compile([OPS.OP_DUP, OPS.OP_HASH160, o.hash, OPS.OP_EQUALVERIFY, OPS.OP_CHECKSIG]); + }); + lazy.prop(o, 'pubkey', function () { + if (!a.input) return; + return _chunks()[1]; + }); + lazy.prop(o, 'signature', function () { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', function () { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript.compile([a.signature, a.pubkey]); + }); + lazy.prop(o, 'witness', function () { + if (!o.input) return; + return []; + }); // extended validation - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); + if (opts.validate) { + var hash = Buffer.from([]); + + if (a.address) { + if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; } - } - return b; -}; -Point.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) throw new TypeError('Hash mismatch');else hash = a.hash; + } -Point.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; + if (a.output) { + if (a.output.length !== 25 || a.output[0] !== OPS.OP_DUP || a.output[1] !== OPS.OP_HASH160 || a.output[2] !== 0x14 || a.output[23] !== OPS.OP_EQUALVERIFY || a.output[24] !== OPS.OP_CHECKSIG) throw new TypeError('Output is invalid'); + var hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) throw new TypeError('Hash mismatch');else hash = hash2; + } -Point.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; + if (a.pubkey) { + var pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) throw new TypeError('Hash mismatch');else hash = pkh; + } -Point.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; + if (a.input) { + var chunks = _chunks(); -Point.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(chunks[0])) throw new TypeError('Input has invalid signature'); + if (!ecc.isPoint(chunks[1])) throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) throw new TypeError('Pubkey mismatch'); - return this.x.fromRed(); -}; + var _pkh = bcrypto.hash160(chunks[1]); -},{"../../elliptic":209,"../curve":212,"bn.js":125,"inherits":401}],214:[function(require,module,exports){ -'use strict'; + if (hash.length > 0 && !hash.equals(_pkh)) throw new TypeError('Hash mismatch'); + } + } -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var assert = elliptic.utils.assert; - -function ShortCurve(conf) { - Base.call(this, 'short', conf); - - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); + return Object.assign(o, a); } -inherits(ShortCurve, Base); -module.exports = ShortCurve; -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; +exports.p2pkh = p2pkh; - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new BN(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } - } +},{"../crypto":166,"../networks":169,"../script":179,"./lazy":172,"bs58check":263,"tiny-secp256k1":2922,"typeforce":2945}],176:[function(require,module,exports){ +'use strict'; - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN(vec.a, 16), - b: new BN(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } +Object.defineProperty(exports, '__esModule', { + value: true +}); - return { - beta: beta, - lambda: lambda, - basis: basis - }; -}; +var bcrypto = require('../crypto'); -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : BN.mont(num); - var tinv = new BN(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); +var networks_1 = require('../networks'); - var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); +var bscript = require('../script'); - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; +var lazy = require('./lazy'); -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); +var typef = require('typeforce'); - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN(1); - var y1 = new BN(0); - var x2 = new BN(0); - var y2 = new BN(1); +var OPS = bscript.OPS; - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; +var bs58check = require('bs58check'); - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every(function (x, i) { + return x.equals(b[i]); + }); +} // input: [redeemScriptSig ...] {redeemScript} +// witness: +// output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; +function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) throw new TypeError('Not enough data'); + opts = Object.assign({ + validate: true + }, opts || {}); + typef({ + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(20)), + output: typef.maybe(typef.BufferN(23)), + redeem: typef.maybe({ + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + input: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)) + }), + input: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)) + }, a); + var network = a.network; - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; + if (!network) { + network = a.redeem && a.redeem.network || networks_1.bitcoin; } - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } + var o = { + network: network + }; - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; + var _address = lazy.value(function () { + var payload = bs58check.decode(a.address); + var version = payload.readUInt8(0); + var hash = payload.slice(1); + return { + version: version, + hash: hash + }; + }); -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; + var _chunks = lazy.value(function () { + return bscript.decompile(a.input); + }); - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); + var _redeem = lazy.value(function () { + var chunks = _chunks(); - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); + return { + network: network, + output: chunks[chunks.length - 1], + input: bscript.compile(chunks.slice(0, -1)), + witness: a.witness || [] + }; + }); // output dependents - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); + lazy.prop(o, 'address', function () { + if (!o.hash) return; + var payload = Buffer.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check.encode(payload); + }); + lazy.prop(o, 'hash', function () { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto.hash160(o.redeem.output); + }); + lazy.prop(o, 'output', function () { + if (!o.hash) return; + return bscript.compile([OPS.OP_HASH160, o.hash, OPS.OP_EQUAL]); + }); // input dependents + + lazy.prop(o, 'redeem', function () { + if (!a.input) return; + return _redeem(); + }); + lazy.prop(o, 'input', function () { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript.compile([].concat(bscript.decompile(a.redeem.input), a.redeem.output)); + }); + lazy.prop(o, 'witness', function () { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + if (opts.validate) { + var hash = Buffer.from([]); - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + if (a.address) { + if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } - return this.point(x, y); -}; + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) throw new TypeError('Hash mismatch');else hash = a.hash; + } -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + if (a.output) { + if (a.output.length !== 23 || a.output[0] !== OPS.OP_HASH160 || a.output[1] !== 0x14 || a.output[22] !== OPS.OP_EQUAL) throw new TypeError('Output is invalid'); + var hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) throw new TypeError('Hash mismatch');else hash = hash2; + } // inlined to prevent 'no-inner-declarations' failing - var x = point.x; - var y = point.y; - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; + var checkRedeem = function checkRedeem(redeem) { + // is the redeem output empty/invalid? + if (redeem.output) { + var decompile = bscript.decompile(redeem.output); + if (!decompile || decompile.length < 1) throw new TypeError('Redeem.output too short'); // match hash against other sources -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); + var _hash = bcrypto.hash160(redeem.output); - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } + if (hash.length > 0 && !hash.equals(_hash)) throw new TypeError('Hash mismatch');else hash = _hash; + } - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + if (redeem.input) { + var hasInput = redeem.input.length > 0; + var hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) throw new TypeError('Input and witness provided'); - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; + if (hasInput) { + var richunks = bscript.decompile(redeem.input); + if (!bscript.isPushOnly(richunks)) throw new TypeError('Non push-only scriptSig'); + } + } + }; -function Point(curve, x, y, isRed) { - Base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); + if (a.input) { + var chunks = _chunks(); + + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!Buffer.isBuffer(_redeem().output)) throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits(Point, Base.BasePoint); -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) throw new TypeError('Network mismatch'); -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; + if (a.input) { + var redeem = _redeem(); -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) throw new TypeError('Redeem.input mismatch'); + } - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; + checkRedeem(a.redeem); + } - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; + if (a.witness) { + if (a.redeem && a.redeem.witness && !stacksEqual(a.redeem.witness, a.witness)) throw new TypeError('Witness and redeem.witness mismatch'); + } } - return beta; -}; -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; + return Object.assign(o, a); +} - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; -}; +exports.p2sh = p2sh; -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; +},{"../crypto":166,"../networks":169,"../script":179,"./lazy":172,"bs58check":263,"typeforce":2945}],177:[function(require,module,exports){ +'use strict'; - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } +Object.defineProperty(exports, '__esModule', { + value: true +}); - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) - } - }; - return res; -}; +var bcrypto = require('../crypto'); -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; +var networks_1 = require('../networks'); -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; +var bscript = require('../script'); -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; +var lazy = require('./lazy'); - // P + O = P - if (p.inf) - return this; +var typef = require('typeforce'); - // P + P = 2P - if (this.eq(p)) - return this.dbl(); +var OPS = bscript.OPS; - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); +var ecc = require('tiny-secp256k1'); - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); +var bech32 = require('bech32'); - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; +var EMPTY_BUFFER = Buffer.alloc(0); // witness: {signature} {pubKey} +// input: <> +// output: OP_0 {pubKeyHash} -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; +function p2wpkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) throw new TypeError('Not enough data'); + opts = Object.assign({ + validate: true + }, opts || {}); + typef({ + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(20)), + input: typef.maybe(typef.BufferN(0)), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.BufferN(22)), + pubkey: typef.maybe(ecc.isPoint), + signature: typef.maybe(bscript.isCanonicalScriptSignature), + witness: typef.maybe(typef.arrayOf(typef.Buffer)) + }, a); + + var _address = lazy.value(function () { + var result = bech32.decode(a.address); + var version = result.words.shift(); + var data = bech32.fromWords(result.words); + return { + version: version, + prefix: result.prefix, + data: Buffer.from(data) + }; + }); - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); + var network = a.network || networks_1.bitcoin; + var o = { + network: network + }; + lazy.prop(o, 'address', function () { + if (!o.hash) return; + var words = bech32.toWords(o.hash); + words.unshift(0x00); + return bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', function () { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', function () { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'pubkey', function () { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy.prop(o, 'signature', function () { + if (!a.witness) return; + return a.witness[0]; + }); + lazy.prop(o, 'input', function () { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', function () { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); // extended validation - var a = this.curve.a; + if (opts.validate) { + var hash = Buffer.from([]); - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + if (a.address) { + if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) throw new TypeError('Invalid address data'); + hash = _address().data; + } - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) throw new TypeError('Hash mismatch');else hash = a.hash; + } -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; + if (a.output) { + if (a.output.length !== 22 || a.output[0] !== OPS.OP_0 || a.output[1] !== 0x14) throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) throw new TypeError('Hash mismatch');else hash = a.output.slice(2); + } -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; + if (a.pubkey) { + var pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) throw new TypeError('Hash mismatch');else hash = pkh; + } -Point.prototype.mul = function mul(k) { - k = new BN(k, 16); + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript.isCanonicalScriptSignature(a.witness[0])) throw new TypeError('Witness has invalid signature'); + if (!ecc.isPoint(a.witness[1])) throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) throw new TypeError('Pubkey mismatch'); - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; + var _pkh = bcrypto.hash160(a.witness[1]); -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; + if (hash.length > 0 && !hash.equals(_pkh)) throw new TypeError('Hash mismatch'); + } + } -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; + return Object.assign(o, a); +} -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; +exports.p2wpkh = p2wpkh; -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; +},{"../crypto":166,"../networks":169,"../script":179,"./lazy":172,"bech32":145,"tiny-secp256k1":2922,"typeforce":2945}],178:[function(require,module,exports){ +'use strict'; - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) - } - }; - } - return res; -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); +var bcrypto = require('../crypto'); - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; +var networks_1 = require('../networks'); -function JPoint(curve, x, y, z) { - Base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new BN(0); - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = new BN(z, 16); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); +var bscript = require('../script'); - this.zOne = this.z === this.curve.one; -} -inherits(JPoint, Base.BasePoint); +var lazy = require('./lazy'); -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; +var typef = require('typeforce'); -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); +var OPS = bscript.OPS; - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); +var bech32 = require('bech32'); - return this.curve.point(ax, ay); -}; +var EMPTY_BUFFER = Buffer.alloc(0); -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every(function (x, i) { + return x.equals(b[i]); + }); +} // input: <> +// witness: [redeemScriptSig ...] {redeemScript} +// output: OP_0 {sha256(redeemScript)} -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - // P + O = P - if (p.isInfinity()) - return this; +function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) throw new TypeError('Not enough data'); + opts = Object.assign({ + validate: true + }, opts || {}); + typef({ + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)) + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)) + }, a); + + var _address = lazy.value(function () { + var result = bech32.decode(a.address); + var version = result.words.shift(); + var data = bech32.fromWords(result.words); + return { + version: version, + prefix: result.prefix, + data: Buffer.from(data) + }; + }); - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); + var _rchunks = lazy.value(function () { + return bscript.decompile(a.redeem.input); + }); - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); + var network = a.network; + + if (!network) { + network = a.redeem && a.redeem.network || networks_1.bitcoin; } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + var o = { + network: network + }; + lazy.prop(o, 'address', function () { + if (!o.hash) return; + var words = bech32.toWords(o.hash); + words.unshift(0x00); + return bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', function () { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', function () { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', function () { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1) + }; + }); + lazy.prop(o, 'input', function () { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', function () { + // transform redeem input to witness stack? + if (a.redeem && a.redeem.input && a.redeem.input.length > 0 && a.redeem.output && a.redeem.output.length > 0) { + var stack = bscript.toStack(_rchunks()); // assign, and blank the existing input - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); + o.redeem = Object.assign({ + witness: stack + }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } - return this.curve.jpoint(nx, ny, nz); -}; + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); // extended validation -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); + if (opts.validate) { + var hash = Buffer.from([]); - // P + O = P - if (p.isInfinity()) - return this; + if (a.address) { + if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) throw new TypeError('Invalid address data'); + hash = _address().data; + } - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) throw new TypeError('Hash mismatch');else hash = a.hash; + } - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } + if (a.output) { + if (a.output.length !== 34 || a.output[0] !== OPS.OP_0 || a.output[1] !== 0x20) throw new TypeError('Output is invalid'); + var hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) throw new TypeError('Hash mismatch');else hash = hash2; + } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) throw new TypeError('Network mismatch'); // is there two redeem sources? - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); + if (a.redeem.input && a.redeem.input.length > 0 && a.redeem.witness && a.redeem.witness.length > 0) throw new TypeError('Ambiguous witness source'); // is the redeem output non-empty? - return this.curve.jpoint(nx, ny, nz); -}; + if (a.redeem.output) { + if (bscript.decompile(a.redeem.output).length === 0) throw new TypeError('Redeem.output is invalid'); // match hash against other sources -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); + var _hash = bcrypto.sha256(a.redeem.output); - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; + if (hash.length > 0 && !hash.equals(_hash)) throw new TypeError('Hash mismatch');else hash = _hash; + } + + if (a.redeem.input && !bscript.isPushOnly(_rchunks())) throw new TypeError('Non push-only scriptSig'); + if (a.witness && a.redeem.witness && !stacksEqual(a.witness, a.redeem.witness)) throw new TypeError('Witness and redeem.witness mismatch'); + } + + if (a.witness) { + if (a.redeem && a.redeem.output && !a.redeem.output.equals(a.witness[a.witness.length - 1])) throw new TypeError('Witness and redeem.output mismatch'); + } } - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; + return Object.assign(o, a); +} - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); +exports.p2wsh = p2wsh; - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); +},{"../crypto":166,"../networks":169,"../script":179,"./lazy":172,"bech32":145,"typeforce":2945}],179:[function(require,module,exports){ +'use strict'; - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); +Object.defineProperty(exports, '__esModule', { + value: true +}); - jx = nx; - jz = nz; - jyd = dny; - } +var scriptNumber = require('./script_number'); - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; +var scriptSignature = require('./script_signature'); -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; +var types = require('./types'); - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; +var bip66 = require('bip66'); -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A +var ecc = require('tiny-secp256k1'); - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); +var pushdata = require('pushdata-bitcoin'); - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); +var typeforce = require('typeforce'); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A +exports.OPS = require('bitcoin-ops'); - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); +var REVERSE_OPS = require('bitcoin-ops/map'); - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); +var OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } +function isOPInt(value) { + return types.Number(value) && (value === exports.OPS.OP_0 || value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16 || value === exports.OPS.OP_1NEGATE); +} - return this.curve.jpoint(nx, ny, nz); -}; +function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); +} -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A +function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); +} - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S +exports.isPushOnly = isPushOnly; - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } +function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; +} - return this.curve.jpoint(nx, ny, nz); -}; +function chunksIsBuffer(buf) { + return Buffer.isBuffer(buf); +} -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; +function chunksIsArray(buf) { + return types.Array(buf); +} - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); +function singleChunkIsBuffer(buf) { + return Buffer.isBuffer(buf); +} - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); +function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + var bufferSize = chunks.reduce(function (accum, chunk) { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } // opcode - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); + return accum + 1; + }, 0.0); + var buffer = Buffer.allocUnsafe(bufferSize); + var offset = 0; + chunks.forEach(function (chunk) { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + var opcode = asMinimalOP(chunk); - return this.curve.jpoint(nx, ny, nz); -}; + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; +} - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... +exports.compile = compile; - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); +function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + var chunks = []; + var i = 0; - return this.curve.jpoint(nx, ny, nz); -}; + while (i < buffer.length) { + var opcode = buffer[i]; // data chunk -JPoint.prototype.mul = function mul(k, kbase) { - k = new BN(k, kbase); + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + var d = pushdata.decode(buffer, i); // did reading a pushDataInt fail? - return this.curve._wnafMul(this, k); -}; + if (d === null) return null; + i += d.size; // attempt to read too much data? -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); + if (i + d.number > buffer.length) return null; + var data = buffer.slice(i, i + d.number); + i += d.number; // decompile minimally - if (this === p) - return true; + var op = asMinimalOP(data); - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } // opcode - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; + } else { + chunks.push(opcode); + i += 1; + } + } -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; + return chunks; +} - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; +exports.decompile = decompile; - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; +function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); } - return false; -}; -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; + return chunks.map(function (chunk) { + // data? + if (singleChunkIsBuffer(chunk)) { + var op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } // opcode! -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; -},{"../../elliptic":209,"../curve":212,"bn.js":125,"inherits":401}],215:[function(require,module,exports){ -'use strict'; + return REVERSE_OPS[chunk]; + }).join(' '); +} -var curves = exports; +exports.toASM = toASM; -var hash = require('hash.js'); -var elliptic = require('../elliptic'); +function fromASM(asm) { + typeforce(types.String, asm); + return compile(asm.split(' ').map(function (chunkStr) { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); // data! -var assert = elliptic.utils.assert; + return Buffer.from(chunkStr, 'hex'); + })); +} -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new elliptic.curve.short(options); - else if (options.type === 'edwards') - this.curve = new elliptic.curve.edwards(options); - else - this.curve = new elliptic.curve.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; +exports.fromASM = fromASM; - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(function (op) { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); } -curves.PresetCurve = PresetCurve; -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); +exports.toStack = toStack; + +function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); } -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] -}); +exports.isCanonicalPubKey = isCanonicalPubKey; -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] -}); +function isDefinedHashType(hashType) { + var hashTypeMod = hashType & ~0x80; // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] -}); + return hashTypeMod > 0x00 && hashTypeMod < 0x04; +} -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] -}); +exports.isDefinedHashType = isDefinedHashType; -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] -}); +function isCanonicalScriptSignature(buffer) { + if (!Buffer.isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); +} -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '9' - ] -}); +exports.isCanonicalScriptSignature = isCanonicalScriptSignature; // tslint:disable-next-line variable-name -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', +exports.number = scriptNumber; +exports.signature = scriptSignature; - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); +},{"./script_number":180,"./script_signature":181,"./types":205,"bip66":154,"bitcoin-ops":160,"bitcoin-ops/map":161,"pushdata-bitcoin":2705,"tiny-secp256k1":2922,"typeforce":2945}],180:[function(require,module,exports){ +'use strict'; -var pre; -try { - pre = require('./precomputed/secp256k1'); -} catch (e) { - pre = undefined; -} +Object.defineProperty(exports, '__esModule', { + value: true +}); -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash.sha256, +function decode(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + var length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number'); } - ], + } // 40-bit - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] -}); -},{"../elliptic":209,"./precomputed/secp256k1":222,"hash.js":356}],216:[function(require,module,exports){ -'use strict'; + if (length === 5) { + var a = buffer.readUInt32LE(0); + var b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } // 32-bit / 24-bit / 16-bit / 8-bit -var BN = require('bn.js'); -var HmacDRBG = require('hmac-drbg'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var KeyPair = require('./key'); -var Signature = require('./signature'); + var result = 0; -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); + for (var i = 0; i < length; ++i) { + result |= buffer[i] << 8 * i; + } - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); + if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << 8 * (length - 1))); + return result; +} - options = elliptic.curves[options]; - } +exports.decode = decode; - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof elliptic.curves.PresetCurve) - options = { curve: options }; +function scriptNumSize(i) { + return i > 0x7fffffff ? 5 : i > 0x7fffff ? 4 : i > 0x7fff ? 3 : i > 0x7f ? 2 : i > 0x00 ? 1 : 0; +} - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; +function encode(_number) { + var value = Math.abs(_number); + var size = scriptNumSize(value); + var buffer = Buffer.allocUnsafe(size); + var negative = _number < 0; - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); + for (var i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; + } - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + + return buffer; } -module.exports = EC; -EC.prototype.keyPair = function keyPair(options) { - return new KeyPair(this, options); -}; +exports.encode = encode; -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair.fromPrivate(this, priv, enc); -}; +},{}],181:[function(require,module,exports){ +'use strict'; -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair.fromPublic(this, pub, enc); -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; +var types = require('./types'); - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); +var bip66 = require('bip66'); - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new BN(2)); - do { - var priv = new BN(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; +var typeforce = require('typeforce'); - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); -}; +var ZERO = Buffer.alloc(1, 0); -EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { - var delta = msg.byteLength() * 8 - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; +function toDER(x) { + var i = 0; -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; + while (x[i] === 0) { + ++i; } - if (!options) - options = {}; - key = this.keyFromPrivate(key, enc); - msg = this._truncateToN(new BN(msg, 16)); + if (i === x.length) return ZERO; + x = x.slice(i); + if (x[0] & 0x80) return Buffer.concat([ZERO, x], 1 + x.length); + return x; +} - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); +function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + var buffer = Buffer.alloc(32, 0); + var bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; +} // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' +function decode(buffer) { + var hashType = buffer.readUInt8(buffer.length - 1); + var hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); + var decoded = bip66.decode(buffer.slice(0, -1)); + var r = fromDER(decoded.r); + var s = fromDER(decoded.s); + var signature = Buffer.concat([r, s], 64); + return { + signature: signature, + hashType: hashType + }; +} + +exports.decode = decode; + +function encode(signature, hashType) { + typeforce({ + signature: types.BufferN(64), + hashType: types.UInt8 + }, { + signature: signature, + hashType: hashType }); + var hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); + var hashTypeBuffer = Buffer.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + var r = toDER(signature.slice(0, 32)); + var s = toDER(signature.slice(32, 64)); + return Buffer.concat([bip66.encode(r, s), hashTypeBuffer]); +} - // Number of bytes to generate - var ns1 = this.n.sub(new BN(1)); +exports.encode = encode; - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new BN(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; +},{"./types":205,"bip66":154,"typeforce":2945}],182:[function(require,module,exports){ +'use strict'; - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; +Object.defineProperty(exports, '__esModule', { + value: true +}); - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; +var input = require('./input'); - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; +exports.input = input; - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); +var output = require('./output'); - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } +exports.output = output; - return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); - } -}; +},{"./input":183,"./output":184}],183:[function(require,module,exports){ +'use strict'; // OP_0 [signatures ...] -EC.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature(signature, 'hex'); +Object.defineProperty(exports, '__esModule', { + value: true +}); - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; +var bscript = require('../../script'); - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); +var script_1 = require('../../script'); - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; +function partialSignature(value) { + return value === script_1.OPS.OP_0 || bscript.isCanonicalScriptSignature(value); +} - return p.getX().umod(this.n).cmp(r) === 0; +function check(script, allowIncomplete) { + var chunks = bscript.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1.OPS.OP_0) return false; + + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); } - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K + return chunks.slice(1).every(bscript.isCanonicalScriptSignature); +} - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; +exports.check = check; - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); +check.toJSON = function () { + return 'multisig input'; }; -EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature(signature, enc); +},{"../../script":179}],184:[function(require,module,exports){ +'use strict'; // m [pubKeys ...] n OP_CHECKMULTISIG - var n = this.n; - var e = new BN(msg); - var r = signature.r; - var s = signature.s; +Object.defineProperty(exports, '__esModule', { + value: true +}); - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); +var bscript = require('../../script'); - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); +var script_1 = require('../../script'); - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); +var types = require('../../types'); - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; +var OP_INT_BASE = script_1.OPS.OP_RESERVED; // OP_1 - 1 -EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; +function check(script, allowIncomplete) { + var chunks = bscript.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1.OPS.OP_CHECKMULTISIG) return false; + if (!types.Number(chunks[0])) return false; + if (!types.Number(chunks[chunks.length - 2])) return false; + var m = chunks[0] - OP_INT_BASE; + var n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + var keys = chunks.slice(1, -2); + return keys.every(bscript.isCanonicalPubKey); +} - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { - continue; - } +exports.check = check; - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); +check.toJSON = function () { + return 'multi-sig output'; }; -},{"../../elliptic":209,"./key":217,"./signature":218,"bn.js":125,"hmac-drbg":371}],217:[function(require,module,exports){ +},{"../../script":179,"../../types":205}],185:[function(require,module,exports){ 'use strict'; -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; +Object.defineProperty(exports, '__esModule', { + value: true +}); // OP_RETURN {data} -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; +var bscript = require('../script'); - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); +var OPS = bscript.OPS; + +function check(script) { + var buffer = bscript.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; } -module.exports = KeyPair; -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; +exports.check = check; - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); +check.toJSON = function () { + return 'null data output'; }; -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; - - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); +var output = { + check: check }; +exports.output = output; -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); - - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; +},{"../script":179}],186:[function(require,module,exports){ +arguments[4][182][0].apply(exports,arguments) +},{"./input":187,"./output":188,"dup":182}],187:[function(require,module,exports){ +'use strict'; // {signature} - return { result: true, reason: null }; -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -KeyPair.prototype.getPublic = function getPublic(compact, enc) { - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } +var bscript = require('../../script'); - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); +function check(script) { + var chunks = bscript.decompile(script); + return chunks.length === 1 && bscript.isCanonicalScriptSignature(chunks[0]); +} - if (!enc) - return this.pub; +exports.check = check; - return this.pub.encode(enc, compact); +check.toJSON = function () { + return 'pubKey input'; }; -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; +},{"../../script":179}],188:[function(require,module,exports){ +'use strict'; // {pubKey} OP_CHECKSIG -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN(key, enc || 16); - - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; +var bscript = require('../../script'); -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); -}; +var script_1 = require('../../script'); -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; +function check(script) { + var chunks = bscript.decompile(script); + return chunks.length === 2 && bscript.isCanonicalPubKey(chunks[0]) && chunks[1] === script_1.OPS.OP_CHECKSIG; +} -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; +exports.check = check; -KeyPair.prototype.inspect = function inspect() { - return ''; +check.toJSON = function () { + return 'pubKey output'; }; -},{"../../elliptic":209,"bn.js":125}],218:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; +},{"../../script":179}],189:[function(require,module,exports){ +arguments[4][182][0].apply(exports,arguments) +},{"./input":190,"./output":191,"dup":182}],190:[function(require,module,exports){ +'use strict'; // {signature} {pubKey} -function Signature(options, enc) { - if (options instanceof Signature) - return options; +Object.defineProperty(exports, '__esModule', { + value: true +}); - if (this._importDER(options, enc)) - return; +var bscript = require('../../script'); - assert(options.r && options.s, 'Signature without r or s'); - this.r = new BN(options.r, 16); - this.s = new BN(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; +function check(script) { + var chunks = bscript.decompile(script); + return chunks.length === 2 && bscript.isCanonicalScriptSignature(chunks[0]) && bscript.isCanonicalPubKey(chunks[1]); } -module.exports = Signature; -function Position() { - this.place = 0; -} +exports.check = check; -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; -} +check.toJSON = function () { + return 'pubKeyHash input'; +}; -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} +},{"../../script":179}],191:[function(require,module,exports){ +'use strict'; // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG -Signature.prototype._importDER = function _importDER(data, enc) { - data = utils.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); - } +Object.defineProperty(exports, '__esModule', { + value: true +}); - this.r = new BN(r); - this.s = new BN(s); - this.recoveryParam = null; +var bscript = require('../../script'); - return true; -}; +var script_1 = require('../../script'); -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; - } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); +function check(script) { + var buffer = bscript.compile(script); + return buffer.length === 25 && buffer[0] === script_1.OPS.OP_DUP && buffer[1] === script_1.OPS.OP_HASH160 && buffer[2] === 0x14 && buffer[23] === script_1.OPS.OP_EQUALVERIFY && buffer[24] === script_1.OPS.OP_CHECKSIG; } -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); +exports.check = check; - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils.encode(res, enc); +check.toJSON = function () { + return 'pubKeyHash output'; }; -},{"../../elliptic":209,"bn.js":125}],219:[function(require,module,exports){ -'use strict'; - -var hash = require('hash.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EDDSA(curve) { - assert(curve === 'ed25519', 'only tested with ed25519 so far'); +},{"../../script":179}],192:[function(require,module,exports){ +arguments[4][182][0].apply(exports,arguments) +},{"./input":193,"./output":194,"dup":182}],193:[function(require,module,exports){ +'use strict'; // {serialized scriptPubKey script} - if (!(this instanceof EDDSA)) - return new EDDSA(curve); +Object.defineProperty(exports, '__esModule', { + value: true +}); - var curve = elliptic.curves[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); +var bscript = require('../../script'); - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash.sha512; -} +var p2ms = require('../multisig'); -module.exports = EDDSA; +var p2pk = require('../pubkey'); -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); -}; +var p2pkh = require('../pubkeyhash'); -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message -*/ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; +var p2wpkho = require('../witnesspubkeyhash/output'); -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils.intFromLE(hash.digest()).umod(this.curve.n); -}; +var p2wsho = require('../witnessscripthash/output'); -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair.fromPublic(this, pub); -}; +function check(script, allowIncomplete) { + var chunks = bscript.decompile(script); + if (chunks.length < 1) return false; + var lastChunk = chunks[chunks.length - 1]; + if (!Buffer.isBuffer(lastChunk)) return false; + var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1))); + var redeemScriptChunks = bscript.decompile(lastChunk); // is redeemScript a valid script? -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair.fromSecret(this, secret); -}; + if (!redeemScriptChunks) return false; // is redeemScriptSig push only? -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof Signature) - return sig; - return new Signature(this, sig); -}; + if (!bscript.isPushOnly(scriptSigChunks)) return false; // is witness? -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; -}; + if (chunks.length === 1) { + return p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks); + } // match types -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils.parseBytes(bytes); - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + if (p2pkh.input.check(scriptSigChunks) && p2pkh.output.check(redeemScriptChunks)) return true; + if (p2ms.input.check(scriptSigChunks, allowIncomplete) && p2ms.output.check(redeemScriptChunks)) return true; + if (p2pk.input.check(scriptSigChunks) && p2pk.output.check(redeemScriptChunks)) return true; + return false; +} - var y = utils.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; +exports.check = check; -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); +check.toJSON = function () { + return 'scriptHash input'; }; -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils.intFromLE(bytes); -}; +},{"../../script":179,"../multisig":182,"../pubkey":186,"../pubkeyhash":189,"../witnesspubkeyhash/output":199,"../witnessscripthash/output":202}],194:[function(require,module,exports){ +'use strict'; // OP_HASH160 {scriptHash} OP_EQUAL -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -},{"../../elliptic":209,"./key":220,"./signature":221,"hash.js":356}],220:[function(require,module,exports){ -'use strict'; +var bscript = require('../../script'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var cachedProperty = utils.cachedProperty; +var script_1 = require('../../script'); -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes(params.pub); +function check(script) { + var buffer = bscript.compile(script); + return buffer.length === 23 && buffer[0] === script_1.OPS.OP_HASH160 && buffer[1] === 0x14 && buffer[22] === script_1.OPS.OP_EQUAL; } -KeyPair.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair) - return pub; - return new KeyPair(eddsa, { pub: pub }); -}; +exports.check = check; -KeyPair.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair) - return secret; - return new KeyPair(eddsa, { secret: secret }); +check.toJSON = function () { + return 'scriptHash output'; }; -KeyPair.prototype.secret = function secret() { - return this._secret; -}; +},{"../../script":179}],195:[function(require,module,exports){ +'use strict'; -cachedProperty(KeyPair, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); +Object.defineProperty(exports, '__esModule', { + value: true }); -cachedProperty(KeyPair, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); +var output = require('./output'); -cachedProperty(KeyPair, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; +exports.output = output; - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; +},{"./output":196}],196:[function(require,module,exports){ +'use strict'; // OP_RETURN {aa21a9ed} {commitment} - return a; +Object.defineProperty(exports, '__esModule', { + value: true }); -cachedProperty(KeyPair, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); +var bscript = require('../../script'); -cachedProperty(KeyPair, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); +var script_1 = require('../../script'); -cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); +var types = require('../../types'); -KeyPair.prototype.sign = function sign(message) { - assert(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; +var typeforce = require('typeforce'); -KeyPair.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; +var HEADER = Buffer.from('aa21a9ed', 'hex'); -KeyPair.prototype.getSecret = function getSecret(enc) { - assert(this._secret, 'KeyPair is public only'); - return utils.encode(this.secret(), enc); -}; +function check(script) { + var buffer = bscript.compile(script); + return buffer.length > 37 && buffer[0] === script_1.OPS.OP_RETURN && buffer[1] === 0x24 && buffer.slice(2, 6).equals(HEADER); +} -KeyPair.prototype.getPublic = function getPublic(enc) { - return utils.encode(this.pubBytes(), enc); +exports.check = check; + +check.toJSON = function () { + return 'Witness commitment output'; }; -module.exports = KeyPair; +function encode(commitment) { + typeforce(types.Hash256bit, commitment); + var buffer = Buffer.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript.compile([script_1.OPS.OP_RETURN, buffer]); +} -},{"../../elliptic":209}],221:[function(require,module,exports){ -'use strict'; +exports.encode = encode; -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var cachedProperty = utils.cachedProperty; -var parseBytes = utils.parseBytes; +function decode(buffer) { + typeforce(check, buffer); + return bscript.decompile(buffer)[1].slice(4, 36); +} -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature(eddsa, sig) { - this.eddsa = eddsa; +exports.decode = decode; - if (typeof sig !== 'object') - sig = parseBytes(sig); +},{"../../script":179,"../../types":205,"typeforce":2945}],197:[function(require,module,exports){ +arguments[4][182][0].apply(exports,arguments) +},{"./input":198,"./output":199,"dup":182}],198:[function(require,module,exports){ +'use strict'; // {signature} {pubKey} - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; - } +Object.defineProperty(exports, '__esModule', { + value: true +}); - assert(sig.R && sig.S, 'Signature without R or S'); +var bscript = require('../../script'); - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN) - this._S = sig.S; +function isCompressedCanonicalPubKey(pubKey) { + return bscript.isCanonicalPubKey(pubKey) && pubKey.length === 33; +} - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +function check(script) { + var chunks = bscript.decompile(script); + return chunks.length === 2 && bscript.isCanonicalScriptSignature(chunks[0]) && isCompressedCanonicalPubKey(chunks[1]); } -cachedProperty(Signature, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); +exports.check = check; -cachedProperty(Signature, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); +check.toJSON = function () { + return 'witnessPubKeyHash input'; +}; -cachedProperty(Signature, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); +},{"../../script":179}],199:[function(require,module,exports){ +'use strict'; // OP_0 {pubKeyHash} -cachedProperty(Signature, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); +Object.defineProperty(exports, '__esModule', { + value: true }); -Signature.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature.prototype.toHex = function toHex() { - return utils.encode(this.toBytes(), 'hex').toUpperCase(); -}; +var bscript = require('../../script'); -module.exports = Signature; +var script_1 = require('../../script'); -},{"../../elliptic":209,"bn.js":125}],222:[function(require,module,exports){ -module.exports = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] - } -}; +function check(script) { + var buffer = bscript.compile(script); + return buffer.length === 22 && buffer[0] === script_1.OPS.OP_0 && buffer[1] === 0x14; +} -},{}],223:[function(require,module,exports){ -'use strict'; +exports.check = check; -var utils = exports; -var BN = require('bn.js'); -var minAssert = require('minimalistic-assert'); -var minUtils = require('minimalistic-crypto-utils'); +check.toJSON = function () { + return 'Witness pubKeyHash output'; +}; -utils.assert = minAssert; -utils.toArray = minUtils.toArray; -utils.zero2 = minUtils.zero2; -utils.toHex = minUtils.toHex; -utils.encode = minUtils.encode; +},{"../../script":179}],200:[function(require,module,exports){ +arguments[4][182][0].apply(exports,arguments) +},{"./input":201,"./output":202,"dup":182}],201:[function(require,module,exports){ +'use strict'; // {serialized scriptPubKey script} -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; - } - naf.push(z); +Object.defineProperty(exports, '__esModule', { + value: true +}); - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } +var bscript = require('../../script'); - return naf; -} -utils.getNAF = getNAF; +var typeforce = require('typeforce'); -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; +var p2ms = require('../multisig'); - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { +var p2pk = require('../pubkey'); - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; - } - jsf[0].push(u1); +var p2pkh = require('../pubkeyhash'); - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); +function check(chunks, allowIncomplete) { + typeforce(typeforce.Array, chunks); + if (chunks.length < 1) return false; + var witnessScript = chunks[chunks.length - 1]; + if (!Buffer.isBuffer(witnessScript)) return false; + var witnessScriptChunks = bscript.decompile(witnessScript); // is witnessScript a valid script? - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + var witnessRawScriptSig = bscript.compile(chunks.slice(0, -1)); // match types - return jsf; + if (p2pkh.input.check(witnessRawScriptSig) && p2pkh.output.check(witnessScriptChunks)) return true; + if (p2ms.input.check(witnessRawScriptSig, allowIncomplete) && p2ms.output.check(witnessScriptChunks)) return true; + if (p2pk.input.check(witnessRawScriptSig) && p2pk.output.check(witnessScriptChunks)) return true; + return false; } -utils.getJSF = getJSF; -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; -} -utils.cachedProperty = cachedProperty; +exports.check = check; -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; -} -utils.parseBytes = parseBytes; +check.toJSON = function () { + return 'witnessScriptHash input'; +}; -function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); -} -utils.intFromLE = intFromLE; +},{"../../script":179,"../multisig":182,"../pubkey":186,"../pubkeyhash":189,"typeforce":2945}],202:[function(require,module,exports){ +'use strict'; // OP_0 {scriptHash} +Object.defineProperty(exports, '__esModule', { + value: true +}); -},{"bn.js":125,"minimalistic-assert":955,"minimalistic-crypto-utils":956}],224:[function(require,module,exports){ -module.exports={ - "name": "elliptic", - "version": "6.4.0", - "description": "EC cryptography", - "main": "lib/elliptic.js", - "files": [ - "lib" - ], - "scripts": { - "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", - "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", - "lint": "npm run jscs && npm run jshint", - "unit": "istanbul test _mocha --reporter=spec test/index.js", - "test": "npm run lint && npm run unit", - "version": "grunt dist && git add dist/" - }, - "repository": { - "type": "git", - "url": "git@github.com:indutny/elliptic" - }, - "keywords": [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ], - "author": "Fedor Indutny ", - "license": "MIT", - "bugs": { - "url": "https://github.com/indutny/elliptic/issues" - }, - "homepage": "https://github.com/indutny/elliptic", - "devDependencies": { - "brfs": "^1.4.3", - "coveralls": "^2.11.3", - "grunt": "^0.4.5", - "grunt-browserify": "^5.0.0", - "grunt-cli": "^1.2.0", - "grunt-contrib-connect": "^1.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^1.0.1", - "grunt-mocha-istanbul": "^3.0.1", - "grunt-saucelabs": "^8.6.2", - "istanbul": "^0.4.2", - "jscs": "^2.9.0", - "jshint": "^2.6.0", - "mocha": "^2.1.0" - }, - "dependencies": { - "bn.js": "^4.4.0", - "brorand": "^1.0.1", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.0" - } +var bscript = require('../../script'); -,"_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz" -,"_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=" -,"_from": "elliptic@6.4.0" -} -},{}],225:[function(require,module,exports){ -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ +var script_1 = require('../../script'); -'use strict' +function check(script) { + var buffer = bscript.compile(script); + return buffer.length === 34 && buffer[0] === script_1.OPS.OP_0 && buffer[1] === 0x20; +} -/** - * Module exports. - * @public - */ +exports.check = check; -module.exports = encodeUrl +check.toJSON = function () { + return 'Witness scriptHash output'; +}; -/** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private - */ +},{"../../script":179}],203:[function(require,module,exports){ +'use strict'; -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -/** - * RegExp to match unmatched surrogate pair. - * @private - */ +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -/** - * String to replace unmatched surrogate pair with. - * @private - */ +Object.defineProperty(exports, '__esModule', { + value: true +}); -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' +var bufferutils = require('./bufferutils'); -/** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). - * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. - * - * @param {string} url - * @return {string} - * @public - */ +var bufferutils_1 = require('./bufferutils'); -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} +var bcrypto = require('./crypto'); -},{}],226:[function(require,module,exports){ -'use strict' +var bscript = require('./script'); -var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN -var AbstractChainedBatch = require('abstract-leveldown').AbstractChainedBatch -var AbstractIterator = require('abstract-leveldown').AbstractIterator -var inherits = require('inherits') -var xtend = require('xtend') -var Codec = require('level-codec') -var EncodingError = require('level-errors').EncodingError +var script_1 = require('./script'); -module.exports = DB.default = DB +var types = require('./types'); -function DB (db, opts) { - if (!(this instanceof DB)) return new DB(db, opts) - AbstractLevelDOWN.call(this, '') +var typeforce = require('typeforce'); - opts = opts || {} - if (typeof opts.keyEncoding === 'undefined') opts.keyEncoding = 'utf8' - if (typeof opts.valueEncoding === 'undefined') opts.valueEncoding = 'utf8' +var varuint = require('varuint-bitcoin'); - this.db = db - this.codec = new Codec(opts) +function varSliceSize(someScript) { + var length = someScript.length; + return varuint.encodingLength(length) + length; } -inherits(DB, AbstractLevelDOWN) - -DB.prototype._serializeKey = -DB.prototype._serializeValue = function (datum) { - return datum +function vectorSize(someVector) { + var length = someVector.length; + return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) { + return sum + varSliceSize(witness); + }, 0); } -DB.prototype._open = function (opts, cb) { - this.db.open(opts, cb) -} +var EMPTY_SCRIPT = Buffer.allocUnsafe(0); +var EMPTY_WITNESS = []; +var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex'); +var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex'); +var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex'); +var BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX +}; -DB.prototype._close = function (cb) { - this.db.close(cb) +function isOutput(out) { + return out.value !== undefined; } -DB.prototype._put = function (key, value, opts, cb) { - key = this.codec.encodeKey(key, opts) - value = this.codec.encodeValue(value, opts) - this.db.put(key, value, opts, cb) -} +var Transaction = +/*#__PURE__*/ +function () { + function Transaction() { + _classCallCheck(this, Transaction); -DB.prototype._get = function (key, opts, cb) { - var self = this - key = this.codec.encodeKey(key, opts) - opts.asBuffer = this.codec.valueAsBuffer(opts) - this.db.get(key, opts, function (err, value) { - if (err) return cb(err) - try { - value = self.codec.decodeValue(value, opts) - } catch (err) { - return cb(new EncodingError(err)) + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; + } + + _createClass(Transaction, [{ + key: "isCoinbase", + value: function isCoinbase() { + return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash); } - cb(null, value) - }) -} + }, { + key: "addInput", + value: function addInput(hash, index, sequence, scriptSig) { + typeforce(types.tuple(types.Hash256bit, types.UInt32, types.maybe(types.UInt32), types.maybe(types.Buffer)), arguments); -DB.prototype._del = function (key, opts, cb) { - key = this.codec.encodeKey(key, opts) - this.db.del(key, opts, cb) -} + if (types.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } // Add the input and return the input's index -DB.prototype._chainedBatch = function () { - return new Batch(this) -} -DB.prototype._batch = function (ops, opts, cb) { - ops = this.codec.encodeBatch(ops, opts) - this.db.batch(ops, opts, cb) -} + return this.ins.push({ + hash: hash, + index: index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS + }) - 1; + } + }, { + key: "addOutput", + value: function addOutput(scriptPubKey, value) { + typeforce(types.tuple(types.Buffer, types.Satoshi), arguments); // Add the output and return the output's index -DB.prototype._iterator = function (opts) { - opts.keyAsBuffer = this.codec.keyAsBuffer(opts) - opts.valueAsBuffer = this.codec.valueAsBuffer(opts) - return new Iterator(this, opts) -} + return this.outs.push({ + script: scriptPubKey, + value: value + }) - 1; + } + }, { + key: "hasWitnesses", + value: function hasWitnesses() { + return this.ins.some(function (x) { + return x.witness.length !== 0; + }); + } + }, { + key: "weight", + value: function weight() { + var base = this.__byteLength(false); -DB.prototype._setupIteratorOptions = function (options) { - options = xtend(options) - options.reverse = !!options.reverse - options.keys = options.keys !== false - options.values = options.values !== false - options.limit = 'limit' in options ? options.limit : -1 - options.keyAsBuffer = options.keyAsBuffer !== false - options.valueAsBuffer = options.valueAsBuffer !== false - return options -} + var total = this.__byteLength(true); -DB.prototype.approximateSize = function (start, end, opts, cb) { - return this.db.approximateSize(start, end, opts, cb) -} + return base * 3 + total; + } + }, { + key: "virtualSize", + value: function virtualSize() { + return Math.ceil(this.weight() / 4); + } + }, { + key: "byteLength", + value: function byteLength() { + return this.__byteLength(true); + } + }, { + key: "clone", + value: function clone() { + var newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(function (txIn) { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness + }; + }); + newTx.outs = this.outs.map(function (txOut) { + return { + script: txOut.script, + value: txOut.value + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ -function Iterator (db, opts) { - AbstractIterator.call(this, db) - this.codec = db.codec - this.keys = opts.keys - this.values = opts.values - this.opts = this.codec.encodeLtgt(opts) - this.it = db.db.iterator(this.opts) -} + }, { + key: "hashForSignature", + value: function hashForSignature(inIndex, prevOutScript, hashType) { + typeforce(types.tuple(types.UInt32, types.Buffer, + /* types.UInt8 */ + types.Number), arguments); // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 -inherits(Iterator, AbstractIterator) + if (inIndex >= this.ins.length) return ONE; // ignore OP_CODESEPARATOR -Iterator.prototype._next = function (cb) { - var self = this - this.it.next(function (err, key, value) { - if (err) return cb(err) - try { - if (self.keys && typeof key !== 'undefined') { - key = self.codec.decodeKey(key, self.opts) - } else { - key = undefined - } + var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) { + return x !== script_1.OPS.OP_CODESEPARATOR; + })); + var txTmp = this.clone(); // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if (self.values && typeof value !== 'undefined') { - value = self.codec.decodeValue(value, self.opts) - } else { - value = undefined - } - } catch (err) { - return cb(new EncodingError(err)) - } - cb(null, key, value) - }) -} + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; // ignore sequence numbers (except at inIndex) -Iterator.prototype._end = function (cb) { - this.it.end(cb) -} + txTmp.ins.forEach(function (input, i) { + if (i === inIndex) return; + input.sequence = 0; + }); // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; // truncate outputs after -function Batch (db, codec) { - AbstractChainedBatch.call(this, db) - this.codec = db.codec - this.batch = db.db.batch() -} + txTmp.outs.length = inIndex + 1; // "blank" outputs before -inherits(Batch, AbstractChainedBatch) + for (var i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } // ignore sequence numbers (except at inIndex) -Batch.prototype._put = function (key, value) { - key = this.codec.encodeKey(key) - value = this.codec.encodeValue(value) - this.batch.put(key, value) -} -Batch.prototype._del = function (key) { - key = this.codec.encodeKey(key) - this.batch.del(key) -} + txTmp.ins.forEach(function (input, y) { + if (y === inIndex) return; + input.sequence = 0; + }); + } // SIGHASH_ANYONECANPAY: ignore inputs entirely? -Batch.prototype._clear = function () { - this.batch.clear() -} -Batch.prototype._write = function (opts, cb) { - this.batch.write(opts, cb) -} + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(function (input) { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; + } // serialize and hash -},{"abstract-leveldown":230,"inherits":401,"level-codec":639,"level-errors":231,"xtend":1356}],227:[function(require,module,exports){ -arguments[4][188][0].apply(exports,arguments) -},{"dup":188}],228:[function(require,module,exports){ -arguments[4][189][0].apply(exports,arguments) -},{"dup":189}],229:[function(require,module,exports){ -/* Copyright (c) 2017 Rod Vagg, MIT License */ -var xtend = require('xtend') -var AbstractIterator = require('./abstract-iterator') -var AbstractChainedBatch = require('./abstract-chained-batch') -var hasOwnProperty = Object.prototype.hasOwnProperty -var rangeOptions = 'start end gt gte lt lte'.split(' ') + var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) { - throw new Error('constructor requires at least a location argument') - } + txTmp.__toBuffer(buffer, 0, false); - if (typeof location !== 'string') { - throw new Error('constructor requires a location string argument') - } + return bcrypto.hash256(buffer); + } + }, { + key: "hashForWitnessV0", + value: function hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments); + var tbuffer = Buffer.from([]); + var toffset = 0; - this.location = location - this.status = 'new' -} + function writeSlice(slice) { + toffset += slice.copy(tbuffer, toffset); + } -AbstractLevelDOWN.prototype.open = function (options, callback) { - var self = this - var oldStatus = this.status + function writeUInt32(i) { + toffset = tbuffer.writeUInt32LE(i, toffset); + } - if (typeof options === 'function') { callback = options } + function writeUInt64(i) { + toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset); + } - if (typeof callback !== 'function') { - throw new Error('open() requires a callback argument') - } + function writeVarInt(i) { + varuint.encode(i, tbuffer, toffset); + toffset += varuint.encode.bytes; + } - if (typeof options !== 'object') { options = {} } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } - options.createIfMissing = options.createIfMissing !== false - options.errorIfExists = !!options.errorIfExists + var hashOutputs = ZERO; + var hashPrevouts = ZERO; + var hashSequence = ZERO; - this.status = 'opening' - this._open(options, function (err) { - if (err) { - self.status = oldStatus - return callback(err) + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer.allocUnsafe(36 * this.ins.length); + toffset = 0; + this.ins.forEach(function (txIn) { + writeSlice(txIn.hash); + writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto.hash256(tbuffer); + } + + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) && (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { + tbuffer = Buffer.allocUnsafe(4 * this.ins.length); + toffset = 0; + this.ins.forEach(function (txIn) { + writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto.hash256(tbuffer); + } + + if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { + var txOutsSize = this.outs.reduce(function (sum, output) { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer.allocUnsafe(txOutsSize); + toffset = 0; + this.outs.forEach(function (out) { + writeUInt64(out.value); + writeVarSlice(out.script); + }); + hashOutputs = bcrypto.hash256(tbuffer); + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) { + var output = this.outs[inIndex]; + tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)); + toffset = 0; + writeUInt64(output.value); + writeVarSlice(output.script); + hashOutputs = bcrypto.hash256(tbuffer); + } + + tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)); + toffset = 0; + var input = this.ins[inIndex]; + writeUInt32(this.version); + writeSlice(hashPrevouts); + writeSlice(hashSequence); + writeSlice(input.hash); + writeUInt32(input.index); + writeVarSlice(prevOutScript); + writeUInt64(value); + writeUInt32(input.sequence); + writeSlice(hashOutputs); + writeUInt32(this.locktime); + writeUInt32(hashType); + return bcrypto.hash256(tbuffer); } - self.status = 'open' - callback() - }) -} + }, { + key: "getHash", + value: function getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer.alloc(32, 0); + return bcrypto.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + }, { + key: "getId", + value: function getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1.reverseBuffer(this.getHash(false)).toString('hex'); + } + }, { + key: "toBuffer", + value: function toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + }, { + key: "toHex", + value: function toHex() { + return this.toBuffer(undefined, undefined).toString('hex'); + } + }, { + key: "setInputScript", + value: function setInputScript(index, scriptSig) { + typeforce(types.tuple(types.Number, types.Buffer), arguments); + this.ins[index].script = scriptSig; + } + }, { + key: "setWitness", + value: function setWitness(index, witness) { + typeforce(types.tuple(types.Number, [types.Buffer]), arguments); + this.ins[index].witness = witness; + } + }, { + key: "__byteLength", + value: function __byteLength(_ALLOW_WITNESS) { + var hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + + return (hasWitnesses ? 10 : 8) + varuint.encodingLength(this.ins.length) + varuint.encodingLength(this.outs.length) + this.ins.reduce(function (sum, input) { + return sum + 40 + varSliceSize(input.script); + }, 0) + this.outs.reduce(function (sum, output) { + return sum + 8 + varSliceSize(output.script); + }, 0) + (hasWitnesses ? this.ins.reduce(function (sum, input) { + return sum + vectorSize(input.witness); + }, 0) : 0); + } + }, { + key: "__toBuffer", + value: function __toBuffer(buffer, initialOffset, _ALLOW_WITNESS) { + if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(_ALLOW_WITNESS)); + var offset = initialOffset || 0; -AbstractLevelDOWN.prototype._open = function (options, callback) { - process.nextTick(callback) -} + function writeSlice(slice) { + offset += slice.copy(buffer, offset); + } -AbstractLevelDOWN.prototype.close = function (callback) { - var self = this - var oldStatus = this.status + function writeUInt8(i) { + offset = buffer.writeUInt8(i, offset); + } - if (typeof callback !== 'function') { - throw new Error('close() requires a callback argument') - } + function writeUInt32(i) { + offset = buffer.writeUInt32LE(i, offset); + } - this.status = 'closing' - this._close(function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'closed' - callback() - }) -} + function writeInt32(i) { + offset = buffer.writeInt32LE(i, offset); + } -AbstractLevelDOWN.prototype._close = function (callback) { - process.nextTick(callback) -} + function writeUInt64(i) { + offset = bufferutils.writeUInt64LE(buffer, i, offset); + } -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - if (typeof options === 'function') { callback = options } + function writeVarInt(i) { + varuint.encode(i, buffer, offset); + offset += varuint.encode.bytes; + } - if (typeof callback !== 'function') { - throw new Error('get() requires a callback argument') - } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } - var err = this._checkKey(key, 'key') - if (err) return process.nextTick(callback, err) + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } - key = this._serializeKey(key) + writeInt32(this.version); - if (typeof options !== 'object') { options = {} } + var hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - options.asBuffer = options.asBuffer !== false + if (hasWitnesses) { + writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } - this._get(key, options, callback) -} + writeVarInt(this.ins.length); + this.ins.forEach(function (txIn) { + writeSlice(txIn.hash); + writeUInt32(txIn.index); + writeVarSlice(txIn.script); + writeUInt32(txIn.sequence); + }); + writeVarInt(this.outs.length); + this.outs.forEach(function (txOut) { + if (isOutput(txOut)) { + writeUInt64(txOut.value); + } else { + writeSlice(txOut.valueBuffer); + } -AbstractLevelDOWN.prototype._get = function (key, options, callback) { - process.nextTick(function () { callback(new Error('NotFound')) }) -} + writeVarSlice(txOut.script); + }); -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - if (typeof options === 'function') { callback = options } + if (hasWitnesses) { + this.ins.forEach(function (input) { + writeVector(input.witness); + }); + } - if (typeof callback !== 'function') { - throw new Error('put() requires a callback argument') - } + writeUInt32(this.locktime); // avoid slicing unless necessary - var err = this._checkKey(key, 'key') - if (err) return process.nextTick(callback, err) + if (initialOffset !== undefined) return buffer.slice(initialOffset, offset); + return buffer; + } + }], [{ + key: "fromBuffer", + value: function fromBuffer(buffer, _NO_STRICT) { + var offset = 0; - key = this._serializeKey(key) - value = this._serializeValue(value) + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } - if (typeof options !== 'object') { options = {} } + function readUInt32() { + var i = buffer.readUInt32LE(offset); + offset += 4; + return i; + } - this._put(key, value, options, callback) -} + function readInt32() { + var i = buffer.readInt32LE(offset); + offset += 4; + return i; + } -AbstractLevelDOWN.prototype._put = function (key, value, options, callback) { - process.nextTick(callback) -} + function readUInt64() { + var i = bufferutils.readUInt64LE(buffer, offset); + offset += 8; + return i; + } -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - if (typeof options === 'function') { callback = options } + function readVarInt() { + var vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; + } - if (typeof callback !== 'function') { - throw new Error('del() requires a callback argument') - } + function readVarSlice() { + return readSlice(readVarInt()); + } - var err = this._checkKey(key, 'key') - if (err) return process.nextTick(callback, err) + function readVector() { + var count = readVarInt(); + var vector = []; - key = this._serializeKey(key) + for (var i = 0; i < count; i++) { + vector.push(readVarSlice()); + } - if (typeof options !== 'object') { options = {} } + return vector; + } - this._del(key, options, callback) -} + var tx = new Transaction(); + tx.version = readInt32(); + var marker = buffer.readUInt8(offset); + var flag = buffer.readUInt8(offset + 1); + var hasWitnesses = false; -AbstractLevelDOWN.prototype._del = function (key, options, callback) { - process.nextTick(callback) -} + if (marker === Transaction.ADVANCED_TRANSACTION_MARKER && flag === Transaction.ADVANCED_TRANSACTION_FLAG) { + offset += 2; + hasWitnesses = true; + } -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) { return this._chainedBatch() } + var vinLen = readVarInt(); - if (typeof options === 'function') { callback = options } + for (var i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: readSlice(32), + index: readUInt32(), + script: readVarSlice(), + sequence: readUInt32(), + witness: EMPTY_WITNESS + }); + } - if (typeof array === 'function') { callback = array } + var voutLen = readVarInt(); - if (typeof callback !== 'function') { - throw new Error('batch(array) requires a callback argument') - } + for (var _i = 0; _i < voutLen; ++_i) { + tx.outs.push({ + value: readUInt64(), + script: readVarSlice() + }); + } - if (!Array.isArray(array)) { - return process.nextTick(callback, new Error('batch(array) requires an array argument')) - } + if (hasWitnesses) { + for (var _i2 = 0; _i2 < vinLen; ++_i2) { + tx.ins[_i2].witness = readVector(); + } // was this pointless? - if (!options || typeof options !== 'object') { options = {} } - var serialized = new Array(array.length) + if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data'); + } - for (var i = 0; i < array.length; i++) { - if (typeof array[i] !== 'object' || array[i] === null) { - return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`')) + tx.locktime = readUInt32(); + if (_NO_STRICT) return tx; + if (offset !== buffer.length) throw new Error('Transaction has unexpected data'); + return tx; } + }, { + key: "fromHex", + value: function fromHex(hex) { + return Transaction.fromBuffer(Buffer.from(hex, 'hex'), false); + } + }, { + key: "isCoinbaseHash", + value: function isCoinbaseHash(buffer) { + typeforce(types.Hash256bit, buffer); - var e = xtend(array[i]) + for (var i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } - if (e.type !== 'put' && e.type !== 'del') { - return process.nextTick(callback, new Error("`type` must be 'put' or 'del'")) + return true; } + }]); - var err = this._checkKey(e.key, 'key') - if (err) return process.nextTick(callback, err) + return Transaction; +}(); - e.key = this._serializeKey(e.key) +Transaction.DEFAULT_SEQUENCE = 0xffffffff; +Transaction.SIGHASH_ALL = 0x01; +Transaction.SIGHASH_NONE = 0x02; +Transaction.SIGHASH_SINGLE = 0x03; +Transaction.SIGHASH_ANYONECANPAY = 0x80; +Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; +Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; +exports.Transaction = Transaction; - if (e.type === 'put') { e.value = this._serializeValue(e.value) } +},{"./bufferutils":164,"./crypto":166,"./script":179,"./types":205,"typeforce":2945,"varuint-bitcoin":2969}],204:[function(require,module,exports){ +'use strict'; - serialized[i] = e - } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - this._batch(serialized, options, callback) -} +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -AbstractLevelDOWN.prototype._batch = function (array, options, callback) { - process.nextTick(callback) -} +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - options = cleanRangeOptions(options) +Object.defineProperty(exports, '__esModule', { + value: true +}); - options.reverse = !!options.reverse - options.keys = options.keys !== false - options.values = options.values !== false - options.limit = 'limit' in options ? options.limit : -1 - options.keyAsBuffer = options.keyAsBuffer !== false - options.valueAsBuffer = options.valueAsBuffer !== false +var baddress = require('./address'); - return options -} +var bufferutils_1 = require('./bufferutils'); -function cleanRangeOptions (options) { - var result = {} +var classify = require('./classify'); - for (var k in options) { - if (!hasOwnProperty.call(options, k)) continue - if (isRangeOption(k) && isEmptyRangeOption(options[k])) continue +var bcrypto = require('./crypto'); - result[k] = options[k] - } +var ECPair = require('./ecpair'); - return result -} +var networks = require('./networks'); -function isRangeOption (k) { - return rangeOptions.indexOf(k) !== -1 -} +var payments = require('./payments'); -function isEmptyRangeOption (v) { - return v === '' || v == null || isEmptyBuffer(v) -} +var bscript = require('./script'); -function isEmptyBuffer (v) { - return Buffer.isBuffer(v) && v.length === 0 -} +var script_1 = require('./script'); -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options !== 'object') { options = {} } - options = this._setupIteratorOptions(options) - return this._iterator(options) -} +var transaction_1 = require('./transaction'); -AbstractLevelDOWN.prototype._iterator = function (options) { - return new AbstractIterator(this) -} +var types = require('./types'); -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) -} +var typeforce = require('typeforce'); -AbstractLevelDOWN.prototype._serializeKey = function (key) { - return Buffer.isBuffer(key) ? key : String(key) +var SCRIPT_TYPES = classify.types; + +function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; } -AbstractLevelDOWN.prototype._serializeValue = function (value) { - if (value == null) return '' - return Buffer.isBuffer(value) || process.browser ? value : String(value) +function txIsTransaction(tx) { + return tx instanceof transaction_1.Transaction; } -AbstractLevelDOWN.prototype._checkKey = function (obj, type) { - if (obj === null || obj === undefined) { - return new Error(type + ' cannot be `null` or `undefined`') - } +var TransactionBuilder = +/*#__PURE__*/ +function () { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + function TransactionBuilder() { + var network = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : networks.bitcoin; + var maximumFeeRate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2500; - if (Buffer.isBuffer(obj) && obj.length === 0) { - return new Error(type + ' cannot be an empty Buffer') - } + _classCallCheck(this, TransactionBuilder); - if (String(obj) === '') { - return new Error(type + ' cannot be an empty String') + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; } -} -module.exports = AbstractLevelDOWN + _createClass(TransactionBuilder, [{ + key: "setLowR", + value: function setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); -},{"./abstract-chained-batch":227,"./abstract-iterator":228,"xtend":1356}],230:[function(require,module,exports){ -arguments[4][191][0].apply(exports,arguments) -},{"./abstract-chained-batch":227,"./abstract-iterator":228,"./abstract-leveldown":229,"dup":191}],231:[function(require,module,exports){ -/* Copyright (c) 2012-2017 LevelUP contributors - * See list at - * MIT License - * - */ + if (setting === undefined) { + setting = true; + } -var createError = require('errno').create -var LevelUPError = createError('LevelUPError') -var NotFoundError = createError('NotFoundError', LevelUPError) + this.__USE_LOW_R = setting; + return setting; + } + }, { + key: "setLockTime", + value: function setLockTime(locktime) { + typeforce(types.UInt32, locktime); // if any signatures exist, throw + + if (this.__INPUTS.some(function (input) { + if (!input.signatures) return false; + return input.signatures.some(function (s) { + return s !== undefined; + }); + })) { + throw new Error('No, this would invalidate signatures'); + } -NotFoundError.prototype.notFound = true -NotFoundError.prototype.status = 404 + this.__TX.locktime = locktime; + } + }, { + key: "setVersion", + value: function setVersion(version) { + typeforce(types.UInt32, version); // XXX: this might eventually become more complex depending on what the versions represent -module.exports = { - LevelUPError: LevelUPError, - InitializationError: createError('InitializationError', LevelUPError), - OpenError: createError('OpenError', LevelUPError), - ReadError: createError('ReadError', LevelUPError), - WriteError: createError('WriteError', LevelUPError), - NotFoundError: NotFoundError, - EncodingError: createError('EncodingError', LevelUPError) -} + this.__TX.version = version; + } + }, { + key: "addInput", + value: function addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); + } -},{"errno":258}],232:[function(require,module,exports){ -var once = require('once'); + var value; // is it a hex string? -var noop = function() {}; + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer.from(txHash, 'hex')); // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + var txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); + } -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; + return this.__addInputUnsafe(txHash, vout, { + sequence: sequence, + prevOutScript: prevOutScript, + value: value + }); + } + }, { + key: "addOutput", + value: function addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } // Attempt to get a script if it's a base58 or bech32 address string -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); + } - callback = once(callback || noop); + return this.__TX.addOutput(scriptPubKey, value); + } + }, { + key: "build", + value: function build() { + return this.__build(false); + } + }, { + key: "buildIncomplete", + value: function buildIncomplete() { + return this.__build(true); + } + }, { + key: "sign", + value: function sign(vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) { + var _this = this; - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network'); + if (!this.__INPUTS[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1.Transaction.SIGHASH_ALL; + if (this.__needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + var input = this.__INPUTS[vin]; // if redeemScript was previously provided, enforce consistency - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; + if (input.redeemScript !== undefined && redeemScript && !input.redeemScript.equals(redeemScript)) { + throw new Error('Inconsistent redeemScript'); + } - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; + var ourPubKey = keyPair.publicKey || keyPair.getPublicKey(); - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; + } - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; + if (!canSign(input)) { + var prepared = prepareInput(input, ourPubKey, redeemScript, witnessScript); // updates inline - var onerror = function(err) { - callback.call(stream, err); - }; + Object.assign(input, prepared); + } - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); - }; + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + } // ready to sign - var onrequest = function() { - stream.req.on('finish', onfinish); - }; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } + var signatureHash; - if (isChildProcess(stream)) stream.on('exit', onexit); + if (input.hasWitness) { + signatureHash = this.__TX.hashForWitnessV0(vin, input.signScript, input.value, hashType); + } else { + signatureHash = this.__TX.hashForSignature(vin, input.signScript, hashType); + } // enforce in order signing of public keys - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; + var signed = input.pubkeys.some(function (pubKey, i) { + if (!ourPubKey.equals(pubKey)) return false; + if (input.signatures[i]) throw new Error('Signature already exists'); // TODO: add tests -module.exports = eos; + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH'); + } -},{"once":1055}],233:[function(require,module,exports){ + var signature = keyPair.sign(signatureHash, _this.__USE_LOW_R); + input.signatures[i] = bscript.signature.encode(signature, hashType); + return true; + }); + if (!signed) throw new Error('Key pair cannot sign for this input'); + } + }, { + key: "__addInputUnsafe", + value: function __addInputUnsafe(txHash, vout, options) { + if (transaction_1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); + } -module.exports = require('./socket'); + var prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut); + var input = {}; // derive what we can from the scriptSig -/** - * Exports parser - * - * @api public - * - */ -module.exports.parser = require('engine.io-parser'); + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } // if an input value was given, retain it -},{"./socket":234,"engine.io-parser":254}],234:[function(require,module,exports){ -/** - * Module dependencies. - */ -var transports = require('./transports/index'); -var Emitter = require('component-emitter'); -var debug = require('debug')('engine.io-client:socket'); -var index = require('indexof'); -var parser = require('engine.io-parser'); -var parseuri = require('parseuri'); -var parseqs = require('parseqs'); + if (options.value !== undefined) { + input.value = options.value; + } // derive what we can from the previous transactions output script -/** - * Module exports. - */ -module.exports = Socket; + if (!input.prevOutScript && options.prevOutScript) { + var prevOutType; -/** - * Socket constructor. - * - * @param {String|Object} uri or options - * @param {Object} options - * @api public - */ + if (!input.pubkeys && !input.signatures) { + var expanded = expandOutput(options.prevOutScript); -function Socket (uri, opts) { - if (!(this instanceof Socket)) return new Socket(uri, opts); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; + } - opts = opts || {}; + prevOutType = expanded.type; + } - if (uri && 'object' === typeof uri) { - opts = uri; - uri = null; - } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); + } - if (uri) { - uri = parseuri(uri); - opts.hostname = uri.host; - opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } else if (opts.host) { - opts.hostname = parseuri(opts.host).host; - } + var vin = this.__TX.addInput(txHash, vout, options.sequence, options.scriptSig); - this.secure = null != opts.secure ? opts.secure - : (global.location && 'https:' === location.protocol); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; + } + }, { + key: "__build", + value: function __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } - if (opts.hostname && !opts.port) { - // if no port is specified manually, use the protocol default - opts.port = this.secure ? '443' : '80'; - } + var tx = this.__TX.clone(); // create script signatures from inputs - this.agent = opts.agent || false; - this.hostname = opts.hostname || - (global.location ? location.hostname : 'localhost'); - this.port = opts.port || (global.location && location.port - ? location.port - : (this.secure ? 443 : 80)); - this.query = opts.query || {}; - if ('string' === typeof this.query) this.query = parseqs.decode(this.query); - this.upgrade = false !== opts.upgrade; - this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; - this.forceJSONP = !!opts.forceJSONP; - this.jsonp = false !== opts.jsonp; - this.forceBase64 = !!opts.forceBase64; - this.enablesXDR = !!opts.enablesXDR; - this.timestampParam = opts.timestampParam || 't'; - this.timestampRequests = opts.timestampRequests; - this.transports = opts.transports || ['polling', 'websocket']; - this.transportOptions = opts.transportOptions || {}; - this.readyState = ''; - this.writeBuffer = []; - this.prevBufferLen = 0; - this.policyPort = opts.policyPort || 843; - this.rememberUpgrade = opts.rememberUpgrade || false; - this.binaryType = null; - this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; - this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; - if (true === this.perMessageDeflate) this.perMessageDeflate = {}; - if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { - this.perMessageDeflate.threshold = 1024; - } + this.__INPUTS.forEach(function (input, i) { + if (!input.prevOutType && !allowIncomplete) throw new Error('Transaction is not complete'); + var result = build(input.prevOutType, input, allowIncomplete); - // SSL options for Node.js client - this.pfx = opts.pfx || null; - this.key = opts.key || null; - this.passphrase = opts.passphrase || null; - this.cert = opts.cert || null; - this.ca = opts.ca || null; - this.ciphers = opts.ciphers || null; - this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized; - this.forceNode = !!opts.forceNode; + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } - // other options for Node.js client - var freeGlobal = typeof global === 'object' && global; - if (freeGlobal.global === freeGlobal) { - if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { - this.extraHeaders = opts.extraHeaders; - } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); - if (opts.localAddress) { - this.localAddress = opts.localAddress; + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); + } + } + + return tx; } - } + }, { + key: "__canModifyInputs", + value: function __canModifyInputs() { + return this.__INPUTS.every(function (input) { + if (!input.signatures) return true; + return input.signatures.every(function (signature) { + if (!signature) return true; + var hashType = signatureHashType(signature); // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + + return (hashType & transaction_1.Transaction.SIGHASH_ANYONECANPAY) !== 0; + }); + }); + } + }, { + key: "__needsOutputs", + value: function __needsOutputs(signingHashType) { + if (signingHashType === transaction_1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; + } // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK - // set on handshake - this.id = null; - this.upgrades = null; - this.pingInterval = null; - this.pingTimeout = null; - // set on heartbeat - this.pingIntervalTimer = null; - this.pingTimeoutTimer = null; + return this.__TX.outs.length === 0 && this.__INPUTS.some(function (input) { + if (!input.signatures) return false; + return input.signatures.some(function (signature) { + if (!signature) return false; // no signature, no issue - this.open(); -} + var hashType = signatureHashType(signature); + if (hashType & transaction_1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs -Socket.priorWebsocketSuccess = false; + return true; // SIGHASH_* does care + }); + }); + } + }, { + key: "__canModifyOutputs", + value: function __canModifyOutputs() { + var nInputs = this.__TX.ins.length; + var nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(function (input) { + if (input.signatures === undefined) return true; + return input.signatures.every(function (signature) { + if (!signature) return true; + var hashType = signatureHashType(signature); + var hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1.Transaction.SIGHASH_NONE) return true; + + if (hashTypeMod === transaction_1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } -/** - * Mix in `Emitter`. - */ + return false; + }); + }); + } + }, { + key: "__overMaximumFees", + value: function __overMaximumFees(bytes) { + // not all inputs will have .value defined + var incoming = this.__INPUTS.reduce(function (a, x) { + return a + (x.value >>> 0); + }, 0); // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + + + var outgoing = this.__TX.outs.reduce(function (a, x) { + return a + x.value; + }, 0); + + var fee = incoming - outgoing; + var feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; + } + }], [{ + key: "fromTransaction", + value: function fromTransaction(transaction, network) { + var txb = new TransactionBuilder(network); // Copy transaction fields + + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); // Copy outputs (done first to avoid signature invalidation) + + transaction.outs.forEach(function (txOut) { + txb.addOutput(txOut.script, txOut.value); + }); // Copy inputs + + transaction.ins.forEach(function (txIn) { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness + }); + }); // fix some things not possible through the public API -Emitter(Socket.prototype); + txb.__INPUTS.forEach(function (input, i) { + fixMultisigOrder(input, transaction, i); + }); -/** - * Protocol version. - * - * @api public - */ + return txb; + } + }]); -Socket.protocol = parser.protocol; // this is an int + return TransactionBuilder; +}(); -/** - * Expose deps for legacy compatibility - * and standalone browser access. - */ +exports.TransactionBuilder = TransactionBuilder; -Socket.Socket = Socket; -Socket.Transport = require('./transport'); -Socket.transports = require('./transports/index'); -Socket.parser = require('engine.io-parser'); +function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; -/** - * Creates transport of the given type. - * - * @param {String} transport name - * @return {Transport} - * @api private - */ + if (!type) { + var ssType = classify.input(scriptSig, true); + var wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; + } -Socket.prototype.createTransport = function (name) { - debug('creating transport "%s"', name); - var query = clone(this.query); + switch (type) { + case SCRIPT_TYPES.P2WPKH: + { + var _payments$p2wpkh = payments.p2wpkh({ + witness: witnessStack + }), + output = _payments$p2wpkh.output, + pubkey = _payments$p2wpkh.pubkey, + signature = _payments$p2wpkh.signature; - // append engine.io protocol identifier - query.EIO = parser.protocol; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature] + }; + } - // transport name - query.transport = name; + case SCRIPT_TYPES.P2PKH: + { + var _payments$p2pkh = payments.p2pkh({ + input: scriptSig + }), + _output = _payments$p2pkh.output, + _pubkey = _payments$p2pkh.pubkey, + _signature = _payments$p2pkh.signature; - // per-transport options - var options = this.transportOptions[name] || {}; + return { + prevOutScript: _output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [_pubkey], + signatures: [_signature] + }; + } - // session id if we already have one - if (this.id) query.sid = this.id; + case SCRIPT_TYPES.P2PK: + { + var _payments$p2pk = payments.p2pk({ + input: scriptSig + }), + _signature2 = _payments$p2pk.signature; - var transport = new transports[name]({ - query: query, - socket: this, - agent: options.agent || this.agent, - hostname: options.hostname || this.hostname, - port: options.port || this.port, - secure: options.secure || this.secure, - path: options.path || this.path, - forceJSONP: options.forceJSONP || this.forceJSONP, - jsonp: options.jsonp || this.jsonp, - forceBase64: options.forceBase64 || this.forceBase64, - enablesXDR: options.enablesXDR || this.enablesXDR, - timestampRequests: options.timestampRequests || this.timestampRequests, - timestampParam: options.timestampParam || this.timestampParam, - policyPort: options.policyPort || this.policyPort, - pfx: options.pfx || this.pfx, - key: options.key || this.key, - passphrase: options.passphrase || this.passphrase, - cert: options.cert || this.cert, - ca: options.ca || this.ca, - ciphers: options.ciphers || this.ciphers, - rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized, - perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate, - extraHeaders: options.extraHeaders || this.extraHeaders, - forceNode: options.forceNode || this.forceNode, - localAddress: options.localAddress || this.localAddress, - requestTimeout: options.requestTimeout || this.requestTimeout, - protocols: options.protocols || void (0) - }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [_signature2] + }; + } - return transport; -}; + case SCRIPT_TYPES.P2MS: + { + var _payments$p2ms = payments.p2ms({ + input: scriptSig, + output: scriptPubKey + }, { + allowIncomplete: true + }), + m = _payments$p2ms.m, + pubkeys = _payments$p2ms.pubkeys, + signatures = _payments$p2ms.signatures; -function clone (obj) { - var o = {}; - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - o[i] = obj[i]; - } + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys: pubkeys, + signatures: signatures, + maxSignatures: m + }; + } } - return o; -} -/** - * Initializes transport to use and starts probe. - * - * @api private - */ -Socket.prototype.open = function () { - var transport; - if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { - transport = 'websocket'; - } else if (0 === this.transports.length) { - // Emit error on next tick so it can be listened to - var self = this; - setTimeout(function () { - self.emit('error', 'No transports available'); - }, 0); - return; - } else { - transport = this.transports[0]; - } - this.readyState = 'opening'; + if (type === SCRIPT_TYPES.P2SH) { + var _payments$p2sh = payments.p2sh({ + input: scriptSig, + witness: witnessStack + }), + _output2 = _payments$p2sh.output, + redeem = _payments$p2sh.redeem; - // Retry with the next transport if the transport is disabled (jsonp: false) - try { - transport = this.createTransport(transport); - } catch (e) { - this.transports.shift(); - this.open(); - return; + var outputType = classify.output(redeem.output); + var expanded = expandInput(redeem.input, redeem.witness, outputType, redeem.output); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: _output2, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures + }; } - transport.open(); - this.setTransport(transport); -}; + if (type === SCRIPT_TYPES.P2WSH) { + var _payments$p2wsh = payments.p2wsh({ + input: scriptSig, + witness: witnessStack + }), + _output3 = _payments$p2wsh.output, + _redeem = _payments$p2wsh.redeem; -/** - * Sets the current transport. Disables the existing one (if any). - * - * @api private - */ + var _outputType = classify.output(_redeem.output); -Socket.prototype.setTransport = function (transport) { - debug('setting transport %s', transport.name); - var self = this; + var _expanded; - if (this.transport) { - debug('clearing existing transport %s', this.transport.name); - this.transport.removeAllListeners(); + if (_outputType === SCRIPT_TYPES.P2WPKH) { + _expanded = expandInput(_redeem.input, _redeem.witness, _outputType); + } else { + _expanded = expandInput(bscript.compile(_redeem.witness), [], _outputType, _redeem.output); + } + + if (!_expanded.prevOutType) return {}; + return { + prevOutScript: _output3, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: _redeem.output, + witnessScriptType: _expanded.prevOutType, + pubkeys: _expanded.pubkeys, + signatures: _expanded.signatures + }; } - // set up transport - this.transport = transport; + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig + }; +} // could be done in expandInput, but requires the original Transaction for hashForSignature - // set up transport listeners - transport - .on('drain', function () { - self.onDrain(); - }) - .on('packet', function (packet) { - self.onPacket(packet); - }) - .on('error', function (e) { - self.onError(e); - }) - .on('close', function () { - self.onClose('transport close'); - }); -}; -/** - * Probes a transport. - * - * @param {String} transport name - * @api private - */ +function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) return; + if (input.pubkeys.length === input.signatures.length) return; + var unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(function (pubKey) { + var keyPair = ECPair.fromPublicKey(pubKey); + var match; // check for a signature -Socket.prototype.probe = function (name) { - debug('probing transport "%s"', name); - var transport = this.createTransport(name, { probe: 1 }); - var failed = false; - var self = this; + unmatched.some(function (signature, i) { + // skip if undefined || OP_0 + if (!signature) return false; // TODO: avoid O(n) hashForSignature - Socket.priorWebsocketSuccess = false; + var parsed = bscript.signature.decode(signature); + var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType); // skip if signature does not match pubKey - function onTransportOpen () { - if (self.onlyBinaryUpgrades) { - var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; - failed = failed || upgradeLosesBinary; - } - if (failed) return; + if (!keyPair.verify(hash, parsed.signature)) return false; // remove matched signature from unmatched - debug('probe transport "%s" opened', name); - transport.send([{ type: 'ping', data: 'probe' }]); - transport.once('packet', function (msg) { - if (failed) return; - if ('pong' === msg.type && 'probe' === msg.data) { - debug('probe transport "%s" pong', name); - self.upgrading = true; - self.emit('upgrading', transport); - if (!transport) return; - Socket.priorWebsocketSuccess = 'websocket' === transport.name; + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); +} - debug('pausing current transport "%s"', self.transport.name); - self.transport.pause(function () { - if (failed) return; - if ('closed' === self.readyState) return; - debug('changing transport and sending upgrade packet'); +function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + var type = classify.output(script); - cleanup(); + switch (type) { + case SCRIPT_TYPES.P2PKH: + { + if (!ourPubKey) return { + type: type + }; // does our hash160(pubKey) match the output scripts? + + var pkh1 = payments.p2pkh({ + output: script + }).hash; + var pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { + type: type + }; + return { + type: type, + pubkeys: [ourPubKey], + signatures: [undefined] + }; + } - self.setTransport(transport); - transport.send([{ type: 'upgrade' }]); - self.emit('upgrade', transport); - transport = null; - self.upgrading = false; - self.flush(); + case SCRIPT_TYPES.P2WPKH: + { + if (!ourPubKey) return { + type: type + }; // does our hash160(pubKey) match the output scripts? + + var wpkh1 = payments.p2wpkh({ + output: script + }).hash; + var wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { + type: type + }; + return { + type: type, + pubkeys: [ourPubKey], + signatures: [undefined] + }; + } + + case SCRIPT_TYPES.P2PK: + { + var p2pk = payments.p2pk({ + output: script }); - } else { - debug('probe transport "%s" failed', name); - var err = new Error('probe error'); - err.transport = transport.name; - self.emit('upgradeError', err); + return { + type: type, + pubkeys: [p2pk.pubkey], + signatures: [undefined] + }; + } + + case SCRIPT_TYPES.P2MS: + { + var p2ms = payments.p2ms({ + output: script + }); + return { + type: type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(function () { + return undefined; + }), + maxSignatures: p2ms.m + }; } - }); } - function freezeTransport () { - if (failed) return; + return { + type: type + }; +} - // Any callback called by transport should be ignored since now - failed = true; +function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + var p2wsh = payments.p2wsh({ + redeem: { + output: witnessScript + } + }); + var p2wshAlt = payments.p2wsh({ + output: redeemScript + }); + var p2sh = payments.p2sh({ + redeem: { + output: redeemScript + } + }); + var p2shAlt = payments.p2sh({ + redeem: p2wsh + }); // enforces P2SH(P2WSH(...)) - cleanup(); + if (!p2wsh.hash.equals(p2wshAlt.hash)) throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) throw new Error('Redeem script inconsistent with prevOutScript'); + var expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) throw new Error(expanded.type + ' not supported as witnessScript (' + bscript.toASM(witnessScript) + ')'); - transport.close(); - transport = null; + if (input.signatures && input.signatures.some(function (x) { + return x !== undefined; + })) { + expanded.signatures = input.signatures; + } + + var signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript: redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript: witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript: signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures + }; } - // Handle any error that happens while probing - function onerror (err) { - var error = new Error('probe error: ' + err); - error.transport = transport.name; + if (redeemScript) { + var _p2sh = payments.p2sh({ + redeem: { + output: redeemScript + } + }); - freezeTransport(); + if (input.prevOutScript) { + var _p2shAlt; - debug('probe transport "%s" failed because of error: %s', name, err); + try { + _p2shAlt = payments.p2sh({ + output: input.prevOutScript + }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); + } - self.emit('upgradeError', error); - } + if (!_p2sh.hash.equals(_p2shAlt.hash)) throw new Error('Redeem script inconsistent with prevOutScript'); + } - function onTransportClose () { - onerror('transport closed'); - } + var _expanded2 = expandOutput(_p2sh.redeem.output, ourPubKey); - // When the socket is closed while we're probing - function onclose () { - onerror('socket closed'); - } + if (!_expanded2.pubkeys) throw new Error(_expanded2.type + ' not supported as redeemScript (' + bscript.toASM(redeemScript) + ')'); - // When the socket is upgraded while we're probing - function onupgrade (to) { - if (transport && to.name !== transport.name) { - debug('"%s" works - aborting "%s"', to.name, transport.name); - freezeTransport(); + if (input.signatures && input.signatures.some(function (x) { + return x !== undefined; + })) { + _expanded2.signatures = input.signatures; } - } - - // Remove all listeners on the transport and on self - function cleanup () { - transport.removeListener('open', onTransportOpen); - transport.removeListener('error', onerror); - transport.removeListener('close', onTransportClose); - self.removeListener('close', onclose); - self.removeListener('upgrading', onupgrade); - } - transport.once('open', onTransportOpen); - transport.once('error', onerror); - transport.once('close', onTransportClose); + var _signScript = redeemScript; - this.once('close', onclose); - this.once('upgrading', onupgrade); + if (_expanded2.type === SCRIPT_TYPES.P2WPKH) { + _signScript = payments.p2pkh({ + pubkey: _expanded2.pubkeys[0] + }).output; + } - transport.open(); -}; + return { + redeemScript: redeemScript, + redeemScriptType: _expanded2.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: _p2sh.output, + hasWitness: _expanded2.type === SCRIPT_TYPES.P2WPKH, + signScript: _signScript, + signType: _expanded2.type, + pubkeys: _expanded2.pubkeys, + signatures: _expanded2.signatures, + maxSignatures: _expanded2.maxSignatures + }; + } -/** - * Called when connection is deemed open. - * - * @api public - */ + if (witnessScript) { + var _p2wsh = payments.p2wsh({ + redeem: { + output: witnessScript + } + }); -Socket.prototype.onOpen = function () { - debug('socket open'); - this.readyState = 'open'; - Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; - this.emit('open'); - this.flush(); + if (input.prevOutScript) { + var _p2wshAlt = payments.p2wsh({ + output: input.prevOutScript + }); - // we check for `readyState` in case an `open` - // listener already closed the socket - if ('open' === this.readyState && this.upgrade && this.transport.pause) { - debug('starting upgrade probes'); - for (var i = 0, l = this.upgrades.length; i < l; i++) { - this.probe(this.upgrades[i]); + if (!_p2wsh.hash.equals(_p2wshAlt.hash)) throw new Error('Witness script inconsistent with prevOutScript'); } - } -}; -/** - * Handles a packet. - * - * @api private - */ + var _expanded3 = expandOutput(_p2wsh.redeem.output, ourPubKey); -Socket.prototype.onPacket = function (packet) { - if ('opening' === this.readyState || 'open' === this.readyState || - 'closing' === this.readyState) { - debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + if (!_expanded3.pubkeys) throw new Error(_expanded3.type + ' not supported as witnessScript (' + bscript.toASM(witnessScript) + ')'); - this.emit('packet', packet); + if (input.signatures && input.signatures.some(function (x) { + return x !== undefined; + })) { + _expanded3.signatures = input.signatures; + } - // Socket is live - any packet counts - this.emit('heartbeat'); + var _signScript2 = witnessScript; + if (_expanded3.type === SCRIPT_TYPES.P2WPKH) throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript: witnessScript, + witnessScriptType: _expanded3.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: _p2wsh.output, + hasWitness: true, + signScript: _signScript2, + signType: _expanded3.type, + pubkeys: _expanded3.pubkeys, + signatures: _expanded3.signatures, + maxSignatures: _expanded3.maxSignatures + }; + } - switch (packet.type) { - case 'open': - this.onHandshake(JSON.parse(packet.data)); - break; + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript'); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) throw new Error('PrevOutScript is ' + input.prevOutType + ', requires witnessScript'); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); - case 'pong': - this.setPing(); - this.emit('pong'); - break; + var _expanded4 = expandOutput(input.prevOutScript, ourPubKey); - case 'error': - var err = new Error('server error'); - err.code = packet.data; - this.onError(err); - break; + if (!_expanded4.pubkeys) throw new Error(_expanded4.type + ' not supported (' + bscript.toASM(input.prevOutScript) + ')'); - case 'message': - this.emit('data', packet.data); - this.emit('message', packet.data); - break; + if (input.signatures && input.signatures.some(function (x) { + return x !== undefined; + })) { + _expanded4.signatures = input.signatures; } - } else { - debug('packet received with socket readyState "%s"', this.readyState); - } -}; -/** - * Called upon handshake completion. - * - * @param {Object} handshake obj - * @api private - */ + var _signScript3 = input.prevOutScript; -Socket.prototype.onHandshake = function (data) { - this.emit('handshake', data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.onOpen(); - // In case open handler closes socket - if ('closed' === this.readyState) return; - this.setPing(); + if (_expanded4.type === SCRIPT_TYPES.P2WPKH) { + _signScript3 = payments.p2pkh({ + pubkey: _expanded4.pubkeys[0] + }).output; + } - // Prolong liveness of socket on heartbeat - this.removeListener('heartbeat', this.onHeartbeat); - this.on('heartbeat', this.onHeartbeat); -}; + return { + prevOutType: _expanded4.type, + prevOutScript: input.prevOutScript, + hasWitness: _expanded4.type === SCRIPT_TYPES.P2WPKH, + signScript: _signScript3, + signType: _expanded4.type, + pubkeys: _expanded4.pubkeys, + signatures: _expanded4.signatures, + maxSignatures: _expanded4.maxSignatures + }; + } -/** - * Resets ping timeout. - * - * @api private - */ + var prevOutScript = payments.p2pkh({ + pubkey: ourPubKey + }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript: prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined] + }; +} -Socket.prototype.onHeartbeat = function (timeout) { - clearTimeout(this.pingTimeoutTimer); - var self = this; - self.pingTimeoutTimer = setTimeout(function () { - if ('closed' === self.readyState) return; - self.onClose('ping timeout'); - }, timeout || (self.pingInterval + self.pingTimeout)); -}; +function build(type, input, allowIncomplete) { + var pubkeys = input.pubkeys || []; + var signatures = input.signatures || []; -/** - * Pings server every `this.pingInterval` and expects response - * within `this.pingTimeout` or closes connection. - * - * @api private - */ + switch (type) { + case SCRIPT_TYPES.P2PKH: + { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments.p2pkh({ + pubkey: pubkeys[0], + signature: signatures[0] + }); + } -Socket.prototype.setPing = function () { - var self = this; - clearTimeout(self.pingIntervalTimer); - self.pingIntervalTimer = setTimeout(function () { - debug('writing ping packet - expecting pong within %sms', self.pingTimeout); - self.ping(); - self.onHeartbeat(self.pingTimeout); - }, self.pingInterval); -}; + case SCRIPT_TYPES.P2WPKH: + { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments.p2wpkh({ + pubkey: pubkeys[0], + signature: signatures[0] + }); + } -/** -* Sends a ping packet. -* -* @api private -*/ + case SCRIPT_TYPES.P2PK: + { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments.p2pk({ + signature: signatures[0] + }); + } -Socket.prototype.ping = function () { - var self = this; - this.sendPacket('ping', function () { - self.emit('ping'); - }); -}; + case SCRIPT_TYPES.P2MS: + { + var m = input.maxSignatures; -/** - * Called on `drain` event - * - * @api private - */ + if (allowIncomplete) { + signatures = signatures.map(function (x) { + return x || script_1.OPS.OP_0; + }); + } else { + signatures = signatures.filter(function (x) { + return x; + }); + } // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) -Socket.prototype.onDrain = function () { - this.writeBuffer.splice(0, this.prevBufferLen); - // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - this.prevBufferLen = 0; + var validate = !allowIncomplete || m === signatures.length; + return payments.p2ms({ + m: m, + pubkeys: pubkeys, + signatures: signatures + }, { + allowIncomplete: allowIncomplete, + validate: validate + }); + } - if (0 === this.writeBuffer.length) { - this.emit('drain'); - } else { - this.flush(); + case SCRIPT_TYPES.P2SH: + { + var redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness + } + }); + } + + case SCRIPT_TYPES.P2WSH: + { + var _redeem2 = build(input.witnessScriptType, input, allowIncomplete); + + if (!_redeem2) return; + return payments.p2wsh({ + redeem: { + output: input.witnessScript, + input: _redeem2.input, + witness: _redeem2.witness + } + }); + } } -}; +} -/** - * Flush write buffers. - * - * @api private - */ +function canSign(input) { + return input.signScript !== undefined && input.signType !== undefined && input.pubkeys !== undefined && input.signatures !== undefined && input.signatures.length === input.pubkeys.length && input.pubkeys.length > 0 && (input.hasWitness === false || input.value !== undefined); +} -Socket.prototype.flush = function () { - if ('closed' !== this.readyState && this.transport.writable && - !this.upgrading && this.writeBuffer.length) { - debug('flushing %d packets in socket', this.writeBuffer.length); - this.transport.send(this.writeBuffer); - // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - this.prevBufferLen = this.writeBuffer.length; - this.emit('flush'); - } -}; +function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); +} -/** - * Sends a message. - * - * @param {String} message. - * @param {Function} callback function. - * @param {Object} options. - * @return {Socket} for chaining. - * @api public - */ +},{"./address":162,"./bufferutils":164,"./classify":165,"./crypto":166,"./ecpair":167,"./networks":169,"./payments":171,"./script":179,"./transaction":203,"./types":205,"typeforce":2945}],205:[function(require,module,exports){ +'use strict'; -Socket.prototype.write = -Socket.prototype.send = function (msg, options, fn) { - this.sendPacket('message', msg, options, fn); - return this; -}; +Object.defineProperty(exports, '__esModule', { + value: true +}); -/** - * Sends a packet. - * - * @param {String} packet type. - * @param {String} data. - * @param {Object} options. - * @param {Function} callback function. - * @api private - */ +var typeforce = require('typeforce'); -Socket.prototype.sendPacket = function (type, data, options, fn) { - if ('function' === typeof data) { - fn = data; - data = undefined; - } +var UINT31_MAX = Math.pow(2, 31) - 1; - if ('function' === typeof options) { - fn = options; - options = null; - } +function UInt31(value) { + return typeforce.UInt32(value) && value <= UINT31_MAX; +} - if ('closing' === this.readyState || 'closed' === this.readyState) { - return; - } +exports.UInt31 = UInt31; - options = options || {}; - options.compress = false !== options.compress; +function BIP32Path(value) { + return typeforce.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); +} - var packet = { - type: type, - data: data, - options: options - }; - this.emit('packetCreate', packet); - this.writeBuffer.push(packet); - if (fn) this.once('flush', fn); - this.flush(); +exports.BIP32Path = BIP32Path; + +BIP32Path.toJSON = function () { + return 'BIP32 derivation path'; }; -/** - * Closes the connection. - * - * @api private - */ +var SATOSHI_MAX = 21 * 1e14; -Socket.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.readyState = 'closing'; +function Satoshi(value) { + return typeforce.UInt53(value) && value <= SATOSHI_MAX; +} - var self = this; +exports.Satoshi = Satoshi; // external dependent types - if (this.writeBuffer.length) { - this.once('drain', function () { - if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - }); - } else if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - } +exports.ECPoint = typeforce.quacksLike('Point'); // exposed, external API - function close () { - self.onClose('forced close'); - debug('socket closing - telling transport to close'); - self.transport.close(); - } +exports.Network = typeforce.compile({ + messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String), + bip32: { + "public": typeforce.UInt32, + "private": typeforce.UInt32 + }, + pubKeyHash: typeforce.UInt8, + scriptHash: typeforce.UInt8, + wif: typeforce.UInt8 +}); +exports.Buffer256bit = typeforce.BufferN(32); +exports.Hash160bit = typeforce.BufferN(20); +exports.Hash256bit = typeforce.BufferN(32); +exports.Number = typeforce.Number; // tslint:disable-line variable-name + +exports.Array = typeforce.Array; +exports.Boolean = typeforce.Boolean; // tslint:disable-line variable-name + +exports.String = typeforce.String; // tslint:disable-line variable-name + +exports.Buffer = typeforce.Buffer; +exports.Hex = typeforce.Hex; +exports.maybe = typeforce.maybe; +exports.tuple = typeforce.tuple; +exports.UInt8 = typeforce.UInt8; +exports.UInt32 = typeforce.UInt32; +exports.Function = typeforce.Function; +exports.BufferN = typeforce.BufferN; +exports.Null = typeforce.Null; +exports.oneOf = typeforce.oneOf; + +},{"typeforce":2945}],206:[function(require,module,exports){ +"use strict"; - function cleanupAndClose () { - self.removeListener('upgrade', cleanupAndClose); - self.removeListener('upgradeError', cleanupAndClose); - close(); - } +module.exports = DHT; - function waitForUpgrade () { - // wait for upgrade to finish since we can't send packets while pausing a transport - self.once('upgrade', cleanupAndClose); - self.once('upgradeError', cleanupAndClose); - } +var bencode = require('bencode'); - return this; -}; +var Buffer = require('safe-buffer').Buffer; -/** - * Called upon transport error - * - * @api private - */ +var debug = require('debug')('bittorrent-dht'); -Socket.prototype.onError = function (err) { - debug('socket error %j', err); - Socket.priorWebsocketSuccess = false; - this.emit('error', err); - this.onClose('transport error', err); -}; +var equals = require('buffer-equals'); -/** - * Called upon transport close. - * - * @api private - */ +var EventEmitter = require('events').EventEmitter; -Socket.prototype.onClose = function (reason, desc) { - if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { - debug('socket close with reason: "%s"', reason); - var self = this; +var inherits = require('inherits'); - // clear timers - clearTimeout(this.pingIntervalTimer); - clearTimeout(this.pingTimeoutTimer); +var KBucket = require('k-bucket'); - // stop event from firing again for transport - this.transport.removeAllListeners('close'); +var krpc = require('k-rpc'); - // ensure transport won't stay open - this.transport.close(); +var LRU = require('lru'); - // ignore further transport communication - this.transport.removeAllListeners(); +var randombytes = require('randombytes'); - // set ready state - this.readyState = 'closed'; +var simpleSha1 = require('simple-sha1'); - // clear session id - this.id = null; +var PeerStore = require('./peer-store'); - // emit close event - this.emit('close', reason, desc); +var ROTATE_INTERVAL = 5 * 60 * 1000; // rotate secrets every 5 minutes - // clean buffers after, so users can still - // grab the buffers on `close` event - self.writeBuffer = []; - self.prevBufferLen = 0; - } -}; +var BUCKET_OUTDATED_TIMESPAN = 15 * 60 * 1000; // check nodes in bucket in 15 minutes old buckets -/** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} server upgrades - * @api private - * - */ +inherits(DHT, EventEmitter); -Socket.prototype.filterUpgrades = function (upgrades) { - var filteredUpgrades = []; - for (var i = 0, j = upgrades.length; i < j; i++) { - if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); - } - return filteredUpgrades; -}; +function DHT(opts) { + if (!(this instanceof DHT)) return new DHT(opts); + if (!opts) opts = {}; + var self = this; + this._tables = LRU({ + maxAge: ROTATE_INTERVAL, + max: opts.maxTables || 1000 + }); + this._values = LRU(opts.maxValues || 1000); + this._peers = new PeerStore({ + maxAge: opts.maxAge || Infinity, + max: opts.maxPeers || 10000 + }); + this._secrets = null; + this._hash = opts.hash || sha1; + this._hashLength = this._hash(Buffer.from('')).length; + this._rpc = opts.krpc || krpc(Object.assign({ + idLength: this._hashLength + }, opts)); -},{"./transport":235,"./transports/index":236,"component-emitter":157,"debug":182,"engine.io-parser":254,"indexof":399,"parseqs":1088,"parseuri":1089}],235:[function(require,module,exports){ -/** - * Module dependencies. - */ + this._rpc.on('query', onquery); -var parser = require('engine.io-parser'); -var Emitter = require('component-emitter'); + this._rpc.on('node', onnode); -/** - * Module exports. - */ + this._rpc.on('warning', onwarning); -module.exports = Transport; + this._rpc.on('error', onerror); -/** - * Transport abstract constructor. - * - * @param {Object} options. - * @api private - */ + this._rpc.on('listening', onlistening); -function Transport (opts) { - this.path = opts.path; - this.hostname = opts.hostname; - this.port = opts.port; - this.secure = opts.secure; - this.query = opts.query; - this.timestampParam = opts.timestampParam; - this.timestampRequests = opts.timestampRequests; - this.readyState = ''; - this.agent = opts.agent || false; - this.socket = opts.socket; - this.enablesXDR = opts.enablesXDR; + this._rotateSecrets(); - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - this.forceNode = opts.forceNode; + this._verify = opts.verify || null; + this._host = opts.host || null; + this._interval = setInterval(rotateSecrets, ROTATE_INTERVAL); + this._runningBucketCheck = false; + this._bucketCheckTimeout = null; + this._bucketOutdatedTimeSpan = opts.timeBucketOutdated || BUCKET_OUTDATED_TIMESPAN; + this.listening = false; + this.destroyed = false; + this.nodeId = this._rpc.id; + this.nodes = this._rpc.nodes; + this.nodes.on('ping', function (nodes, contact) { + self._debug('received ping', nodes, contact); - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - this.localAddress = opts.localAddress; -} + self._checkAndRemoveNodes(nodes, function (_, removed) { + if (removed) { + self._debug('added new node:', contact); -/** - * Mix in `Emitter`. - */ + self.addNode(contact); + } -Emitter(Transport.prototype); + self._debug('no node added, all other nodes ok'); + }); + }); + process.nextTick(bootstrap); + EventEmitter.call(this); -/** - * Emits an error. - * - * @param {String} str - * @return {Transport} for chaining - * @api public - */ + this._debug('new DHT %s', this.nodeId); -Transport.prototype.onError = function (msg, desc) { - var err = new Error(msg); - err.type = 'TransportError'; - err.description = desc; - this.emit('error', err); - return this; -}; + function onlistening() { + self.listening = true; -/** - * Opens the transport. - * - * @api public - */ + self._debug('listening %d', self.address().port); -Transport.prototype.open = function () { - if ('closed' === this.readyState || '' === this.readyState) { - this.readyState = 'opening'; - this.doOpen(); + self.emit('listening'); } - return this; -}; + function onquery(query, peer) { + self._onquery(query, peer); + } -/** - * Closes the transport. - * - * @api private - */ + function rotateSecrets() { + self._rotateSecrets(); + } -Transport.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.doClose(); - this.onClose(); + function bootstrap() { + if (!self.destroyed) self._bootstrap(opts.bootstrap !== false); } - return this; -}; + function onwarning(err) { + self.emit('warning', err); + } -/** - * Sends multiple packets. - * - * @param {Array} packets - * @api private - */ + function onerror(err) { + self.emit('error', err); + } -Transport.prototype.send = function (packets) { - if ('open' === this.readyState) { - this.write(packets); - } else { - throw new Error('Transport not open'); + function onnode(node) { + self.emit('node', node); } -}; +} -/** - * Called upon open - * - * @api private - */ +DHT.prototype._setBucketCheckInterval = function () { + var self = this; + var interval = 1 * 60 * 1000; // check age of bucket every minute -Transport.prototype.onOpen = function () { - this.readyState = 'open'; - this.writable = true; - this.emit('open'); -}; + this._runningBucketCheck = true; + queueNext(); -/** - * Called with data. - * - * @param {String} data - * @api private - */ + function checkBucket() { + var diff = Date.now() - self._rpc.nodes.metadata.lastChange; -Transport.prototype.onData = function (data) { - var packet = parser.decodePacket(data, this.socket.binaryType); - this.onPacket(packet); -}; + if (diff < self._bucketOutdatedTimeSpan) return queueNext(); -/** - * Called with a decoded packet. - */ + self._pingAll(function () { + if (self.destroyed) return; -Transport.prototype.onPacket = function (packet) { - this.emit('packet', packet); -}; + if (self.nodes.toArray().length < 1) { + // node is currently isolated, + // retry with initial bootstrap nodes + self._bootstrap(true); + } -/** - * Called upon close. - * - * @api private - */ + queueNext(); + }); + } -Transport.prototype.onClose = function () { - this.readyState = 'closed'; - this.emit('close'); + function queueNext() { + if (!self._runningBucketCheck || self.destroyed) return; + var nextTimeout = Math.floor(Math.random() * interval + interval / 2); + self._bucketCheckTimeout = setTimeout(checkBucket, nextTimeout); + } }; -},{"component-emitter":157,"engine.io-parser":254}],236:[function(require,module,exports){ -/** - * Module dependencies - */ - -var XMLHttpRequest = require('xmlhttprequest-ssl'); -var XHR = require('./polling-xhr'); -var JSONP = require('./polling-jsonp'); -var websocket = require('./websocket'); +DHT.prototype._pingAll = function (cb) { + this._checkAndRemoveNodes(this.nodes.toArray(), cb); +}; -/** - * Export transports. - */ +DHT.prototype.removeBucketCheckInterval = function () { + this._runningBucketCheck = false; + clearTimeout(this._bucketCheckTimeout); +}; -exports.polling = polling; -exports.websocket = websocket; +DHT.prototype.updateBucketTimestamp = function () { + this._rpc.nodes.metadata.lastChange = Date.now(); +}; -/** - * Polling transport polymorphic constructor. - * Decides on xhr vs jsonp based on feature detection. - * - * @api private - */ +DHT.prototype._checkAndRemoveNodes = function (nodes, cb) { + var self = this; -function polling (opts) { - var xhr; - var xd = false; - var xs = false; - var jsonp = false !== opts.jsonp; + this._checkNodes(nodes, function (_, node) { + if (node) self.removeNode(node.id); + cb(null, node); + }); +}; - if (global.location) { - var isSSL = 'https:' === location.protocol; - var port = location.port; +DHT.prototype._checkNodes = function (nodes, cb) { + var self = this; - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? 443 : 80; + function test(acc) { + if (!acc.length) { + return cb(null); } - xd = opts.hostname !== location.hostname || port !== opts.port; - xs = opts.secure !== isSSL; - } - - opts.xdomain = xd; - opts.xscheme = xs; - xhr = new XMLHttpRequest(opts); + var current = acc.pop(); - if ('open' in xhr && !opts.forceJSONP) { - return new XHR(opts); - } else { - if (!jsonp) throw new Error('JSONP disabled'); - return new JSONP(opts); - } -} + self._sendPing(current, function (err) { + if (!err) { + self.updateBucketTimestamp(); + return test(acc); + } // retry -},{"./polling-jsonp":237,"./polling-xhr":238,"./websocket":240,"xmlhttprequest-ssl":1354}],237:[function(require,module,exports){ -/** - * Module requirements. - */ + self._sendPing(current, function (er) { + if (err) { + return cb(null, current); + } -var Polling = require('./polling'); -var inherit = require('component-inherit'); + self.updateBucketTimestamp(); + return test(acc); + }); + }); + } -/** - * Module exports. - */ + test(nodes); +}; -module.exports = JSONPPolling; +DHT.prototype.addNode = function (node) { + var self = this; -/** - * Cached regular expressions. - */ + if (node.id) { + node.id = toBuffer(node.id); + var old = !!this._rpc.nodes.get(node.id); -var rNewline = /\n/g; -var rEscapedNewline = /\\n/g; + this._rpc.nodes.add(node); -/** - * Global JSONP callbacks. - */ + if (!old) { + this.emit('node', node); + this.updateBucketTimestamp(); + } -var callbacks; + return; + } -/** - * Noop. - */ + this._sendPing(node, function (_, node) { + if (node) self.addNode(node); + }); +}; -function empty () { } +DHT.prototype.removeNode = function (id) { + this._rpc.nodes.remove(toBuffer(id)); +}; -/** - * JSONP Polling constructor. - * - * @param {Object} opts. - * @api public - */ +DHT.prototype._sendPing = function (node, cb) { + var self = this; + var expectedId = node.id; -function JSONPPolling (opts) { - Polling.call(this, opts); + this._rpc.query(node, { + q: 'ping' + }, function (err, pong, node) { + if (err) return cb(err); - this.query = this.query || {}; + if (!pong.r || !pong.r.id || !Buffer.isBuffer(pong.r.id) || pong.r.id.length !== self._hashLength) { + return cb(new Error('Bad reply')); + } - // define global callbacks array if not present - // we do this here (lazily) to avoid unneeded global pollution - if (!callbacks) { - // we need to consider multiple engines in the same page - if (!global.___eio) global.___eio = []; - callbacks = global.___eio; - } + if (Buffer.isBuffer(expectedId) && !expectedId.equals(pong.r.id)) { + return cb(new Error('Unexpected node id')); + } - // callback identifier - this.index = callbacks.length; + self.updateBucketTimestamp(); + cb(null, { + id: pong.r.id, + host: node.host || node.address, + port: node.port + }); + }); +}; - // add callback to jsonp global +DHT.prototype.toJSON = function () { var self = this; - callbacks.push(function (msg) { - self.onData(msg); + var values = {}; + Object.keys(this._values.cache).forEach(function (key) { + var value = self._values.cache[key].value; + values[key] = { + v: value.v.toString('hex'), + id: value.id.toString('hex') + }; + if (value.seq != null) values[key].seq = value.seq; + if (value.sig != null) values[key].sig = value.sig.toString('hex'); + if (value.k != null) values[key].k = value.k.toString('hex'); }); + return { + nodes: this._rpc.nodes.toArray().map(toNode), + values: values + }; +}; - // append to query string - this.query.j = this.index; +DHT.prototype.put = function (opts, cb) { + if (Buffer.isBuffer(opts) || typeof opts === 'string') opts = { + v: opts + }; + var isMutable = !!opts.k; - // prevent spurious errors from being emitted when the window is unloaded - if (global.document && global.addEventListener) { - global.addEventListener('beforeunload', function () { - if (self.script) self.script.onerror = empty; - }, false); + if (opts.v === undefined) { + throw new Error('opts.v not given'); } -} -/** - * Inherits from Polling. - */ + if (opts.v.length >= 1000) { + throw new Error('v must be less than 1000 bytes in put()'); + } -inherit(JSONPPolling, Polling); + if (isMutable && opts.cas !== undefined && typeof opts.cas !== 'number') { + throw new Error('opts.cas must be an integer if provided'); + } -/* - * JSONP only supports binary as base64 encoded strings - */ + if (isMutable && !opts.k) { + throw new Error('opts.k ed25519 public key required for mutable put'); + } -JSONPPolling.prototype.supportsBinary = false; + if (isMutable && opts.k.length !== 32) { + throw new Error('opts.k ed25519 public key must be 32 bytes'); + } -/** - * Closes the socket. - * - * @api private - */ + if (isMutable && typeof opts.sign !== 'function' && !Buffer.isBuffer(opts.sig)) { + throw new Error('opts.sign function or options.sig signature is required for mutable put'); + } -JSONPPolling.prototype.doClose = function () { - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; + if (isMutable && opts.salt && opts.salt.length > 64) { + throw new Error('opts.salt is > 64 bytes long'); } - if (this.form) { - this.form.parentNode.removeChild(this.form); - this.form = null; - this.iframe = null; + if (isMutable && opts.seq === undefined) { + throw new Error('opts.seq not provided for a mutable update'); } - Polling.prototype.doClose.call(this); -}; + if (isMutable && typeof opts.seq !== 'number') { + throw new Error('opts.seq not an integer'); + } -/** - * Starts a poll cycle. - * - * @api private - */ + return this._put(opts, cb); +}; -JSONPPolling.prototype.doPoll = function () { - var self = this; - var script = document.createElement('script'); +DHT.prototype._put = function (opts, cb) { + if (!cb) cb = noop; + var isMutable = !!opts.k; + var v = typeof opts.v === 'string' ? Buffer.from(opts.v) : opts.v; + var key = isMutable ? this._hash(opts.salt ? Buffer.concat([opts.k, opts.salt]) : opts.k) : this._hash(bencode.encode(v)); - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; - } + var table = this._tables.get(key.toString('hex')); - script.async = true; - script.src = this.uri(); - script.onerror = function (e) { - self.onError('jsonp poll error', e); + if (!table) return this._preput(key, opts, cb); + var message = { + q: 'put', + a: { + id: this._rpc.id, + token: null, + // queryAll sets this + v: v + } }; - var insertAt = document.getElementsByTagName('script')[0]; - if (insertAt) { - insertAt.parentNode.insertBefore(script, insertAt); - } else { - (document.head || document.body).appendChild(script); + if (isMutable) { + if (typeof opts.cas === 'number') message.a.cas = opts.cas; + if (opts.salt) message.a.salt = opts.salt; + message.a.k = opts.k; + message.a.seq = opts.seq; + if (typeof opts.sign === 'function') message.a.sig = opts.sign(encodeSigData(message.a));else if (Buffer.isBuffer(opts.sig)) message.a.sig = opts.sig; } - this.script = script; - var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); + this._values.set(key.toString('hex'), message.a); - if (isUAgecko) { - setTimeout(function () { - var iframe = document.createElement('iframe'); - document.body.appendChild(iframe); - document.body.removeChild(iframe); - }, 100); - } -}; + this._rpc.queryAll(table.closest(key), message, null, function (err, n) { + if (err) return cb(err, key, n); + cb(null, key, n); + }); -/** - * Writes with a hidden iframe. - * - * @param {String} data to send - * @param {Function} called upon flush. - * @api private - */ + return key; +}; -JSONPPolling.prototype.doWrite = function (data, fn) { +DHT.prototype._preput = function (key, opts, cb) { var self = this; - if (!this.form) { - var form = document.createElement('form'); - var area = document.createElement('textarea'); - var id = this.iframeId = 'eio_iframe_' + this.index; - var iframe; - - form.className = 'socketio'; - form.style.position = 'absolute'; - form.style.top = '-1000px'; - form.style.left = '-1000px'; - form.target = id; - form.method = 'POST'; - form.setAttribute('accept-charset', 'utf-8'); - area.name = 'd'; - form.appendChild(area); - document.body.appendChild(form); + this._closest(key, { + q: 'get', + a: { + id: this._rpc.id, + target: key + } + }, null, function (err, n) { + if (err) return cb(err); + self.put(opts, cb); + }); - this.form = form; - this.area = area; + return key; +}; + +DHT.prototype.get = function (key, opts, cb) { + key = toBuffer(key); + + if (typeof opts === 'function') { + cb = opts; + opts = null; } - this.form.action = this.uri(); + if (!opts) opts = {}; + var verify = opts.verify || this._verify; + var hash = this._hash; + var value = this._values.get(key.toString('hex')) || null; - function complete () { - initIframe(); - fn(); + if (value) { + value = createGetResponse(this._rpc.id, null, value); + return process.nextTick(done); } - function initIframe () { - if (self.iframe) { - try { - self.form.removeChild(self.iframe); - } catch (e) { - self.onError('jsonp polling iframe removal error', e); - } + this._closest(key, { + q: 'get', + a: { + id: this._rpc.id, + target: key } + }, onreply, done); - try { - // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) - var html = '